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 |
|---|---|---|---|---|---|
""" This module provides access to higher level functions and
constants for ieee special values such as Not a Number (nan) and
infinity (inf).
>>> from numarray import *
The special values are designated using lower case as follows:
>> inf
inf
>> plus_inf
inf
>> minus_inf
-inf
>> nan
nan
>> plus_zero
0.0
>> minus_zero
-0.0
Note that the representation of IEEE special values is platform
dependent so your Python might, for instance, say 'Infinity' rather
than 'inf'. Below, inf is seen to arise as the result of floating
point division by 0 and nan is seen to arise from 0 divided by 0:
>>> a = arange(2.0)
>>> b = a/0
Warning: Encountered invalid numeric result(s) in divide
Warning: Encountered divide by zero(s) in divide
Here are the results for linux, but the repr problem causes this
example to fail for windows:
>> b
array([ nan, inf])
A curious property of nan is that it does not compare to *itself* as
equal (results also from linux):
>> b == nan
array([0, 0], type=Bool)
The isnan(), isinf(), and isfinite() functions return boolean arrays
which have the value True where the corresponding predicate holds.
These functions detect bit ranges and are therefore more robust than
simple equality checks.
>>> isnan(b)
array([1, 0], type=Bool)
>>> isinf(b)
array([0, 1], type=Bool)
>>> isfinite(b)
array([0, 0], type=Bool)
Array based indexing provides a convenient way to replace special values:
>>> b[isnan(b)] = 999
>>> b[isinf(b)] = 5
>>> b
array([ 999., 5.])
Here's an easy approach for compressing your data arrays to remove
NaNs:
>>> x, y = arange(10.), arange(10.); x[5] = nan; y[6] = nan;
>>> keep = ~isnan(x) & ~isnan(y)
>>> x[keep]
array([ 0., 1., 2., 3., 4., 7., 8., 9.])
>>> y[keep]
array([ 0., 1., 2., 3., 4., 7., 8., 9.])
=======================================================================
# >>> inf # the repr() of inf may vary from platform to platform
# inf
# >>> nan # the repr() of nan may vary from platform to platform
# nan
# Create a couple inf values in 4,4 array
>>> a=arange(16.0, shape=(4,4))
>>> a[2,3] = 0.0
>>> b = 1/a
Warning: Encountered divide by zero(s) in divide
# Locate the positions of the inf values
>>> getinf(b)
(array([0, 2]), array([0, 3]))
# Change the inf values to something else
>>> isinf(b)
array([[1, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]], type=Bool)
>>> isinf(inf)
1
>>> isinf(1)
0
>>> isinf(nan)
0
>>> isfinite(inf)
0
>>> isfinite(1)
1
>>> isfinite(nan)
0
>>> isnan(inf)
0
>>> isnan(1)
0
>>> isnan(nan)
1
>>> isfinite(b)
array([[0, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 0],
[1, 1, 1, 1]], type=Bool)
>>> a[getinf(b)] = 999
>>> a
array([[ 999., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 999.],
[ 12., 13., 14., 15.]])
# Set a bunch of locations to a special value
>>> a[0,1] = nan; a[1,2] = nan; a[2,3] = nan
>>> getnan(a)
(array([0, 1, 2]), array([1, 2, 3]))
IEEE Special Value support 32-bit
>>> import ieeespecial
>>> a = arange(5.0, type=Float32)
>>> b = (a*a)/a
Warning: Encountered invalid numeric result(s) in divide
>>> ieeemask(b, NAN)
array([1, 0, 0, 0, 0], type=Bool)
>>> ieeemask(b, NUMBER)
array([0, 1, 1, 1, 1], type=Bool)
>>> index(b, NAN)
(array([0]),)
>>> getnan(b)
(array([0]),)
>>> setnan(b, 42.0)
>>> b[0]
42.0
>>> a = arange(1.0, 6.0, type=Float32)
>>> b = a/zeros((5,), type=Float32)
Warning: Encountered divide by zero(s) in divide
>>> ieeemask(b, POS_INFINITY)
array([1, 1, 1, 1, 1], type=Bool)
>>> ieeemask(b, NEG_INFINITY)
array([0, 0, 0, 0, 0], type=Bool)
>>> ieeemask(b, INFINITY)
array([1, 1, 1, 1, 1], type=Bool)
>>> b = (-a)/zeros((5,), type=Float32)
Warning: Encountered divide by zero(s) in divide
>>> ieeemask(b, POS_INFINITY)
array([0, 0, 0, 0, 0], type=Bool)
>>> ieeemask(b, NEG_INFINITY)
array([1, 1, 1, 1, 1], type=Bool)
>>> ieeemask(b, INFINITY)
array([1, 1, 1, 1, 1], type=Bool)
>>> ieeemask(b, NUMBER)
array([0, 0, 0, 0, 0], type=Bool)
>>> ieeemask(array([0], type=Float32), POS_ZERO)
array([1], type=Bool)
>>> ieeemask(array([0], type=Float32), NEG_ZERO)
array([0], type=Bool)
>>> ieeemask(array([0], type=Float32), ZERO)
array([1], type=Bool)
>>> neginf = (array([-1],type=Float32)/array([0], type=Float32))
Warning: Encountered divide by zero(s) in divide
>>> negzero = array([1], type=Float32)/neginf
>>> ieeemask(negzero, POS_ZERO)
array([0], type=Bool)
>>> ieeemask(negzero, NEG_ZERO)
array([1], type=Bool)
>>> ieeemask(array([-0], type=Float32), ZERO)
array([1], type=Bool)
IEEE Special Value support 64-bit
>>> import ieeespecial
>>> a = arange(5.0, type=Float64)
>>> b = (a*a)/a
Warning: Encountered invalid numeric result(s) in divide
>>> ieeemask(b, NAN)
array([1, 0, 0, 0, 0], type=Bool)
>>> ieeemask(b, NUMBER)
array([0, 1, 1, 1, 1], type=Bool)
>>> index(b, NAN)
(array([0]),)
>>> getnan(b)
(array([0]),)
>>> setnan(b, 42.0)
>>> b[0]
42.0
>>> a = arange(1.0, 6.0, type=Float64)
>>> b = a/zeros((5,), type=Float64)
Warning: Encountered divide by zero(s) in divide
>>> ieeemask(b, POS_INFINITY)
array([1, 1, 1, 1, 1], type=Bool)
>>> ieeemask(b, NEG_INFINITY)
array([0, 0, 0, 0, 0], type=Bool)
>>> ieeemask(b, INFINITY)
array([1, 1, 1, 1, 1], type=Bool)
>>> b = (-a)/zeros((5,), type=Float64)
Warning: Encountered divide by zero(s) in divide
>>> ieeemask(b, POS_INFINITY)
array([0, 0, 0, 0, 0], type=Bool)
>>> ieeemask(b, NEG_INFINITY)
array([1, 1, 1, 1, 1], type=Bool)
>>> ieeemask(b, INFINITY)
array([1, 1, 1, 1, 1], type=Bool)
>>> ieeemask(b, NUMBER)
array([0, 0, 0, 0, 0], type=Bool)
>>> ieeemask(array([0], type=Float64), POS_ZERO)
array([1], type=Bool)
>>> ieeemask(array([0], type=Float64), NEG_ZERO)
array([0], type=Bool)
>>> ieeemask(array([0], type=Float64), ZERO)
array([1], type=Bool)
>>> neginf = (array([-1],type=Float64)/array([0], type=Float64))
Warning: Encountered divide by zero(s) in divide
>>> negzero = array([1], type=Float64)/neginf
>>> ieeemask(negzero, POS_ZERO)
array([0], type=Bool)
>>> ieeemask(negzero, NEG_ZERO)
array([1], type=Bool)
>>> ieeemask(array([-0], type=Float64), ZERO)
array([1], type=Bool)
"""
import numarrayall as _na
from numarray.ufunc import isnan
# Define *ieee special values*
_na.Error.pushMode(all="ignore")
plus_inf = inf = (_na.array(1.0)/_na.array(0.0))[()]
minus_inf = (_na.array(-1.0)/_na.array(0.0))[()]
nan = (_na.array(0.0)/_na.array(0.0))[()]
plus_zero = zero = 0.0
minus_zero = (_na.array(-1.0)*0.0)[()]
_na.Error.popMode()
# Define *mask condition bits*
class _IeeeMaskBit(_na.NumArray):
pass
def _BIT(x):
a = _na.array((1 << x), type=_na.Int32)
a.__class__ = _IeeeMaskBit
return a
POS_QUIET_NAN = _BIT(0)
NEG_QUIET_NAN = _BIT(1)
POS_SIGNAL_NAN = _BIT(2)
NEG_SIGNAL_NAN = _BIT(3)
POS_INFINITY = _BIT(4)
NEG_INFINITY = _BIT(5)
POS_DENORMALIZED = _BIT(6)
NEG_DENORMALIZED = _BIT(7)
POS_NORMALIZED = _BIT(8)
NEG_NORMALIZED = _BIT(9)
POS_ZERO = _BIT(10)
NEG_ZERO = _BIT(11)
INDETERM = _BIT(12)
BUG = _BIT(15)
NAN = POS_QUIET_NAN | NEG_QUIET_NAN | POS_SIGNAL_NAN | NEG_SIGNAL_NAN | INDETERM
INFINITY = POS_INFINITY | NEG_INFINITY
SPECIAL = NAN | INFINITY
NORMALIZED = POS_NORMALIZED | NEG_NORMALIZED
DENORMALIZED = POS_DENORMALIZED | NEG_DENORMALIZED
ZERO = POS_ZERO | NEG_ZERO
NUMBER = NORMALIZED | DENORMALIZED | ZERO
FINITE = NUMBER
def mask(a, m):
"""mask(a, m) returns the values of 'a' satisfying category 'm'.
mask does a parallel check for values which are not classifyable
by the categorization code, raising a RuntimeError exception if
any are found.
"""
a = _na.asarray(a)
if isinstance(a.type(), _na.IntegralType):
a = a.astype('Float64')
if isinstance(a.type(), _na.ComplexType):
f = _na.ieeemask(a.real, m) | _na.ieeemask(a.imag, m)
g = _na.ieeemask(a.real, BUG) | _na.ieeemask(a.imag, BUG)
else:
f = _na.ieeemask(a, m)
g = _na.ieeemask(a, BUG)
if _na.bitwise_or.reduce(_na.ravel(g)) != 0:
raise RuntimeError("Unclassifyable floating point values.")
if f.rank == 0:
f = f[()]
return f
def index(a, msk):
"""index returns the tuple of indices where the values satisfy 'mask'"""
return _na.nonzero(mask(a, msk))
def getinf(a):
"""getinf returns a tuple of indices of 'a' where the values are infinite."""
return index(a, INFINITY)
def setinf(a, value):
"""setinf sets elements of 'a' which are infinite to 'value' instead.
DEPRECATED: use 'a[getinf(a)] = value' instead.
"""
_na.put(a, getinf(a), value)
def isinf(a):
"""Idenitfies elements of 'a' which are infinity.
"""
return mask(a, INFINITY)
def getposinf(a):
"""getposinf returns a tuple of indices of 'a' where the values are +inf."""
return index(a, POS_INFINITY)
def getneginf(a):
"""getneginf returns a tuple of indices of 'a' where the values are -inf."""
return index(a, NEG_INFINITY)
def getnan(a):
"""getnan returns a tuple of indices of 'a' where the values are not-a-numbers"""
return _na.nonzero(isnan(a))
def setnan(a, value):
"""setnan sets elements of 'a' which are NANs to 'value' instead.
DEPRECATED: use 'a[getnan(a)] = value' instead.
"""
a[isnan(a)]= value
#def isnan(a):
# """Idenitfies elements of 'a' which are NANs, not a number.
# """
# return _na.isnan(a)
#
# This function has been replaced by isnan macro added to the numarray.ufunc module.
def isfinite(a):
"""Identifies elements of an array which are neither nan nor infinity."""
return _na.logical_not(isinf(a)| isnan(a))
def getbug(a):
"""getbug returns a tuple of indices of 'a' where the values are not classifyable."""
return index(a, BUG)
def test():
import doctest, ieeespecial
return doctest.testmod(ieeespecial)
| fxia22/ASM_xf | PythonD/site_python/numarray/ieeespecial.py | Python | gpl-2.0 | 9,913 |
package nodebox.ui;
import nodebox.client.Application;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ExceptionDialog extends JDialog implements ClipboardOwner {
private String log;
public ExceptionDialog(Frame owner, Throwable exception) {
this(owner, exception, "", true);
}
public ExceptionDialog(Frame owner, Throwable exception, String extraMessage) {
this(owner, exception, extraMessage, true);
}
public ExceptionDialog(Frame owner, Throwable exception, String extraMessage, boolean showQuitButton) {
super(owner, "Error", true);
Container container = getContentPane();
container.setLayout(new BorderLayout(0, 0));
JPanel innerPanel = new JPanel(new BorderLayout(10, 10));
innerPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel messageLabel = new JLabel("<html><b>Error: </b>" + exception.getMessage() + " " + extraMessage + "</html>");
JTextArea textArea = new JTextArea();
textArea.setFont(Theme.EDITOR_FONT);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
log = sw.toString();
textArea.setText(log);
textArea.setEditable(false);
textArea.setCaretPosition(0);
JScrollPane scrollPane = new JScrollPane(textArea);
innerPanel.add(messageLabel, BorderLayout.NORTH);
innerPanel.add(scrollPane, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 10, 10));
if (showQuitButton) {
JButton quitButton = new JButton("Quit");
quitButton.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
Application.getInstance().quit();
}
});
buttonPanel.add(quitButton);
}
JButton copyButton = new JButton("Copy");
copyButton.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
Clipboard clipboard = getToolkit().getSystemClipboard();
StringSelection ss = new StringSelection(log);
clipboard.setContents(ss, ExceptionDialog.this);
}
});
JButton closeButton = new JButton("Close");
closeButton.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
// Simple spacer hack
buttonPanel.add(copyButton);
buttonPanel.add(closeButton);
innerPanel.add(buttonPanel, BorderLayout.SOUTH);
container.add(innerPanel, BorderLayout.CENTER);
setSize(600, 400);
Window win = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
SwingUtils.centerOnScreen(this, win);
}
public void lostOwnership(Clipboard clipboard, Transferable transferable) {
// Do nothing
}
public static Throwable getRootCause(Throwable e) {
if (e.getCause() == null) return e;
if (e.getCause() == e) return e;
return getRootCause(e.getCause());
}
} | joansmith/nodebox | src/main/java/nodebox/ui/ExceptionDialog.java | Java | gpl-2.0 | 3,569 |
<?php
class EM_Location_Post_Admin{
function init(){
global $pagenow;
if($pagenow == 'post.php' || $pagenow == 'post-new.php' ){ //only needed if editing post
add_action('admin_head', array('EM_Location_Post_Admin','admin_head'));
}
//Meta Boxes
add_action('add_meta_boxes', array('EM_Location_Post_Admin','meta_boxes'));
//Save/Edit actions
add_filter('wp_insert_post_data',array('EM_Location_Post_Admin','wp_insert_post_data'),100,2); //validate post meta before saving is done
add_action('save_post',array('EM_Location_Post_Admin','save_post'),1,1); //set to 1 so metadata gets saved ASAP
add_action('before_delete_post',array('EM_Location_Post_Admin','before_delete_post'),10,1);
add_action('trashed_post',array('EM_Location_Post_Admin','trashed_post'),10,1);
add_action('untrash_post',array('EM_Location_Post_Admin','untrash_post'),10,1);
add_action('untrashed_post',array('EM_Location_Post_Admin','untrashed_post'),10,1);
//Notices
add_action('admin_notices',array('EM_Location_Post_Admin','admin_notices'));
add_action('post_updated_messages',array('EM_Location_Post_Admin','admin_notices_filter'),1,1);
}
function admin_head(){
global $post, $EM_Location;
if( !empty($post) && $post->post_type == EM_POST_TYPE_LOCATION ){
$EM_Location = em_get_location($post);
}
}
function admin_notices(){
//When editing
global $post, $EM_Notices;
if( !empty($post) && $post->post_type == EM_POST_TYPE_LOCATION){
}
}
function admin_notices_filter($messages){
//When editing
global $post, $EM_Notices;
if( $post->post_type == EM_POST_TYPE_LOCATION ){
if ( $EM_Notices->count_errors() > 0 ) {
unset($_GET['message']);
}
}
return $messages;
}
/**
* Hooks in just before a post is saves and does a quick post meta validation.
* This prevents the location from being temporarily published and firing hooks that indicate this before we come in on save_post and properly save data.
* @param array $data
* @param array $postarr
* @return array
*/
public static function wp_insert_post_data( $data, $postarr ){
global $wpdb, $EM_Event, $EM_Location, $EM_Notices;
$post_type = $data['post_type'];
$post_ID = !empty($postarr['ID']) ? $postarr['ID'] : false;
$is_post_type = $post_type == EM_POST_TYPE_LOCATION;
$saving_status = !in_array($data['post_status'], array('trash','auto-draft')) && !defined('DOING_AUTOSAVE');
$untrashing = $post_ID && defined('UNTRASHING_'.$post_ID);
if( !$untrashing && $is_post_type && $saving_status ){
if( !empty($_REQUEST['_emnonce']) && wp_verify_nonce($_REQUEST['_emnonce'], 'edit_location') ){
//this is only run if we know form data was submitted, hence the nonce
$EM_Location = em_get_location();
//Handle Errors by making post draft
$get_meta = $EM_Location->get_post_meta();
$validate_meta = $EM_Location->validate_meta();
if( !$get_meta || !$validate_meta ) $data['post_status'] = 'draft';
}
}
return $data;
}
/**
* Once the post is saved, saves EM meta data
* @param int $post_id
*/
function save_post($post_id){
global $wpdb, $EM_Location, $EM_Notices;
$saving_status = !in_array(get_post_status($post_id), array('trash','auto-draft')) && !defined('DOING_AUTOSAVE');
$is_post_type = get_post_type($post_id) == EM_POST_TYPE_LOCATION;
if(!defined('UNTRASHING_'.$post_id) && $is_post_type && $saving_status){
if( !empty($_REQUEST['_emnonce']) && wp_verify_nonce($_REQUEST['_emnonce'], 'edit_location')){
$EM_Location = em_get_location($post_id, 'post_id');
do_action('em_location_save_pre', $EM_Location);
$get_meta = $EM_Location->get_post_meta();
$save_meta = $EM_Location->save_meta();
//Handle Errors by making post draft
if( !$get_meta || !$save_meta ){
$EM_Location->set_status(null, true);
$EM_Notices->add_error( '<strong>'.sprintf(__('Your %s details are incorrect and cannot be published, please correct these errors first:','dbem'),__('location','dbem')).'</strong>', true); //Always seems to redirect, so we make it static
$EM_Notices->add_error($EM_Location->get_errors(), true); //Always seems to redirect, so we make it static
apply_filters('em_location_save', false , $EM_Location);
}else{
apply_filters('em_location_save', true , $EM_Location);
}
}else{
//do a quick and dirty update
$EM_Location = new EM_Location($post_id, 'post_id');
do_action('em_location_save_pre', $EM_Location);
//check for existence of index
$loc_truly_exists = $wpdb->get_var('SELECT location_id FROM '.EM_LOCATIONS_TABLE." WHERE location_id={$EM_Location->location_id}") == $EM_Location->location_id;
if(empty($EM_Location->location_id) || !$loc_truly_exists){ $EM_Location->save_meta(); }
//continue
$EM_Location->get_previous_status(); //before we save anything
$location_status = $EM_Location->get_status(true);
$where_array = array($EM_Location->location_name, $EM_Location->location_slug, $EM_Location->location_private, $EM_Location->location_id);
$sql = $wpdb->prepare("UPDATE ".EM_LOCATIONS_TABLE." SET location_name=%s, location_slug=%s, location_private=%d, location_status={$location_status} WHERE location_id=%d", $where_array);
$wpdb->query($sql);
apply_filters('em_location_save', true , $EM_Location);
}
}
}
function before_delete_post($post_id){
if(get_post_type($post_id) == EM_POST_TYPE_LOCATION){
$EM_Location = em_get_location($post_id,'post_id');
$EM_Location->delete_meta();
}
}
function trashed_post($post_id){
if(get_post_type($post_id) == EM_POST_TYPE_LOCATION){
global $EM_Notices;
$EM_Location = em_get_location($post_id,'post_id');
$EM_Location->set_status(-1);
$EM_Notices->remove_all(); //no validation/notices needed
}
}
function untrash_post($post_id){
if(get_post_type($post_id) == EM_POST_TYPE_LOCATION){
//set a constant so we know this event doesn't need 'saving'
if(!defined('UNTRASHING_'.$post_id)) define('UNTRASHING_'.$post_id, true);
}
}
function untrashed_post($post_id){
if(get_post_type($post_id) == EM_POST_TYPE_LOCATION){
global $EM_Notices;
$EM_Location = new EM_Location($post_id,'post_id');
$EM_Location->set_status($EM_Location->get_status());
$EM_Notices->remove_all(); //no validation/notices needed
}
}
function meta_boxes(){
add_meta_box('em-location-where', __('Where','dbem'), array('EM_Location_Post_Admin','meta_box_where'),EM_POST_TYPE_LOCATION, 'normal','high');
//add_meta_box('em-location-metadump', __('EM_Location Meta Dump','dbem'), array('EM_Location_Post_Admin','meta_box_metadump'),EM_POST_TYPE_LOCATION, 'normal','high');
if( get_option('dbem_location_attributes_enabled') ){
add_meta_box('em-location-attributes', __('Attributes','dbem'), array('EM_Location_Post_Admin','meta_box_attributes'),EM_POST_TYPE_LOCATION, 'normal','default');
}
}
function meta_box_metadump(){
global $post,$EM_Location;
echo "<pre>"; print_r(get_post_custom($post->ID)); echo "</pre>";
echo "<pre>"; print_r($EM_Location); echo "</pre>";
}
function meta_box_where(){
?><input type="hidden" name="_emnonce" value="<?php echo wp_create_nonce('edit_location'); ?>" /><?php
em_locate_template('forms/location/where.php',true);
}
function meta_box_attributes(){
em_locate_template('forms/location/attributes.php',true);
}
}
add_action('admin_init',array('EM_Location_Post_Admin','init')); | kunalsavlani/ufais | wp-content/plugins/events-manager/classes/em-location-post-admin.php | PHP | gpl-2.0 | 7,611 |
class FetchSessionsWorker < ApplicationWorker
def initialize(user_id, immediate = false)
@user_id = user_id
@immediate = immediate
user = User.find @user_id
super user.sessions_update.id
end
def perform
user = User.find @user_id
immediate = @immediate
user.sessions_rev_increment!
revision = user.sessions_rev
client = Client.new
%w(grades absences).each do |type|
# Fetch the sessions and sort them (1st year to last)
sessions = client.send "#{type}_sessions", user
sessions.sort! { |x, y| x.id > y.id ? 1 : -1 }
sessions.each do |session|
# Set the year of the current session
year = nil
(1..5).each do |i|
year = i if session.name.include? "#{i}A"
end
# We don't know how to process this session!
next if year.nil?
# Fetch the right corresponding user session
user_session = UserSession.where(user_id: user.id, year: year).first_or_create!
if user_session.send("#{type}_session").present? and user_session.send("#{type}_session") != session.id
user_session = UserSession.where(user_id: user.id, year: year, try: 2).first_or_create!
end
# Update the session id and save entity
user_session.send "#{type}_session=", session.id
user_session.save
# Update the revision number without touching the updated_at
user_session.update_column :update_number, revision
end
end
# Tidy up the user's sessions
UserSession.where(user_id: user.id).where("update_number != ?", revision).delete_all
# Schedule the grades and absences updates if asked
# We sort the session in desc chronological order to have the interesting grades and absences first
if immediate
user.sessions.sort { |x, y| y.year <=> x.year }.each do |session|
Delayed::Job.enqueue FetchDetailedGradesWorker.new(user.id, session.id),
priority: ApplicationWorker::PR_FETCH_DETAILED_GRADES,
queue: ApplicationWorker::QUEUE_DETAILED_GRADES
Delayed::Job.enqueue FetchAbsencesWorker.new(user.id, session.id),
priority: ApplicationWorker::PR_FETCH_ABSENCES,
queue: ApplicationWorker::QUEUE_REGULAR
end
end
end
end | ldavin/hei-connect-web | app/workers/fetch_sessions_worker.rb | Ruby | gpl-2.0 | 2,361 |
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2016 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#include "Device/Driver/KRT2.hpp"
#include "Device/Driver.hpp"
#include "Device/Port/Port.hpp"
#include "NMEA/Info.hpp"
#include "RadioFrequency.hpp"
#include "Thread/Cond.hxx"
#include "Thread/Mutex.hxx"
#include "Util/CharUtil.hxx"
#include "Util/StaticFifoBuffer.hxx"
#include "Util/Compiler.h"
#include <cstdint>
#include <stdio.h>
/**
* KRT2 device class.
*
* This class provides the interface to communicate with the KRT2 radio.
* The driver retransmits messages in case of a failure.
* See
* http://bugs.xcsoar.org/raw-attachment/ticket/2727/Remote_control_Interface_V12.pdf
* for the protocol specification.
*/
class KRT2Device final : public AbstractDevice {
static constexpr auto CMD_TIMEOUT = std::chrono::milliseconds(250); //!< Command timeout
static constexpr unsigned NR_RETRIES = 3; //!< Number of tries to send a command.
static constexpr char STX = 0x02; //!< Command start character.
static constexpr char ACK = 0x06; //!< Command acknowledged character.
static constexpr char NAK = 0x15; //!< Command not acknowledged character.
static constexpr char NO_RSP = 0; //!< No response received yet.
static constexpr size_t MAX_NAME_LENGTH = 8; //!< Max. radio station name length.
struct stx_msg {
uint8_t start = STX;
uint8_t command;
uint8_t mhz;
uint8_t khz;
char station[MAX_NAME_LENGTH];
uint8_t checksum;
};
//! Port the radio is connected to.
Port &port;
//! Expected length of the message just receiving.
size_t expected_msg_length{};
//! Buffer which receives the messages send from the radio.
StaticFifoBuffer<uint8_t, 256u> rx_buf;
//! Last response received from the radio.
uint8_t response;
//! Condition to signal that a response was received from the radio.
Cond rx_cond;
//! Mutex to be locked to access response.
Mutex response_mutex;
public:
/**
* Constructor of the radio device class.
*
* @param _port Port the radio is connected to.
*/
KRT2Device(Port &_port);
private:
/**
* Sends a message to the radio.
*
* @param msg Message to be send to the radio.
*/
bool Send(const uint8_t *msg, unsigned msg_size, OperationEnvironment &env);
/**
* Calculates the length of the message just receiving.
*
* @param data Pointer to the first character of the message.
* @param length Number of characters received.
* @return Expected message length.
*/
static size_t ExpectedMsgLength(const uint8_t *data, size_t length);
/**
* Calculates the length of the command message just receiving.
*
* @param code Command code received after the STX character.
* @return Expected message length after the code character.
*/
static size_t ExpectedMsgLengthSTX(uint8_t code);
/**
* Gets the displayable station name.
*
* @param name Name of the radio station.
* @return Name of the radio station (printable ASCII, MAX_NAME_LENGTH characters).
*/
static void GetStationName(char *station_name, const TCHAR *name);
/**
* Sends the frequency to the radio.
*
* Puts the frequency and the name of the station at the active or
* passive location on the radio.
* @param cmd Command char to set the location of the frequency.
* @param frequency Frequency of the radio station.
* @param name Name of the radio station.
* @param env Operation environment.
* @return true if the frequency is defined.
*/
bool PutFrequency(char cmd,
RadioFrequency frequency,
const TCHAR *name,
OperationEnvironment &env);
/**
* Handle an STX command from the radio.
*
* Handles STX commands from the radio, when these indicate a change in either
* active of passive frequency.
*/
static void HandleSTXCommand(const struct stx_msg * msg, struct NMEAInfo & info);
public:
/**
* Sets the active frequency on the radio.
*/
virtual bool PutActiveFrequency(RadioFrequency frequency,
const TCHAR *name,
OperationEnvironment &env) override;
/**
* Sets the standby frequency on the radio.
*/
virtual bool PutStandbyFrequency(RadioFrequency frequency,
const TCHAR *name,
OperationEnvironment &env) override;
/**
* Receives and handles data from the radio.
*
* The function parses messages send by the radio.
* Because all control characters (e.g. STX, ACK, NAK, ...)
* can be part of the payload of the messages, it is important
* to separate the messages to distinguish control characters
* from payload characters.
*
* If a response to a command is received, the function notifies
* the sender. This could trigger a retransmission in case of a
* failure.
*/
virtual bool DataReceived(const void *data, size_t length,
struct NMEAInfo &info) override;
};
/* Workaround for some GCC versions which don't inline the constexpr
despite being defined so in C++17, see
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0386r2.pdf */
#if GCC_OLDER_THAN(9,0)
constexpr std::chrono::milliseconds KRT2Device::CMD_TIMEOUT;
#endif
KRT2Device::KRT2Device(Port &_port)
: port(_port)
{
}
bool
KRT2Device::Send(const uint8_t *msg, unsigned msg_size,
OperationEnvironment &env)
{
//! Number of tries to send a message
unsigned retries = NR_RETRIES;
assert(msg_size > 0);
do {
{
const std::lock_guard<Mutex> lock(response_mutex);
response = NO_RSP;
}
// Send the message
if (!port.FullWrite(msg, msg_size, env, CMD_TIMEOUT))
return false;
// Wait for the response
uint8_t _response;
{
std::unique_lock<Mutex> lock(response_mutex);
rx_cond.wait_for(lock, std::chrono::milliseconds(CMD_TIMEOUT));
_response = response;
}
if (_response == ACK)
// ACK received, finish
return true;
// No ACK received, retry
retries--;
} while (retries);
return false;
}
bool
KRT2Device::DataReceived(const void *_data, size_t length,
struct NMEAInfo &info)
{
assert(_data != nullptr);
assert(length > 0);
const uint8_t *data = (const uint8_t *)_data;
const uint8_t *end = data + length;
do {
// Append new data to the buffer, as much as fits in there
auto range = rx_buf.Write();
if (rx_buf.IsFull()) {
// Overflow: reset buffer to recover quickly
rx_buf.Clear();
expected_msg_length = 0;
continue;
}
size_t nbytes = std::min(range.size, size_t(end - data));
memcpy(range.data, data, nbytes);
data += nbytes;
rx_buf.Append(nbytes);
for (;;) {
// Read data from buffer to handle the messages
range = rx_buf.Read();
if (range.empty())
break;
if (range.size < expected_msg_length)
break;
expected_msg_length = ExpectedMsgLength(range.data, range.size);
if (range.size >= expected_msg_length) {
switch (*(const uint8_t *) range.data) {
case 'S':
// Respond to connection query.
port.Write(0x01);
break;
case ACK:
case NAK:
// Received a response to a normal command (STX)
{
const std::lock_guard<Mutex> lock(response_mutex);
response = *(const uint8_t *) range.data;
// Signal the response to the TX thread
rx_cond.notify_one();
}
break;
case STX:
// Received a command from the radio (STX). Handle what we know.
{
const std::lock_guard<Mutex> lock(response_mutex);
const struct stx_msg * msg = (const struct stx_msg *) range.data;
HandleSTXCommand(msg, info);
}
default:
break;
}
// Message handled -> remove message
rx_buf.Consume(expected_msg_length);
expected_msg_length = 0;
// Received something from the radio -> the connection is alive
info.alive.Update(info.clock);
}
}
} while (data < end);
return true;
}
/**
The expected length of a received message may change,
when the first character is STX and the second character
is not received yet.
*/
size_t
KRT2Device::ExpectedMsgLength(const uint8_t *data, size_t length)
{
size_t expected_length;
assert(data != nullptr);
assert(length > 0);
if (data[0] == STX) {
if (length > 1) {
expected_length = 2 + ExpectedMsgLengthSTX(data[1]);
} else {
// minimum 2 chars
expected_length = 2;
}
} else
expected_length = 1;
return expected_length;
}
size_t
KRT2Device::ExpectedMsgLengthSTX(uint8_t code)
{
size_t expected_length;
switch (code) {
case 'U':
// Active frequency
case 'R':
// Standby frequency
expected_length = 11;
break;
case 'Z':
// Set frequency
expected_length = 12;
break;
case 'A':
// Set volume
expected_length = 4;
break;
case 'C':
// Exchange frequencies
case '8':
// Unknown code, received once after power up, STX '8'
case 'B':
// Low batt
case 'D':
// !Low batt
case 'E':
// PLL error
case 'W':
// PLL error
case 'F':
// !PLL error
case 'J':
// RX
case 'V':
// !RX
case 'K':
// TX
case 'L':
// Te
case 'Y':
// !TX || !RX
case 'O':
// Dual on
case 'o':
// Dual off
case 'M':
// RX on active frequency on (DUAL^)
case 'm':
// RX on active frequency off (DUAL)
expected_length = 0;
break;
default:
// Received unknown STX code
expected_length = 0;
break;
}
return expected_length;
}
void
KRT2Device::GetStationName(char *station_name, const TCHAR *name)
{
if(name == nullptr)
name = _T("");
size_t s_idx = 0; //!< Source name index
size_t d_idx = 0; //!< Destination name index
TCHAR c; //!< Character at source name index
while ((c = name[s_idx++])) {
// KRT2 supports printable ASCII only
if (IsPrintableASCII(c)) {
station_name[d_idx++] = (char) c;
if (d_idx == MAX_NAME_LENGTH)
break;
}
}
// Fill up the rest of the string with spaces
for (; d_idx < MAX_NAME_LENGTH; d_idx++) {
station_name[d_idx] = ' ';
}
}
void
KRT2Device::HandleSTXCommand(const struct stx_msg * msg, struct NMEAInfo & info)
{
if(msg->command != 'U' && msg->command != 'R' && msg->command != 'C') {
return;
}
if(msg->command == 'C') {
info.settings.swap_frequencies.Update(info.clock);
return;
}
if(msg->checksum != (msg->mhz ^ msg->khz)) {
return;
}
RadioFrequency freq;
freq.SetKiloHertz((msg->mhz * 1000) + (msg->khz * 5));
StaticString<MAX_NAME_LENGTH> freq_name;
freq_name.SetASCII(&(msg->station[0]), &(msg->station[MAX_NAME_LENGTH - 1]));
if(msg->command == 'U') {
info.settings.has_active_frequency.Update(info.clock);
info.settings.active_frequency = freq;
info.settings.active_freq_name = freq_name;
}
else if(msg->command == 'R') {
info.settings.has_standby_frequency.Update(info.clock);
info.settings.standby_frequency = freq;
info.settings.standby_freq_name = freq_name;
}
}
bool
KRT2Device::PutFrequency(char cmd,
RadioFrequency frequency,
const TCHAR *name,
OperationEnvironment &env)
{
if (frequency.IsDefined()) {
stx_msg msg;
msg.command = cmd;
msg.mhz = frequency.GetKiloHertz() / 1000;
msg.khz = (frequency.GetKiloHertz() % 1000) / 5;
GetStationName(msg.station, name);
msg.checksum = msg.mhz ^ msg.khz;
Send((uint8_t *) &msg, sizeof(msg), env);
return true;
}
return false;
}
bool
KRT2Device::PutActiveFrequency(RadioFrequency frequency,
const TCHAR *name,
OperationEnvironment &env)
{
return PutFrequency('U', frequency, name, env);
}
bool
KRT2Device::PutStandbyFrequency(RadioFrequency frequency,
const TCHAR *name,
OperationEnvironment &env)
{
return PutFrequency('R', frequency, name, env);
}
static Device *
KRT2CreateOnPort(const DeviceConfig &config, Port &comPort)
{
Device *dev = new KRT2Device(comPort);
return dev;
}
const struct DeviceRegister krt2_driver = {
_T("KRT2"),
_T("KRT2"),
DeviceRegister::NO_TIMEOUT
| DeviceRegister::RAW_GPS_DATA,
KRT2CreateOnPort,
};
| fb/XCSoar | src/Device/Driver/KRT2.cpp | C++ | gpl-2.0 | 13,477 |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark 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
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest04100")
public class BenchmarkTest04100 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
java.util.Map<String,String[]> map = request.getParameterMap();
String param = "";
if (!map.isEmpty()) {
param = map.get("foo")[0];
}
String bar = "safe!";
java.util.HashMap<String,Object> map33050 = new java.util.HashMap<String,Object>();
map33050.put("keyA-33050", "a_Value"); // put some stuff in the collection
map33050.put("keyB-33050", param.toString()); // put it in a collection
map33050.put("keyC", "another_Value"); // put some stuff in the collection
bar = (String)map33050.get("keyB-33050"); // get it back out
bar = (String)map33050.get("keyA-33050"); // get safe value back out
String sql = "SELECT * from USERS where USERNAME='foo' and PASSWORD='"+ bar +"'";
try {
java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
java.sql.ResultSet rs = statement.executeQuery( sql );
} catch (java.sql.SQLException e) {
throw new ServletException(e);
}
}
}
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest04100.java | Java | gpl-2.0 | 2,470 |
<?php
// Echo Open software Copyright © 2012 KnowledgeWorks Foundation
// ECHO OPEN trademark and logo are trademarks of New Technology Network LLC
// The Echo Open software is licensed under the GNU GPLv2. For licensing information // please contact New Technology Network Licensing at: // webmaster@newtechnetwork.org or 935 Clinton Street, Napa, CA 94559.
// $Id: views-view.tpl.php,v 1.13 2009/06/02 19:30:44 merlinofchaos Exp $
/**
* @file views-view.tpl.php
* Main view template
*
* Variables available:
* - $css_name: A css-safe version of the view name.
* - $header: The view header
* - $footer: The view footer
* - $rows: The results of the view query, if any
* - $empty: The empty text to display if the view is empty
* - $pager: The pager next/prev links to display, if any
* - $exposed: Exposed widget form/info to display
* - $feed_icon: Feed icon to display, if any
* - $more: A link to view more, if any
* - $admin_links: A rendered list of administrative links
* - $admin_links_raw: A list of administrative links suitable for theme('links')
*
* @ingroup views_templates
*/
?>
<div class="view view-<?php print $css_name; ?> view-id-<?php print $name; ?> view-display-id-<?php print $display_id; ?> view-dom-id-<?php print $dom_id; ?>">
<?php if ($admin_links): ?>
<div class="views-admin-links views-hide">
<?php print $admin_links; ?>
</div>
<?php endif; ?>
<?php if ($header): ?>
<div class="view-header">
<?php print $header; ?>
</div>
<?php endif; ?>
<?php if (false && $exposed): ?>
<div class="view-filters">
<?php print $exposed; ?>
</div>
<?php endif; ?>
<?php if ($attachment_before): ?>
<div class="attachment attachment-before">
<?php print $attachment_before; ?>
</div>
<?php endif; ?>
<?php if ($rows): ?>
<div class="view-content">
<?php print $rows; ?>
</div>
<?php elseif ($empty): ?>
<div class="view-empty">
<?php print $empty; ?>
</div>
<?php endif; ?>
<?php if ($pager): ?>
<?php print $pager; ?>
<?php endif; ?>
<?php if ($attachment_after): ?>
<div class="attachment attachment-after">
<?php print $attachment_after; ?>
</div>
<?php endif; ?>
<?php if ($more): ?>
<?php print $more; ?>
<?php endif; ?>
<?php if ($footer): ?>
<div class="view-footer">
<?php print $footer; ?>
</div>
<?php endif; ?>
<?php if ($feed_icon): ?>
<div class="feed-icon">
<?php print $feed_icon; ?>
</div>
<?php endif; ?>
</div> <?php /* class view */ ?>
| NewTechNetwork/EchoOpen | themes/Boldr/views-view--ntlp-ntn-resource-lib.tpl.php | PHP | gpl-2.0 | 2,661 |
<?php
/**
* Abstract FacetCache Factory.
*
* PHP version 7
*
* Copyright (C) Villanova University 2018.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Search_Base
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development Wiki
*/
namespace VuFind\Search\Base;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
/**
* Abstract FacetCache Factory.
*
* @category VuFind
* @package Search_Base
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development Wiki
*/
class FacetCacheFactory implements FactoryInterface
{
/**
* Create a results object.
*
* @param ContainerInterface $container Service manager
* @param string $name Name of results object to load (based
* on name of FacetCache service name)
*
* @return Results
*/
protected function getResults(ContainerInterface $container, $name)
{
return $container->get(\VuFind\Search\Results\PluginManager::class)
->get($name);
}
/**
* Create an object
*
* @param ContainerInterface $container Service manager
* @param string $requestedName Service being created
* @param null|array $options Extra options (optional)
*
* @return object
*
* @throws ServiceNotFoundException if unable to resolve the service.
* @throws ServiceNotCreatedException if an exception is raised when
* creating a service.
* @throws ContainerException if any other error occurs
*/
public function __invoke(ContainerInterface $container, $requestedName,
array $options = null
) {
if (!empty($options)) {
throw new \Exception('Unexpected options sent to factory.');
}
$parts = explode('\\', $requestedName);
$requestedNamespace = $parts[count($parts) - 2];
$results = $this->getResults($container, $requestedNamespace);
$cacheManager = $container->get(\VuFind\Cache\Manager::class);
$language = $container->get(\Zend\Mvc\I18n\Translator::class)->getLocale();
return new $requestedName($results, $cacheManager, $language);
}
}
| arto70/NDL-VuFind2 | module/VuFind/src/VuFind/Search/Base/FacetCacheFactory.php | PHP | gpl-2.0 | 3,084 |
/*
* Copyright (C) 2008-2019 TrinityCore <https://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "TransportMgr.h"
#include "DatabaseEnv.h"
#include "InstanceScript.h"
#include "Log.h"
#include "MapManager.h"
#include "MoveSplineInitArgs.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Spline.h"
#include "Transport.h"
TransportTemplate::~TransportTemplate()
{
}
TransportMgr::TransportMgr() { }
TransportMgr::~TransportMgr() { }
TransportMgr* TransportMgr::instance()
{
static TransportMgr instance;
return &instance;
}
void TransportMgr::Unload()
{
_transportTemplates.clear();
}
void TransportMgr::LoadTransportTemplates()
{
uint32 oldMSTime = getMSTime();
QueryResult result = WorldDatabase.Query("SELECT entry FROM gameobject_template WHERE type = 15 ORDER BY entry ASC");
if (!result)
{
TC_LOG_INFO("server.loading", ">> Loaded 0 transport templates. DB table `gameobject_template` has no transports!");
return;
}
uint32 count = 0;
do
{
Field* fields = result->Fetch();
uint32 entry = fields[0].GetUInt32();
GameObjectTemplate const* goInfo = sObjectMgr->GetGameObjectTemplate(entry);
if (goInfo == nullptr)
{
TC_LOG_ERROR("sql.sql", "Transport %u has no associated GameObjectTemplate from `gameobject_template` , skipped.", entry);
continue;
}
if (goInfo->moTransport.taxiPathId >= sTaxiPathNodesByPath.size())
{
TC_LOG_ERROR("sql.sql", "Transport %u (name: %s) has an invalid path specified in `gameobject_template`.`data0` (%u) field, skipped.", entry, goInfo->name.c_str(), goInfo->moTransport.taxiPathId);
continue;
}
// paths are generated per template, saves us from generating it again in case of instanced transports
TransportTemplate& transport = _transportTemplates[entry];
transport.entry = entry;
GeneratePath(goInfo, &transport);
// transports in instance are only on one map
if (transport.inInstance)
_instanceTransports[*transport.mapsUsed.begin()].insert(entry);
++count;
} while (result->NextRow());
TC_LOG_INFO("server.loading", ">> Loaded %u transport templates in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
void TransportMgr::LoadTransportAnimationAndRotation()
{
for (uint32 i = 0; i < sTransportAnimationStore.GetNumRows(); ++i)
if (TransportAnimationEntry const* anim = sTransportAnimationStore.LookupEntry(i))
AddPathNodeToTransport(anim->TransportEntry, anim->TimeSeg, anim);
for (uint32 i = 0; i < sTransportRotationStore.GetNumRows(); ++i)
if (TransportRotationEntry const* rot = sTransportRotationStore.LookupEntry(i))
AddPathRotationToTransport(rot->TransportEntry, rot->TimeSeg, rot);
}
class SplineRawInitializer
{
public:
SplineRawInitializer(Movement::PointsArray& points) : _points(points) { }
void operator()(uint8& mode, bool& cyclic, Movement::PointsArray& points, int& lo, int& hi) const
{
mode = Movement::SplineBase::ModeCatmullrom;
cyclic = false;
points.assign(_points.begin(), _points.end());
lo = 1;
hi = points.size() - 2;
}
Movement::PointsArray& _points;
};
void TransportMgr::GeneratePath(GameObjectTemplate const* goInfo, TransportTemplate* transport)
{
uint32 pathId = goInfo->moTransport.taxiPathId;
TaxiPathNodeList const& path = sTaxiPathNodesByPath[pathId];
std::vector<KeyFrame>& keyFrames = transport->keyFrames;
Movement::PointsArray splinePath, allPoints;
bool mapChange = false;
for (size_t i = 0; i < path.size(); ++i)
allPoints.push_back(G3D::Vector3(path[i]->LocX, path[i]->LocY, path[i]->LocZ));
// Add extra points to allow derivative calculations for all path nodes
allPoints.insert(allPoints.begin(), allPoints.front().lerp(allPoints[1], -0.2f));
allPoints.push_back(allPoints.back().lerp(allPoints[allPoints.size() - 2], -0.2f));
allPoints.push_back(allPoints.back().lerp(allPoints[allPoints.size() - 2], -1.0f));
SplineRawInitializer initer(allPoints);
TransportSpline orientationSpline;
orientationSpline.init_spline_custom(initer);
orientationSpline.initLengths();
for (size_t i = 0; i < path.size(); ++i)
{
if (!mapChange)
{
TaxiPathNodeEntry const* node_i = path[i];
if (i != path.size() - 1 && (node_i->Flags & 1 || node_i->MapID != path[i + 1]->MapID))
{
keyFrames.back().Teleport = true;
mapChange = true;
}
else
{
KeyFrame k(node_i);
G3D::Vector3 h;
orientationSpline.evaluate_derivative(i + 1, 0.0f, h);
k.InitialOrientation = Position::NormalizeOrientation(std::atan2(h.y, h.x) + float(M_PI));
keyFrames.push_back(k);
splinePath.push_back(G3D::Vector3(node_i->LocX, node_i->LocY, node_i->LocZ));
transport->mapsUsed.insert(k.Node->MapID);
}
}
else
mapChange = false;
}
if (splinePath.size() >= 2)
{
// Remove special catmull-rom spline points
if (!keyFrames.front().IsStopFrame() && !keyFrames.front().Node->ArrivalEventID && !keyFrames.front().Node->DepartureEventID)
{
splinePath.erase(splinePath.begin());
keyFrames.erase(keyFrames.begin());
}
if (!keyFrames.back().IsStopFrame() && !keyFrames.back().Node->ArrivalEventID && !keyFrames.back().Node->DepartureEventID)
{
splinePath.pop_back();
keyFrames.pop_back();
}
}
ASSERT(!keyFrames.empty());
if (transport->mapsUsed.size() > 1)
{
for (std::set<uint32>::const_iterator itr = transport->mapsUsed.begin(); itr != transport->mapsUsed.end(); ++itr)
ASSERT(!sMapStore.LookupEntry(*itr)->Instanceable());
transport->inInstance = false;
}
else
transport->inInstance = sMapStore.LookupEntry(*transport->mapsUsed.begin())->Instanceable();
// last to first is always "teleport", even for closed paths
keyFrames.back().Teleport = true;
const float speed = float(goInfo->moTransport.moveSpeed);
const float accel = float(goInfo->moTransport.accelRate);
const float accel_dist = 0.5f * speed * speed / accel;
transport->accelTime = speed / accel;
transport->accelDist = accel_dist;
int32 firstStop = -1;
int32 lastStop = -1;
// first cell is arrived at by teleportation :S
keyFrames[0].DistFromPrev = 0;
keyFrames[0].Index = 1;
if (keyFrames[0].IsStopFrame())
{
firstStop = 0;
lastStop = 0;
}
// find the rest of the distances between key points
// Every path segment has its own spline
size_t start = 0;
for (size_t i = 1; i < keyFrames.size(); ++i)
{
if (keyFrames[i - 1].Teleport || i + 1 == keyFrames.size())
{
size_t extra = !keyFrames[i - 1].Teleport ? 1 : 0;
std::shared_ptr<TransportSpline> spline = std::make_shared<TransportSpline>();
spline->init_spline(&splinePath[start], i - start + extra, Movement::SplineBase::ModeCatmullrom);
spline->initLengths();
for (size_t j = start; j < i + extra; ++j)
{
keyFrames[j].Index = j - start + 1;
keyFrames[j].DistFromPrev = float(spline->length(j - start, j + 1 - start));
if (j > 0)
keyFrames[j - 1].NextDistFromPrev = keyFrames[j].DistFromPrev;
keyFrames[j].Spline = spline;
}
if (keyFrames[i - 1].Teleport)
{
keyFrames[i].Index = i - start + 1;
keyFrames[i].DistFromPrev = 0.0f;
keyFrames[i - 1].NextDistFromPrev = 0.0f;
keyFrames[i].Spline = spline;
}
start = i;
}
if (keyFrames[i].IsStopFrame())
{
// remember first stop frame
if (firstStop == -1)
firstStop = i;
lastStop = i;
}
}
keyFrames.back().NextDistFromPrev = keyFrames.front().DistFromPrev;
if (firstStop == -1 || lastStop == -1)
firstStop = lastStop = 0;
// at stopping keyframes, we define distSinceStop == 0,
// and distUntilStop is to the next stopping keyframe.
// this is required to properly handle cases of two stopping frames in a row (yes they do exist)
float tmpDist = 0.0f;
for (size_t i = 0; i < keyFrames.size(); ++i)
{
int32 j = (i + lastStop) % keyFrames.size();
if (keyFrames[j].IsStopFrame() || j == lastStop)
tmpDist = 0.0f;
else
tmpDist += keyFrames[j].DistFromPrev;
keyFrames[j].DistSinceStop = tmpDist;
}
tmpDist = 0.0f;
for (int32 i = int32(keyFrames.size()) - 1; i >= 0; i--)
{
int32 j = (i + firstStop) % keyFrames.size();
tmpDist += keyFrames[(j + 1) % keyFrames.size()].DistFromPrev;
keyFrames[j].DistUntilStop = tmpDist;
if (keyFrames[j].IsStopFrame() || j == firstStop)
tmpDist = 0.0f;
}
for (size_t i = 0; i < keyFrames.size(); ++i)
{
float total_dist = keyFrames[i].DistSinceStop + keyFrames[i].DistUntilStop;
if (total_dist < 2 * accel_dist) // won't reach full speed
{
if (keyFrames[i].DistSinceStop < keyFrames[i].DistUntilStop) // is still accelerating
{
// calculate accel+brake time for this short segment
float segment_time = 2.0f * std::sqrt((keyFrames[i].DistUntilStop + keyFrames[i].DistSinceStop) / accel);
// substract acceleration time
keyFrames[i].TimeTo = segment_time - std::sqrt(2 * keyFrames[i].DistSinceStop / accel);
}
else // slowing down
keyFrames[i].TimeTo = std::sqrt(2 * keyFrames[i].DistUntilStop / accel);
}
else if (keyFrames[i].DistSinceStop < accel_dist) // still accelerating (but will reach full speed)
{
// calculate accel + cruise + brake time for this long segment
float segment_time = (keyFrames[i].DistUntilStop + keyFrames[i].DistSinceStop) / speed + (speed / accel);
// substract acceleration time
keyFrames[i].TimeTo = segment_time - std::sqrt(2 * keyFrames[i].DistSinceStop / accel);
}
else if (keyFrames[i].DistUntilStop < accel_dist) // already slowing down (but reached full speed)
keyFrames[i].TimeTo = std::sqrt(2 * keyFrames[i].DistUntilStop / accel);
else // at full speed
keyFrames[i].TimeTo = (keyFrames[i].DistUntilStop / speed) + (0.5f * speed / accel);
}
// calculate tFrom times from tTo times
float segmentTime = 0.0f;
for (size_t i = 0; i < keyFrames.size(); ++i)
{
int32 j = (i + lastStop) % keyFrames.size();
if (keyFrames[j].IsStopFrame() || j == lastStop)
segmentTime = keyFrames[j].TimeTo;
keyFrames[j].TimeFrom = segmentTime - keyFrames[j].TimeTo;
}
// calculate path times
keyFrames[0].ArriveTime = 0;
float curPathTime = 0.0f;
if (keyFrames[0].IsStopFrame())
{
curPathTime = float(keyFrames[0].Node->Delay);
keyFrames[0].DepartureTime = uint32(curPathTime * IN_MILLISECONDS);
}
for (size_t i = 1; i < keyFrames.size(); ++i)
{
curPathTime += keyFrames[i - 1].TimeTo;
if (keyFrames[i].IsStopFrame())
{
keyFrames[i].ArriveTime = uint32(curPathTime * IN_MILLISECONDS);
keyFrames[i - 1].NextArriveTime = keyFrames[i].ArriveTime;
curPathTime += float(keyFrames[i].Node->Delay);
keyFrames[i].DepartureTime = uint32(curPathTime * IN_MILLISECONDS);
}
else
{
curPathTime -= keyFrames[i].TimeTo;
keyFrames[i].ArriveTime = uint32(curPathTime * IN_MILLISECONDS);
keyFrames[i - 1].NextArriveTime = keyFrames[i].ArriveTime;
keyFrames[i].DepartureTime = keyFrames[i].ArriveTime;
}
}
keyFrames.back().NextArriveTime = keyFrames.back().DepartureTime;
transport->pathTime = keyFrames.back().DepartureTime;
}
void TransportMgr::AddPathNodeToTransport(uint32 transportEntry, uint32 timeSeg, TransportAnimationEntry const* node)
{
TransportAnimation& animNode = _transportAnimations[transportEntry];
if (animNode.TotalTime < timeSeg)
animNode.TotalTime = timeSeg;
animNode.Path[timeSeg] = node;
}
Transport* TransportMgr::CreateTransport(uint32 entry, ObjectGuid::LowType guid /*= 0*/, Map* map /*= nullptr*/)
{
// instance case, execute GetGameObjectEntry hook
if (map)
{
// SetZoneScript() is called after adding to map, so fetch the script using map
if (map->IsDungeon())
if (InstanceScript* instance = static_cast<InstanceMap*>(map)->GetInstanceScript())
entry = instance->GetGameObjectEntry(0, entry);
if (!entry)
return nullptr;
}
TransportTemplate const* tInfo = GetTransportTemplate(entry);
if (!tInfo)
{
TC_LOG_ERROR("sql.sql", "Transport %u will not be loaded, `transport_template` missing", entry);
return nullptr;
}
// create transport...
Transport* trans = new Transport();
// ...at first waypoint
TaxiPathNodeEntry const* startNode = tInfo->keyFrames.begin()->Node;
uint32 mapId = startNode->MapID;
float x = startNode->LocX;
float y = startNode->LocY;
float z = startNode->LocZ;
float o = tInfo->keyFrames.begin()->InitialOrientation;
// initialize the gameobject base
ObjectGuid::LowType guidLow = guid ? guid : sObjectMgr->GetGenerator<HighGuid::Mo_Transport>().Generate();
if (!trans->Create(guidLow, entry, mapId, x, y, z, o, 255))
{
delete trans;
return nullptr;
}
if (MapEntry const* mapEntry = sMapStore.LookupEntry(mapId))
{
if (mapEntry->Instanceable() != tInfo->inInstance)
{
TC_LOG_ERROR("entities.transport", "Transport %u (name: %s) attempted creation in instance map (id: %u) but it is not an instanced transport!", entry, trans->GetName().c_str(), mapId);
delete trans;
return nullptr;
}
}
// use preset map for instances (need to know which instance)
trans->SetMap(map ? map : sMapMgr->CreateMap(mapId, nullptr));
if (map && map->IsDungeon())
trans->m_zoneScript = map->ToInstanceMap()->GetInstanceScript();
// Passengers will be loaded once a player is near
HashMapHolder<Transport>::Insert(trans);
trans->GetMap()->AddToMap<Transport>(trans);
return trans;
}
void TransportMgr::SpawnContinentTransports()
{
if (_transportTemplates.empty())
return;
uint32 oldMSTime = getMSTime();
QueryResult result = WorldDatabase.Query("SELECT guid, entry FROM transports");
uint32 count = 0;
if (result)
{
do
{
Field* fields = result->Fetch();
ObjectGuid::LowType guid = fields[0].GetUInt32();
uint32 entry = fields[1].GetUInt32();
if (TransportTemplate const* tInfo = GetTransportTemplate(entry))
if (!tInfo->inInstance)
if (CreateTransport(entry, guid))
++count;
} while (result->NextRow());
}
TC_LOG_INFO("server.loading", ">> Spawned %u continent transports in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
void TransportMgr::CreateInstanceTransports(Map* map)
{
TransportInstanceMap::const_iterator mapTransports = _instanceTransports.find(map->GetId());
// no transports here
if (mapTransports == _instanceTransports.end() || mapTransports->second.empty())
return;
// create transports
for (std::set<uint32>::const_iterator itr = mapTransports->second.begin(); itr != mapTransports->second.end(); ++itr)
CreateTransport(*itr, 0, map);
}
TransportAnimationEntry const* TransportAnimation::GetAnimNode(uint32 time) const
{
auto itr = Path.lower_bound(time);
if (itr != Path.end())
return itr->second;
return nullptr;
}
TransportRotationEntry const* TransportAnimation::GetAnimRotation(uint32 time) const
{
auto itr = Rotations.lower_bound(time);
if (itr != Rotations.end())
return itr->second;
return nullptr;
}
| chaodhib/TrinityCore | src/server/game/Maps/TransportMgr.cpp | C++ | gpl-2.0 | 17,321 |
<?php
/*
Plugin Name: Responsive Full Width Background Slider
Plugin URI: http://wptreasure.com
Description: Responsive Full Width Background Slider is very attractive full width background slider for pages and posts as well as custom post types
Author: wptreasure
Version: 1.0.4
Author URI: http://wptreasure.com
*/
/*-------------------------------------------------*/
include_once('inc/rfwbs-settings.php');
include_once('inc/rfwbsFrontClass.php');
/*-------------------------------------------------*/
$rfwbsgobj = new rfwbsFront();
//ADD STYLE AND SCRIPT IN HEAD SECTION
add_action('admin_init','rfwbs_backend_script');
add_action('wp_enqueue_scripts','rfwbs_frontend_script');
// BACKEND SCRIPT
function rfwbs_backend_script(){
if(is_admin()){
if(isset($_GET['page']) && $_GET['page'] === 'rfwbs_slider') {
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_enqueue_script('jquery-ui-sortable');
wp_enqueue_script('jquery-ui-core');
wp_enqueue_script('jquery-ui-dialog');
wp_enqueue_script('rfwbs-admin-script', plugins_url('js/rfwbs_admin.js', __FILE__ ) );
wp_enqueue_style('thickbox');
wp_enqueue_style('rfwbs-admin-style',plugins_url('css/rfwbs-admin.css',__FILE__));
}
}
}
function rfwbs_frontend_script(){
if(!is_admin()){
wp_enqueue_script('jquery');
wp_enqueue_script('rfwbs-easing', plugins_url('js/jquery.easing.1.3.js', __FILE__ ),array('jquery'),'',1 );
wp_enqueue_script('rfwbs-animate', plugins_url('js/jquery.animate-enhanced.min.js', __FILE__ ),array('jquery'),'',1 );
wp_enqueue_script('rfwbs-superslides', plugins_url('js/jquery.superslides.js', __FILE__ ),array('jquery'),'',1 );
wp_enqueue_style('rfwbs-front-style',plugins_url('css/rfwbs_slider.css',__FILE__));
}
}
// 'ADMIN_MENU' FOR ADDING MENU IN ADMIN SECTION
add_action('admin_menu', 'rfwbs_plugin_admin_menu');
function rfwbs_plugin_admin_menu() {
add_menu_page('Responsive Full Width Background Slider', 'RFWB Slider','administrator', 'rfwbs_slider', 'rfwbs_backend_menu',plugins_url('inc/images/rfwbs-icon.png',__FILE__));
}
function rfwbs_settings()
{
$defaultSettings = array(
'rfwbs_pages' => 1,
'rfwbs_posts' => 1,
'rfwbs_frontpg' => 1,
'rfwbs_blogpg' => 1,
'rfwbs_cats' => 1,
'rfwbs_ctax' => 1,
'rfwbs_cposts' => 1,
'rfwbs_tags' => 1,
'rfwbs_date' => 1,
'rfwbs_author' => 1,
'rfwbs_search' => 1,
'rfwbs_sduration' => 8000,
'rfwbs_tspeed' => 700,
'rfwbs_play' => 'true',
'rfwbs_navigation'=> 1,
'rfwbs_toggle' => 1,
'rfwbs_bullet' => 1,
'rfwbs_controlpos'=> 0,
'rfwbs_animation' => 'fade',
'rfwbs_overlay' => 1,
'rfwbs_random' => 1,
'rfwbs_img' => array(
plugins_url('inc/images/slide1.jpg',__FILE__),
plugins_url('inc/images/slide2.jpg',__FILE__),
plugins_url('inc/images/slide3.jpg',__FILE__),
plugins_url('inc/images/slide4.jpg',__FILE__),
)
);
return $defaultSettings;
}
// RUNS WHEN PLUGIN IS ACTIVATED AND ADD OPTION IN wp_option TABLE -
//------------------------------------------------------------------
register_activation_hook(__FILE__,'rfwbs_plugin_install');
function rfwbs_plugin_install() {
add_option('rfwbs_settings', rfwbs_settings());
}
// GET RFWBS VERSION
function rfwbs_plugin_version(){
if ( ! function_exists( 'get_plugins' ) )
require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
$plugin_folder = get_plugins( '/' . plugin_basename( dirname( __FILE__ ) ) );
$plugin_file = basename( ( __FILE__ ) );
return $plugin_folder[$plugin_file]['Version'];
}
//ADD META BOX ---------------------
//----------------------------------
add_action('admin_init','rfwbsp_meta_box');
function rfwbsp_meta_box(){
if( function_exists( 'add_meta_box' ) ) {
$post_types=get_post_types();
foreach($post_types as $post_type) {
add_meta_box('rfwbsp_page', 'Responsive Full Width Background Slider', 'rfwbsp_status_meta_box', $post_type, 'side','high');
}
}
else{}
}
function rfwbsp_status_meta_box() {
global $post;
$custom = get_post_custom($post->ID);
$_rfwbsp_status = (isset($custom["_rfwbsp_status"][0])) ? $custom["_rfwbsp_status"][0] : 0;
?>
<input type="checkbox" name="_rfwbsp_status" id="_rfwbsp_status" <?php checked('true', $_rfwbsp_status); ?> value="true"/> <label for="_rfwbsp_status" style="color:#F90000;"><?php _e('Check it, to deactive RFWB Slider.','rfwbs'); ?> </label><br/>
<?php
}
// SAVE META BOX -------------------
//----------------------------------
add_action( 'save_post', 'rfwbsp_status_meta_box_save' );
function rfwbsp_status_meta_box_save()
{
$post_id = isset($_REQUEST['post_ID'])?$_REQUEST['post_ID']:'';
// Verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
$nonce = isset($_REQUEST['_wpnonce'])?$_REQUEST['_wpnonce']:'';
/*if (!wp_verify_nonce($nonce)) {
return $post_id;
}*/
// Verify if this is an auto save routine. If it is our form has not been submitted, so we dont want
// to do anything
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
// Check permissions to edit pages and/or posts
if ( isset($_POST['post_type']) && ('page' == $_POST['post_type'] || 'post' == $_POST['post_type'])) {
if ( !current_user_can( 'edit_page', $post_id ) || !current_user_can( 'edit_post', $post_id ))
return $post_id;
}
//we're authenticated: we need to find and save the data
$status = isset($_POST['_rfwbsp_status'])?$_POST['_rfwbsp_status']:'';
// save data in INVISIBLE custom field (note the "_" prefixing the custom fields' name
update_post_meta($post_id, '_rfwbsp_status', $status);
}
// DISPLAY CONDITIONS --------------
//----------------------------------
function rfwbs_responsiveslider()
{
global $rfwbsgobj,$post;
$rfwbs_settingOpts = get_option('rfwbs_settings');
if((is_page() && $rfwbs_settingOpts['rfwbs_pages'] && !is_front_page()) || (is_single() && $rfwbs_settingOpts['rfwbs_posts'] && !($rfwbsgobj->rfwbs_is_customPostTtype())) || ($rfwbsgobj->rfwbs_is_customPostTtype() && $rfwbs_settingOpts['rfwbs_cposts'])){
global $wp_query;
$rfwbs_pageId = $wp_query->post->ID;
$_rfwbsp_status = get_post_meta($rfwbs_pageId, '_rfwbsp_status', true);
if(!$_rfwbsp_status){
$rfwbsgobj->rfwbs_display();
}
}
elseif(is_front_page() && $rfwbs_settingOpts['rfwbs_frontpg']){
$rfwbsgobj->rfwbs_display();
}
elseif(is_home() && $rfwbs_settingOpts['rfwbs_blogpg']){
$rfwbsgobj->rfwbs_display();
}
elseif(is_category() && $rfwbs_settingOpts['rfwbs_cats']){
$rfwbsgobj->rfwbs_display();
}
elseif(is_tax() && $rfwbs_settingOpts['rfwbs_cposts']){
$rfwbsgobj->rfwbs_display();
}
elseif(is_tag() && $rfwbs_settingOpts['rfwbs_tags']){
$rfwbsgobj->rfwbs_display();
}
elseif(is_date() && $rfwbs_settingOpts['rfwbs_date']){
$rfwbsgobj->rfwbs_display();
}
elseif(is_author() && $rfwbs_settingOpts['rfwbs_author']){
$rfwbsgobj->rfwbs_display();
}
elseif(is_search() && $rfwbs_settingOpts['rfwbs_search']){
$rfwbsgobj->rfwbs_display();
}
}
add_action('wp_footer', 'rfwbs_responsiveslider');
?>
| toanpv92hy/toanpv_lines | wp-content/plugins/responsive-full-width-background-slider/rfwbs.php | PHP | gpl-2.0 | 7,300 |
#
# Copyright 2011-2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license
#
"""
hooking - various stuff useful when writing vdsm hooks
A vm hook expects domain xml in a file named by an environment variable called
_hook_domxml. The hook may change the xml, but the "china store rule" applies -
if you break something, you own it.
before_migration_destination hook receives the xml of the domain from the
source host. The xml of the domain at the destination will differ in various
details.
Return codes:
0 - the hook ended successfully.
1 - the hook failed, other hooks should be processed.
2 - the hook failed, no further hooks should be processed.
>2 - reserved
"""
from __future__ import absolute_import
from __future__ import division
import io
import json
import os
import sys
from xml.dom import minidom
from vdsm.common import hooks
from vdsm.common.commands import execCmd
from vdsm.common.conv import tobool
# make pyflakes happy
execCmd
tobool
def read_domxml():
with io.open(os.environ['_hook_domxml'], 'rb') as f:
return minidom.parseString(f.read().decode('utf-8'))
def write_domxml(domxml):
with io.open(os.environ['_hook_domxml'], 'wb') as f:
f.write(domxml.toxml(encoding='utf-8'))
def read_json():
with open(os.environ['_hook_json']) as f:
return json.loads(f.read())
def write_json(data):
with open(os.environ['_hook_json'], 'w') as f:
f.write(json.dumps(data))
def log(message):
sys.stderr.write(message + '\n')
def exit_hook(message, return_code=2):
"""
Exit the hook with a given message, which will be printed to the standard
error stream. A newline will be printed at the end.
The default return code is 2 for signaling that an error occurred.
"""
sys.stderr.write(message + "\n")
sys.exit(return_code)
def load_vm_launch_flags_from_file(vm_id):
return hooks.load_vm_launch_flags_from_file(vm_id)
def dump_vm_launch_flags_to_file(vm_id, flags):
hooks.dump_vm_launch_flags_to_file(vm_id, flags)
| nirs/vdsm | lib/vdsm/hook/hooking.py | Python | gpl-2.0 | 2,771 |
/*
* Copyright 2006-2018 The MZmine 2 Development Team
*
* This file is part of MZmine 2.
*
* MZmine 2 is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with MZmine 2; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.sf.mzmine.util.maths.similarity;
import java.util.Arrays;
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
import org.apache.commons.math3.stat.correlation.SpearmansCorrelation;
import org.apache.commons.math3.stat.regression.SimpleRegression;
import net.sf.mzmine.util.maths.Transform;
/**
* Different similarity measures such as COSINE SIMILARITY, PEARSON, SPEARMAN,...
*
* @author Robin Schmid (robinschmid@uni-muenster.de)
*
*/
public abstract class Similarity {
// Measures
public static final Similarity COSINE = new Similarity() {
@Override
public double calc(double[][] data) {
return dot(data) / (Math.sqrt(norm(data, 0)) * Math.sqrt(norm(data, 1)));
}
};
/**
* Log ratio proportionality
* https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1004075
*
*
*/
public static final Similarity LOG_VAR_PROPORTIONALITY = new Similarity() {
@Override
public double calc(double[][] data) {
double[] logratioXY = transform(ratio(data, 0, 1), Transform.LOG);
double[] logx = transform(col(data, 0), Transform.LOG);
return var(logratioXY) / var(logx);
}
};
/**
* Log ratio proportionality -1 to 1
* https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1004075
*
*
*/
public static final Similarity LOG_VAR_CONCORDANCE = new Similarity() {
@Override
public double calc(double[][] data) {
double[] logx = transform(col(data, 0), Transform.LOG);
double[] logy = transform(col(data, 1), Transform.LOG);
return 2 * covar(logx, logy) / (var(logx) + var(logy));
}
};
/**
* Spearmans correlation:
*/
public static final Similarity SPEARMANS_CORR = new Similarity() {
@Override
public double calc(double[][] data) {
SpearmansCorrelation corr = new SpearmansCorrelation();
return corr.correlation(col(data, 0), col(data, 1));
}
};
/**
* Pearson correlation:
*/
public static final Similarity PEARSONS_CORR = new Similarity() {
@Override
public double calc(double[][] data) {
PearsonsCorrelation corr = new PearsonsCorrelation();
return corr.correlation(col(data, 0), col(data, 1));
}
};
/**
* slope
*/
public static final Similarity REGRESSION_SLOPE = new Similarity() {
public SimpleRegression getRegression(double[][] data) {
SimpleRegression reg = new SimpleRegression();
reg.addData(data);
return reg;
}
@Override
public double calc(double[][] data) {
return getRegression(data).getSlope();
}
public double getSignificance(double[][] data) {
return getRegression(data).getSignificance();
}
};
/**
* slope
*/
public static final Similarity REGRESSION_SLOPE_SIGNIFICANCE = new Similarity() {
public SimpleRegression getRegression(double[][] data) {
SimpleRegression reg = new SimpleRegression();
reg.addData(data);
return reg;
}
@Override
public double calc(double[][] data) {
return getRegression(data).getSignificance();
}
};
/**
* Maximum fold-change
*
* @param data
* @return
*/
public static double maxFoldChange(double[][] data, final int i) {
double min = Arrays.stream(data).mapToDouble(d -> d[i]).min().getAsDouble();
double max = Arrays.stream(data).mapToDouble(d -> d[i]).max().getAsDouble();
return max / min;
}
// #############################################
// abstract methods
/**
*
* @param data data[dp][0,1]
* @return
*/
public abstract double calc(double[][] data);
public double[] col(double[][] data, int i) {
double[] v = new double[data.length];
for (int d = 0; d < data.length; d++) {
v[d] = data[d][i];
}
return v;
}
/**
* ratio of a/b
*
* @param data
* @param x
* @param y
* @return
*/
public double[] ratio(double[][] data, int a, int b) {
double[] v = new double[data.length];
for (int d = 0; d < data.length; d++) {
v[d] = data[d][a] / data[d][b];
}
return v;
}
public double[] transform(double[] data, Transform transform) {
double[] v = new double[data.length];
for (int d = 0; d < data.length; d++) {
v[d] = transform.transform(data[d]);
}
return v;
}
// ############################################
// COMMON METHODS
/**
* sum(x*y)
*
* @param data data[dp][x,y]
* @return
*/
public double dot(double[][] data) {
double sum = 0;
for (double[] val : data)
sum += val[0] * val[1];
return sum;
}
public double mean(double[][] data, int i) {
double m = 0;
for (int d = 0; d < data.length; d++) {
m = data[d][i];
}
return m / data.length;
}
public double var(double[][] data, int i) {
double mean = mean(data, i);
double var = 0;
for (int d = 0; d < data.length; d++) {
var += Math.pow(mean - data[d][i], 2);
}
return var / data.length;
}
public double mean(double[] data) {
double m = 0;
for (int d = 0; d < data.length; d++) {
m = data[d];
}
return m / data.length;
}
public double var(double[] data) {
double mean = mean(data);
double var = 0;
for (int d = 0; d < data.length; d++) {
var += Math.pow(mean - data[d], 2);
}
return var / (data.length - 1);
}
public double covar(double[] a, double[] b) {
double meanA = mean(a);
double meanB = mean(b);
double covar = 0;
for (int d = 0; d < a.length; d++) {
covar += (a[d] - meanA) * (b[d] - meanB);
}
return covar / (a.length - 1);
}
/**
* Sample variance n-1
*
* @param data
* @param i
* @return
*/
public double varN(double[][] data, int i) {
double mean = mean(data, i);
double var = 0;
for (int d = 0; d < data.length; d++) {
var += Math.pow(mean - data[d][i], 2);
}
return var / (data.length);
}
public double stdev(double[][] data, int i) {
return Math.sqrt(var(data, i));
}
public double stdevN(double[][] data, int i) {
return Math.sqrt(varN(data, i));
}
/**
* Euclidean norm (self dot product). sum(x*x)
*
* @param data data[dp][indexOfX]
* @param index
* @return
*/
public double norm(double[][] data, int index) {
double sum = 0;
for (double[] val : data)
sum += val[index] * val[index];
return sum;
}
}
| du-lab/mzmine2 | src/main/java/net/sf/mzmine/util/maths/similarity/Similarity.java | Java | gpl-2.0 | 7,559 |
var helper = require(__dirname + '/../test-helper');
//TODO would this be better served set at ../test-helper?
if(helper.args.native) {
Client = require(__dirname + '/../../lib/native');
helper.pg = helper.pg.native;
}
//export parent helper stuffs
module.exports = helper;
| elmerfreddy/nodejs-postgres | node_modules/pg/test/integration/test-helper.js | JavaScript | gpl-2.0 | 280 |
/*
Copyright (c) 2009-2018, Arvid Norberg
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 author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/config.hpp"
#include "libtorrent/aux_/socket_type.hpp"
#include "libtorrent/aux_/openssl.hpp"
#ifdef TORRENT_USE_OPENSSL
#include <boost/asio/ssl/context.hpp>
#include <boost/asio/ssl/rfc2818_verification.hpp>
#endif
#include "libtorrent/debug.hpp"
namespace libtorrent {
namespace aux {
bool is_ssl(socket_type const& s)
{
#ifdef TORRENT_USE_OPENSSL
#define CASE(t) case socket_type_int_impl<ssl_stream<t>>::value:
switch (s.type())
{
CASE(tcp::socket)
CASE(socks5_stream)
CASE(http_stream)
CASE(utp_stream)
return true;
default: return false;
}
#undef CASE
#else
TORRENT_UNUSED(s);
return false;
#endif
}
bool is_utp(socket_type const& s)
{
return s.get<utp_stream>() != nullptr
#ifdef TORRENT_USE_OPENSSL
|| s.get<ssl_stream<utp_stream>>() != nullptr
#endif
;
}
#if TORRENT_USE_I2P
bool is_i2p(socket_type const& s)
{
return s.get<i2p_stream>() != nullptr
#ifdef TORRENT_USE_OPENSSL
|| s.get<ssl_stream<i2p_stream>>() != nullptr
#endif
;
}
#endif
void setup_ssl_hostname(socket_type& s, std::string const& hostname, error_code& ec)
{
#if defined TORRENT_USE_OPENSSL
#ifdef TORRENT_MACOS_DEPRECATED_LIBCRYPTO
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#endif
// for SSL connections, make sure to authenticate the hostname
// of the certificate
#define CASE(t) case socket_type_int_impl<ssl_stream<t>>::value: \
s.get<ssl_stream<t>>()->set_verify_callback( \
boost::asio::ssl::rfc2818_verification(hostname), ec); \
ssl = s.get<ssl_stream<t>>()->native_handle(); \
ctx = SSL_get_SSL_CTX(ssl); \
break;
SSL* ssl = nullptr;
SSL_CTX* ctx = nullptr;
switch(s.type())
{
CASE(tcp::socket)
CASE(socks5_stream)
CASE(http_stream)
CASE(utp_stream)
}
#undef CASE
#if OPENSSL_VERSION_NUMBER >= 0x90812f
if (ctx)
{
aux::openssl_set_tlsext_servername_callback(ctx, nullptr);
aux::openssl_set_tlsext_servername_arg(ctx, nullptr);
}
#endif // OPENSSL_VERSION_NUMBER
#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
if (ssl)
{
aux::openssl_set_tlsext_hostname(ssl, hostname.c_str());
}
#endif
#else
TORRENT_UNUSED(ec);
TORRENT_UNUSED(hostname);
TORRENT_UNUSED(s);
#endif
#ifdef TORRENT_MACOS_DEPRECATED_LIBCRYPTO
#pragma clang diagnostic pop
#endif
}
#ifdef TORRENT_USE_OPENSSL
namespace {
void nop(std::shared_ptr<void>) {}
void on_close_socket(socket_type* s, std::shared_ptr<void>)
{
COMPLETE_ASYNC("on_close_socket");
error_code ec;
s->close(ec);
}
} // anonymous namespace
#endif
// the second argument is a shared pointer to an object that
// will keep the socket (s) alive for the duration of the async operation
void async_shutdown(socket_type& s, std::shared_ptr<void> holder)
{
error_code e;
#ifdef TORRENT_USE_OPENSSL
// for SSL connections, first do an async_shutdown, before closing the socket
#if defined TORRENT_ASIO_DEBUGGING
#define MAYBE_ASIO_DEBUGGING add_outstanding_async("on_close_socket");
#else
#define MAYBE_ASIO_DEBUGGING
#endif
static char const buffer[] = "";
// chasing the async_shutdown by a write is a trick to close the socket as
// soon as we've sent the close_notify, without having to wait to receive a
// response from the other end
// https://stackoverflow.com/questions/32046034/what-is-the-proper-way-to-securely-disconnect-an-asio-ssl-socket
#define CASE(t) case socket_type_int_impl<ssl_stream<t>>::value: \
MAYBE_ASIO_DEBUGGING \
s.get<ssl_stream<t>>()->async_shutdown(std::bind(&nop, holder)); \
s.get<ssl_stream<t>>()->async_write_some(boost::asio::buffer(buffer), std::bind(&on_close_socket, &s, holder)); \
break;
switch (s.type())
{
CASE(tcp::socket)
CASE(socks5_stream)
CASE(http_stream)
CASE(utp_stream)
default: s.close(e); break;
}
#undef CASE
#else
TORRENT_UNUSED(holder);
s.close(e);
#endif // TORRENT_USE_OPENSSL
}
void socket_type::destruct()
{
using tcp_socket = tcp::socket;
switch (m_type)
{
case 0: break;
case socket_type_int_impl<tcp::socket>::value:
get<tcp::socket>()->~tcp_socket();
break;
case socket_type_int_impl<socks5_stream>::value:
get<socks5_stream>()->~socks5_stream();
break;
case socket_type_int_impl<http_stream>::value:
get<http_stream>()->~http_stream();
break;
case socket_type_int_impl<utp_stream>::value:
get<utp_stream>()->~utp_stream();
break;
#if TORRENT_USE_I2P
case socket_type_int_impl<i2p_stream>::value:
get<i2p_stream>()->~i2p_stream();
break;
#endif
#ifdef TORRENT_USE_OPENSSL
case socket_type_int_impl<ssl_stream<tcp::socket>>::value:
get<ssl_stream<tcp::socket>>()->~ssl_stream();
break;
case socket_type_int_impl<ssl_stream<socks5_stream>>::value:
get<ssl_stream<socks5_stream>>()->~ssl_stream();
break;
case socket_type_int_impl<ssl_stream<http_stream>>::value:
get<ssl_stream<http_stream>>()->~ssl_stream();
break;
case socket_type_int_impl<ssl_stream<utp_stream>>::value:
get<ssl_stream<utp_stream>>()->~ssl_stream();
break;
#endif
default: TORRENT_ASSERT_FAIL();
}
m_type = 0;
}
void socket_type::construct(int type, void* userdata)
{
#ifndef TORRENT_USE_OPENSSL
TORRENT_UNUSED(userdata);
#endif
destruct();
switch (type)
{
case 0: break;
case socket_type_int_impl<tcp::socket>::value:
new (reinterpret_cast<tcp::socket*>(&m_data)) tcp::socket(m_io_service);
break;
case socket_type_int_impl<socks5_stream>::value:
new (reinterpret_cast<socks5_stream*>(&m_data)) socks5_stream(m_io_service);
break;
case socket_type_int_impl<http_stream>::value:
new (reinterpret_cast<http_stream*>(&m_data)) http_stream(m_io_service);
break;
case socket_type_int_impl<utp_stream>::value:
new (reinterpret_cast<utp_stream*>(&m_data)) utp_stream(m_io_service);
break;
#if TORRENT_USE_I2P
case socket_type_int_impl<i2p_stream>::value:
new (reinterpret_cast<i2p_stream*>(&m_data)) i2p_stream(m_io_service);
break;
#endif
#ifdef TORRENT_USE_OPENSSL
case socket_type_int_impl<ssl_stream<tcp::socket>>::value:
TORRENT_ASSERT(userdata);
new (reinterpret_cast<ssl_stream<tcp::socket>*>(&m_data)) ssl_stream<tcp::socket>(m_io_service
, *static_cast<ssl::context*>(userdata));
break;
case socket_type_int_impl<ssl_stream<socks5_stream>>::value:
TORRENT_ASSERT(userdata);
new (reinterpret_cast<ssl_stream<socks5_stream>*>(&m_data)) ssl_stream<socks5_stream>(m_io_service
, *static_cast<ssl::context*>(userdata));
break;
case socket_type_int_impl<ssl_stream<http_stream>>::value:
TORRENT_ASSERT(userdata);
new (reinterpret_cast<ssl_stream<http_stream>*>(&m_data)) ssl_stream<http_stream>(m_io_service
, *static_cast<ssl::context*>(userdata));
break;
case socket_type_int_impl<ssl_stream<utp_stream>>::value:
TORRENT_ASSERT(userdata);
new (reinterpret_cast<ssl_stream<utp_stream>*>(&m_data)) ssl_stream<utp_stream>(m_io_service
, *static_cast<ssl::context*>(userdata));
break;
#endif
default: TORRENT_ASSERT_FAIL();
}
m_type = type;
}
char const* socket_type::type_name() const
{
static char const* const names[] =
{
"uninitialized",
"TCP",
"Socks5",
"HTTP",
"uTP",
#if TORRENT_USE_I2P
"I2P",
#else
"",
#endif
#ifdef TORRENT_USE_OPENSSL
"SSL/TCP",
"SSL/Socks5",
"SSL/HTTP",
"SSL/uTP"
#else
"","","",""
#endif
};
return names[m_type];
}
io_service& socket_type::get_io_service() const
{ return m_io_service; }
socket_type::~socket_type()
{ destruct(); }
bool socket_type::is_open() const
{
if (m_type == 0) return false;
TORRENT_SOCKTYPE_FORWARD_RET(is_open(), false)
}
void socket_type::open(protocol_type const& p, error_code& ec)
{ TORRENT_SOCKTYPE_FORWARD(open(p, ec)) }
void socket_type::close(error_code& ec)
{
if (m_type == 0) return;
TORRENT_SOCKTYPE_FORWARD(close(ec))
}
void socket_type::set_close_reason(close_reason_t code)
{
switch (m_type)
{
case socket_type_int_impl<utp_stream>::value:
get<utp_stream>()->set_close_reason(code);
break;
#ifdef TORRENT_USE_OPENSSL
case socket_type_int_impl<ssl_stream<utp_stream>>::value:
get<ssl_stream<utp_stream>>()->lowest_layer().set_close_reason(code);
break;
#endif
default: break;
}
}
close_reason_t socket_type::get_close_reason()
{
switch (m_type)
{
case socket_type_int_impl<utp_stream>::value:
return get<utp_stream>()->get_close_reason();
#ifdef TORRENT_USE_OPENSSL
case socket_type_int_impl<ssl_stream<utp_stream>>::value:
return get<ssl_stream<utp_stream>>()->lowest_layer().get_close_reason();
#endif
default: return close_reason_t::none;
}
}
socket_type::endpoint_type socket_type::local_endpoint(error_code& ec) const
{ TORRENT_SOCKTYPE_FORWARD_RET(local_endpoint(ec), socket_type::endpoint_type()) }
socket_type::endpoint_type socket_type::remote_endpoint(error_code& ec) const
{ TORRENT_SOCKTYPE_FORWARD_RET(remote_endpoint(ec), socket_type::endpoint_type()) }
void socket_type::bind(endpoint_type const& endpoint, error_code& ec)
{ TORRENT_SOCKTYPE_FORWARD(bind(endpoint, ec)) }
std::size_t socket_type::available(error_code& ec) const
{ TORRENT_SOCKTYPE_FORWARD_RET(available(ec), 0) }
int socket_type::type() const { return m_type; }
#ifndef BOOST_NO_EXCEPTIONS
void socket_type::open(protocol_type const& p)
{ TORRENT_SOCKTYPE_FORWARD(open(p)) }
void socket_type::close()
{
if (m_type == 0) return;
TORRENT_SOCKTYPE_FORWARD(close())
}
socket_type::endpoint_type socket_type::local_endpoint() const
{ TORRENT_SOCKTYPE_FORWARD_RET(local_endpoint(), socket_type::endpoint_type()) }
socket_type::endpoint_type socket_type::remote_endpoint() const
{ TORRENT_SOCKTYPE_FORWARD_RET(remote_endpoint(), socket_type::endpoint_type()) }
void socket_type::bind(endpoint_type const& endpoint)
{ TORRENT_SOCKTYPE_FORWARD(bind(endpoint)) }
std::size_t socket_type::available() const
{ TORRENT_SOCKTYPE_FORWARD_RET(available(), 0) }
#endif
}
}
| pavel-pimenov/flylinkdc-r5xx | libtorrent/src/socket_type.cpp | C++ | gpl-2.0 | 11,580 |
package pw.oxcafebabe.marcusant.eventbus;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import pw.oxcafebabe.marcusant.eventbus.exceptions.EventCancellationException;
import pw.oxcafebabe.marcusant.eventbus.exceptions.EventException;
import pw.oxcafebabe.marcusant.eventbus.managers.iridium.IridiumEventManager;
public class EventBus {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testAttachSubscriber() {
exception.expect(RuntimeException.class);
exception.expectMessage("Test Succeeded");
EventManager eventManager = new IridiumEventManager();
eventManager.registerSubscriber(SimpleEvent.class, new SimpleSubscriber<SimpleEvent>() {
@Override
public void eventReceived(SimpleEvent event) {
throw new RuntimeException("Test Succeeded");
}
});
eventManager.push(new SimpleEvent());
}
@Test
public void testCancelEvent() {
EventManager manager = new IridiumEventManager();
manager.registerSubscriber(SimpleEvent.class, new SimpleSubscriber<SimpleEvent>(1) {
@Override
public void eventReceived(SimpleEvent event) {
try {
event.cancel();
} catch (EventCancellationException e) {
throw new RuntimeException("Was unable to cancel an event that should be cancellable");
}
}
});
manager.registerSubscriber(SimpleEvent.class, new SimpleSubscriber<SimpleEvent>(0) {
@Override
public void eventReceived(SimpleEvent event) {
throw new RuntimeException("Received an event should have been cancelled");
}
});
}
@Test
public void testUncancellableEvent() {
EventManager manager = new IridiumEventManager();
exception.expect(RuntimeException.class);
exception.expectMessage("Event did not allow us to cancel it!");
manager.registerSubscriber(SimplePersistentEvent.class, new SimpleSubscriber<SimplePersistentEvent>() {
@Override
public void eventReceived(SimplePersistentEvent event) {
try {
event.cancel();
} catch (EventCancellationException e) {
throw new RuntimeException("Event did not allow us to cancel it!");
}
}
});
manager.push(new SimplePersistentEvent());
}
@Test
public void registerClass() throws EventException {
EventManager manager = new IridiumEventManager();
exception.expect(RuntimeException.class);
exception.expectMessage("An exception was thrown during invocation of bridge method");
manager.registerObject(new TestListener());
manager.push(new SimpleEvent());
}
@Test
public void printLoadTest() {
EventManager manager = new IridiumEventManager();
for(int i = 0; i <= 10; i++) {
manager.registerSubscriber(SimpleEvent.class, new SimpleSubscriber<SimpleEvent>() {
@Override
public void eventReceived(SimpleEvent event) {
// nothing
}
});
}
long startTime = System.nanoTime();
for(int i = 0; i <= 500_000; i++){
manager.push(new SimpleEvent());
}
long elapsedTime = (System.nanoTime() - startTime) / 1_000_000;
System.out.println("Published 500.000 events in " + elapsedTime +"ms");
}
}
| mstojcevich/IridiumEventBus-NG | src/test/java/pw/oxcafebabe/marcusant/eventbus/EventBus.java | Java | gpl-2.0 | 3,647 |
<?php
class actionAdminCtypesRelationsEdit extends cmsAction {
public function run($ctype_id, $relation_id) {
if (!$ctype_id || !$relation_id) {
cmsCore::error404();
}
$ctype = $this->model_backend_content->getContentType($ctype_id);
if (!$ctype) { cmsCore::error404(); }
$relation = $this->model_backend_content->getContentRelation($relation_id);
if (!$relation) { cmsCore::error404(); }
$form = $this->getForm('ctypes_relation', ['edit', $ctype['id']]);
$form->setFieldProperty('basic', 'child_ctype_id', 'is_visible', false);
if ($relation['layout'] != 'tab') {
$form->hideFieldset('tab-opts');
}
if ($this->request->has('submit')) {
$form->removeField('basic', 'child_ctype_id');
$relation = array_merge($relation, $form->parse($this->request, true));
$errors = $form->validate($this, $relation);
if ($relation['layout'] == 'list' && $this->model_backend_content->filterEqual('ctype_id', $ctype['id'])->
filterEqual('layout', 'list')->filterNotEqual('id', $relation['id'])->
getCount('content_relations')) {
$errors['layout'] = LANG_CP_RELATION_LAYOUT_LIST_ERROR;
}
$this->model_backend_content->resetFilters();
if (!$errors) {
$relation['ctype_id'] = $ctype_id;
$this->model_backend_content->updateContentRelation($relation_id, $relation);
cmsUser::addSessionMessage(LANG_SUCCESS_MSG, 'success');
$this->redirectToAction('ctypes', ['relations', $ctype['id']]);
}
if ($errors) {
cmsUser::addSessionMessage(LANG_FORM_ERRORS, 'error');
}
}
$relation['child_ctype_id'] = $relation['target_controller'] . ':' . $relation['child_ctype_id'];
return $this->cms_template->render('ctypes_relation', [
'do' => 'edit',
'ctype' => $ctype,
'relation' => $relation,
'form' => $form,
'errors' => isset($errors) ? $errors : false
]);
}
}
| Loadir/icms2 | system/controllers/admin/actions/ctypes_relations_edit.php | PHP | gpl-2.0 | 2,247 |
FusionCharts.ready(function () {
var salaryDistribution = new FusionCharts({
type: 'boxandwhisker2d',
renderAt: 'chart-container',
width: '500',
height: '350',
dataFormat: 'json',
dataSource:
{
"chart": {
"caption": "Distribution of annual salaries",
"subcaption": "By Gender",
"xAxisName": "Pay Grades",
"YAxisName": "Salaries (In USD)",
"numberPrefix": "$",
"theme": "fint",
"showValues": "0",
//Showing out of range outliers
"showAllOutliers ": "1"
},
"categories": [
{
"category": [
{ "label": "Grade 1" },
{ "label": "Grade 2" },
{ "label": "Grade 3" }
]
}
],
"dataset": [
{
"seriesname": "Male",
"lowerboxcolor": "#008ee4",
"upperboxcolor": "#6baa01",
"data": [
{
"value": "2400,2000,2500,2800,3500,4000, 3700, 3750, 3880, 5000,5500,7500,8000,8200, 8400, 8500, 8550, 8800, 8700, 9000, 14000",
//specifying the outlier
"outliers":"16900"
},
{
"value": "7500,9000,12000,13000,14000,16500,17000, 18000, 19000, 19500",
"outliers":"23000"
},
{
"value": "15000,19000,25000,32000,50000,65000",
"outliers":"72000"
}
]
}, {
"seriesname": "Female",
"lowerboxcolor": "#e44a00",
"upperboxcolor": "#f8bd19",
"data": [
{
"value": "1900,2100,2300,2350,2400,2550,3000,3500,4000, 6000, 6500, 9000",
"outliers":"12000"
},
{
"value": "7000,8000,8300,8700,9500,11000,15000, 17000, 21000",
"outliers":"25000"
},
{
"value": "24000,32000,35000,37000,39000, 58000",
"outliers":"71000"
}
]
}
]
}
}).render();
}); | sguha-work/fiddletest | backup/fiddles/Chart/Data_plots/Configuring_data_plots_in_Box_And_Whisker_chart/demo.js | JavaScript | gpl-2.0 | 2,779 |
/*
* Copyright (C) 2014 Michael Joyce <ubermichael@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation version 2.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package ca.nines.ise.node.chr;
import ca.nines.ise.dom.Fragment;
import ca.nines.ise.node.CharNode;
import java.util.HashMap;
import java.util.Map;
/**
* Digraph characters are like ligatures but are not ligatures.
*
* @author Michael Joyce <ubermichael@gmail.com>
*/
public class DigraphCharNode extends CharNode {
/**
* Mapping.
*/
private static final HashMap<String, String> charMap = new HashMap<>();
/**
* Construct the mapping.
*/
static {
charMap.put("{ae}", "\u00e6");
charMap.put("{AE}", "\u00c6");
charMap.put("{oe}", "\u0153");
charMap.put("{OE}", "\u0152");
charMap.put("{qp}", "\u0239");
charMap.put("{db}", "\u0238");
}
/**
* Return a copy of the mapping.
*
* @return Map<> duplicate.
*/
public static Map<String, String> mapping() {
return new HashMap<>(charMap);
}
/**
* Expand the digraph into a fragment.
*
* @return Fragment
*/
@Override
public Fragment expanded() {
return wrap("DIGRAPH", charMap.get(text));
}
/**
* @return the charType
*/
@Override
public CharType getCharType() {
return CharType.DIGRAPH;
}
}
| emmental/isetools | src/main/java/ca/nines/ise/node/chr/DigraphCharNode.java | Java | gpl-2.0 | 1,874 |
/**************************************************************************
* This file is part of Celera Assembler, a software program that
* assembles whole-genome shotgun reads into contigs and scaffolds.
* Copyright (C) 2007, J. Craig Venter Institute.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received (LICENSE.txt) a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#ifndef AS_MER_GKPSTORE_TO_FASTABASE
#define AS_MER_GKPSTORE_TO_FASTABASE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "AS_PER_gkpStore.H"
#include "seqFile.H"
#include "seqFactory.H"
// Transform a wgs-assembler gkpStore object into a kmer seqFile
// object.
// About IIDs:
// gkpStore IIDs start at 1
// kmer IIDs start at 0
//
// This interface adds in a zero-length sequence to be kmer IID 0,
// and does not change the IID mapping.
// The "name" in openFile() should refer to a gatekeeper store
// directory. It can optionally include ":bgn-end:clr" to return a
// subset of the reads, and to return only the clear range. For
// example:
//
// dros.gkpStore:500-1000:obtini
//
// would return fragments 500 through 1000 inclusive, and return the
// initial OBT clear range.
class gkpStoreFile : public seqFile {
protected:
gkpStoreFile(char const *filename, uint32 bgn, uint32 end, uint32 clr);
gkpStoreFile();
public:
~gkpStoreFile();
static void registerFile(void) {
seqFactory::instance()->registerFile(new gkpStoreFile());
};
protected:
seqFile *openFile(const char *filename);
public:
uint32 find(const char *sequencename) {
fprintf(stderr, "gkpStoreFile::find()-- Not implemented.\n");
exit(1);
return(~uint32ZERO);
};
uint32 getSequenceLength(uint32 iid) {
return(_clrEnd[iid] - _clrBeg[iid]);
};
bool getSequence(uint32 iid,
char *&h, uint32 &hLen, uint32 &hMax,
char *&s, uint32 &sLen, uint32 &sMax);
bool getSequence(uint32 iid,
uint32 bgn, uint32 end, char *s);
uint16 clrBeg(uint32 iid) { return(_clrBeg[iid]); };
uint16 clrEnd(uint32 iid) { return(_clrEnd[iid]); };
private:
void clear(void);
gkStore *_gkp;
gkFragment _frg;
uint32 _bgn;
uint32 _end;
uint16 *_clrBeg;
uint16 *_clrEnd;
};
#endif // AS_MER_GKPSTORE_TO_FASTABASE
| peterhj/wgs-assembler | src/AS_MER/AS_MER_gkpStore_to_FastABase.H | C++ | gpl-2.0 | 3,230 |
<?php include sandy_get_header_path(); ?>
<div id='content'><div class='page-region'>
<?php if ($content): ?>
<div class='page-content content-wrapper clear-block'><?php print $content ?></div>
<?php endif; ?>
<?php print $content_region ?>
</div></div>
<div id='right'><div class='page-region'>
<?php if ($right) print $right ?>
</div></div>
<?php include sandy_get_footer_path(); ?>
| slimabraham/WildNet | sites/default/themes/sandy/page.tpl.php | PHP | gpl-2.0 | 399 |
package net.minecraft.network.play.server;
import java.io.IOException;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.scoreboard.Score;
import net.minecraft.scoreboard.ScoreObjective;
public class S3CPacketUpdateScore implements Packet<INetHandlerPlayClient>
{
private String name = "";
private String objective = "";
private int value;
private S3CPacketUpdateScore.Action action;
public S3CPacketUpdateScore()
{
}
public S3CPacketUpdateScore(Score scoreIn)
{
this.name = scoreIn.getPlayerName();
this.objective = scoreIn.getObjective().getName();
this.value = scoreIn.getScorePoints();
this.action = S3CPacketUpdateScore.Action.CHANGE;
}
public S3CPacketUpdateScore(String nameIn)
{
this.name = nameIn;
this.objective = "";
this.value = 0;
this.action = S3CPacketUpdateScore.Action.REMOVE;
}
public S3CPacketUpdateScore(String nameIn, ScoreObjective objectiveIn)
{
this.name = nameIn;
this.objective = objectiveIn.getName();
this.value = 0;
this.action = S3CPacketUpdateScore.Action.REMOVE;
}
/**
* Reads the raw packet data from the data stream.
*/
public void readPacketData(PacketBuffer buf) throws IOException
{
this.name = buf.readStringFromBuffer(40);
this.action = (S3CPacketUpdateScore.Action)buf.readEnumValue(S3CPacketUpdateScore.Action.class);
this.objective = buf.readStringFromBuffer(16);
if (this.action != S3CPacketUpdateScore.Action.REMOVE)
{
this.value = buf.readVarIntFromBuffer();
}
}
/**
* Writes the raw packet data to the data stream.
*/
public void writePacketData(PacketBuffer buf) throws IOException
{
buf.writeString(this.name);
buf.writeEnumValue(this.action);
buf.writeString(this.objective);
if (this.action != S3CPacketUpdateScore.Action.REMOVE)
{
buf.writeVarIntToBuffer(this.value);
}
}
/**
* Passes this Packet on to the NetHandler for processing.
*/
public void processPacket(INetHandlerPlayClient handler)
{
handler.handleUpdateScore(this);
}
public String getPlayerName()
{
return this.name;
}
public String getObjectiveName()
{
return this.objective;
}
public int getScoreValue()
{
return this.value;
}
public S3CPacketUpdateScore.Action getScoreAction()
{
return this.action;
}
public static enum Action
{
CHANGE,
REMOVE;
}
}
| SkidJava/BaseClient | new_1.8.8/net/minecraft/network/play/server/S3CPacketUpdateScore.java | Java | gpl-2.0 | 2,766 |
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Common styles for the original theme
*
* @package PhpMyAdmin-theme
* @subpackage Original
*/
// unplanned execution path
if (! defined('PMA_MINIMUM_COMMON') && ! defined('TESTSUITE')) {
exit();
}
?>
/******************************************************************************/
/* general tags */
html {
font-size: <?php echo $_SESSION['PMA_Theme']->getFontSize(); ?>
}
input,
select,
textarea {
font-size: 1em;
}
body {
<?php if (! empty($GLOBALS['cfg']['FontFamily'])) { ?>
font-family: <?php echo $GLOBALS['cfg']['FontFamily']; ?>;
<?php
}
?>
padding: 0;
margin: 0;
margin-<?php echo $left; ?>: 240px;
color: <?php echo $GLOBALS['cfg']['MainColor']; ?>;
background: <?php echo $GLOBALS['cfg']['MainBackground']; ?>;
}
body#loginform {
margin: 0;
}
#page_content, #session_debug {
margin: 0 .5em;
}
<?php if (! empty($GLOBALS['cfg']['FontFamilyFixed'])) { ?>
textarea, tt, pre, code {
font-family: <?php echo $GLOBALS['cfg']['FontFamilyFixed']; ?>;
}
<?php
}
?>
h1 {
font-size: 140%;
font-weight: bold;
}
h2 {
font-size: 120%;
font-weight: bold;
}
h3 {
font-weight: bold;
}
a, a:link,
a:visited,
a:active,
button.mult_submit,
.checkall_box+label {
text-decoration: none;
color: #0000FF;
cursor: pointer;
}
a:hover,
button.mult_submit:hover,
button.mult_submit:focus,
.checkall_box+label:hover {
text-decoration: underline;
color: #FF0000;
}
dfn {
font-style: normal;
}
dfn:hover {
font-style: normal;
cursor: help;
}
th {
font-weight: bold;
color: <?php echo $GLOBALS['cfg']['ThColor']; ?>;
background: <?php echo $GLOBALS['cfg']['ThBackground']; ?>;
}
a img {
border: 0;
}
hr {
color: <?php echo $GLOBALS['cfg']['MainColor']; ?>;
background-color: <?php echo $GLOBALS['cfg']['MainColor']; ?>;
border: 0;
height: 1px;
}
form {
padding: 0;
margin: 0;
display: inline;
}
textarea {
overflow: visible;
height: <?php echo ceil($GLOBALS['cfg']['TextareaRows'] * 1.2); ?>em;
}
textarea.char {
height: <?php echo ceil($GLOBALS['cfg']['CharTextareaRows'] * 1.2); ?>em;
}
fieldset {
margin-top: 1em;
border: <?php echo $GLOBALS['cfg']['MainColor']; ?> solid 1px;
padding: 0.5em;
background: <?php echo $GLOBALS['cfg']['BgOne']; ?>;
}
fieldset fieldset {
margin: 0.8em;
}
fieldset legend {
font-weight: bold;
color: #444444;
background-color: <?php echo 'OPERA' != PMA_USR_BROWSER_AGENT ? 'transparent' : $GLOBALS['cfg']['BgOne']; ?>;
}
.some-margin {
margin: .5em;
margin-top: 1em;
}
/* buttons in some browsers (eg. Konqueror) are block elements,
this breaks design */
button {
display: inline;
}
table caption,
table th,
table td {
padding: 0.1em 0.5em 0.1em 0.5em;
margin: 0.1em;
vertical-align: top;
}
img,
input,
select,
button {
vertical-align: middle;
}
/******************************************************************************/
/* classes */
.clearfloat {
clear: both;
}
.floatleft {
float: <?php echo $left; ?>;
margin-<?php echo $right; ?>: 1em;
}
table.nospacing {
border-spacing: 0;
}
table.nopadding tr th, table.nopadding tr td {
padding: 0;
}
th.left, td.left {
text-align: left;
}
th.center, td.center {
text-align: center;
}
th.right, td.right {
text-align: right;
}
tr.vtop, th.vtop, td.vtop {
vertical-align: top;
}
tr.vmiddle, th.vmiddle, td.vmiddle {
vertical-align: middle;
}
tr.vbottom, th.vbottom, td.vbottom {
vertical-align: bottom;
}
.paddingtop {
padding-top: 1em;
}
div.tools {
border: 1px solid #000000;
padding: 0.2em;
}
div.tools,
fieldset.tblFooters {
margin-top: 0;
margin-bottom: 0.5em;
/* avoid a thick line since this should be used under another fieldset */
border-top: 0;
text-align: <?php echo $right; ?>;
float: none;
clear: both;
}
div.null_div {
height: 20px;
text-align: center;
font-style:normal;
min-width:50px;
}
fieldset .formelement {
float: <?php echo $left; ?>;
margin-<?php echo $right; ?>: 0.5em;
/* IE */
white-space: nowrap;
}
@media all and (min-width: 1600px) {
fieldset .formelement {
clear: none;
}
#foreign_keys.relationalTable td:first-child + td {
width: 25%;
}
#foreign_keys.relationalTable td:first-child + td select {
width: auto;
margin-right: 1%;
}
#foreign_keys.relationalTable {
width: 100%;
}
}
/* revert for Gecko */
fieldset div[class=formelement] {
white-space: normal;
}
button.mult_submit {
border: none;
background-color: transparent;
}
/* odd items 1,3,5,7,... */
table tr.odd th,
.odd {
background: <?php echo $GLOBALS['cfg']['BgOne']; ?>;
}
/* even items 2,4,6,8,... */
table tr.even th,
.even {
background: <?php echo $GLOBALS['cfg']['BgTwo']; ?>;
}
/* odd table rows 1,3,5,7,... */
table tr.odd th,
table tr.odd,
table tr.even th,
table tr.even {
text-align: <?php echo $left; ?>;
}
<?php if ($GLOBALS['cfg']['BrowseMarkerEnable']) { ?>
/* marked table rows */
td.marked,
table tr.marked td,
table tr.marked th,
table tr.marked {
background: <?php echo $GLOBALS['cfg']['BrowseMarkerBackground']; ?>;
color: <?php echo $GLOBALS['cfg']['BrowseMarkerColor']; ?>;
}
<?php
}
?>
<?php if ($GLOBALS['cfg']['BrowsePointerEnable']) { ?>
/* hovered items */
.odd:hover,
.even:hover,
.hover {
background: <?php echo $GLOBALS['cfg']['BrowsePointerBackground']; ?>;
color: <?php echo $GLOBALS['cfg']['BrowsePointerColor']; ?>;
}
/* hovered table rows */
table tr.odd:hover th,
table tr.even:hover th,
table tr.hover th {
background: <?php echo $GLOBALS['cfg']['BrowsePointerBackground']; ?>;
color: <?php echo $GLOBALS['cfg']['BrowsePointerColor']; ?>;
}
<?php
}
?>
/**
* marks table rows/cells if the db field is in a where condition
*/
td.condition,
th.condition {
border: 1px solid <?php echo $GLOBALS['cfg']['BrowseMarkerBackground']; ?>;
}
/**
* cells with the value NULL
*/
td.null {
font-style: italic;
text-align: <?php echo $right; ?>;
}
table .valueHeader {
text-align: <?php echo $right; ?>;
white-space: normal;
}
table .value {
text-align: <?php echo $right; ?>;
white-space: normal;
}
/* IE doesnt handles 'pre' right */
table [class=value] {
white-space: normal;
}
<?php if (! empty($GLOBALS['cfg']['FontFamilyFixed'])) { ?>
.value {
font-family: <?php echo $GLOBALS['cfg']['FontFamilyFixed']; ?>;
}
<?php
}
?>
.attention {
color: red;
font-weight: bold;
}
.allfine {
color: green;
}
img.lightbulb {
cursor: pointer;
}
.pdflayout {
overflow: hidden;
clip: inherit;
background-color: #FFFFFF;
display: none;
border: 1px solid #000000;
position: relative;
}
.pdflayout_table {
background: #D3DCE3;
color: #000000;
overflow: hidden;
clip: inherit;
z-index: 2;
display: inline;
visibility: inherit;
cursor: move;
position: absolute;
font-size: 80%;
border: 1px dashed #000000;
}
/* Doc links in SQL */
.cm-sql-doc {
text-decoration: none;
border-bottom: 1px dotted #000;
color: inherit !important;
}
/* leave some space between icons and text */
.icon {
vertical-align: middle;
margin-<?php echo $left; ?>: 0.3em;
}
/* no extra space in table cells */
td .icon {
margin: 0;
}
.selectallarrow {
margin-<?php echo $right; ?>: 0.3em;
margin-<?php echo $left; ?>: 0.6em;
}
/* message boxes: error, confirmation */
#pma_errors, #pma_demo, #pma_footer {
padding: 0 0.5em;
}
.success h1,
.notice h1,
div.error h1 {
border-bottom: 2px solid;
font-weight: bold;
text-align: <?php echo $left; ?>;
margin: 0 0 0.2em 0;
}
div.success,
div.notice,
div.error {
margin: 0.3em 0 0 0;
border: 2px solid;
background-repeat: no-repeat;
<?php
if ($GLOBALS['text_dir'] === 'ltr') { ?>
background-position: 10px 50%;
padding: 0.1em 0.1em 0.1em 36px;
<?php
} else { ?>
background-position: 99% 50%;
padding: 0.1em 46px 0.1em 0.1em;
<?php
}
?>
}
.success {
color: #000000;
background-color: #f0fff0;
}
h1.success,
div.success {
border-color: #00FF00;
}
.success h1 {
border-color: #00FF00;
}
.notice {
color: #000000;
background-color: #FFFFDD;
}
h1.notice,
div.notice {
border-color: #FFD700;
}
.notice h1 {
border-color: #FFD700;
}
.error {
background-color: #FFFFCC;
color: #ff0000;
}
h1.error,
div.error {
border-color: #ff0000;
}
div.error h1 {
border-color: #ff0000;
}
.confirmation {
background-color: #FFFFCC;
}
fieldset.confirmation {
border: 0.1em solid #FF0000;
}
fieldset.confirmation legend {
border-left: 0.1em solid #FF0000;
border-right: 0.1em solid #FF0000;
font-weight: bold;
background-image: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('s_really.png');?>);
background-repeat: no-repeat;
<?php
if ($GLOBALS['text_dir'] === 'ltr') { ?>
background-position: 5px 50%;
padding: 0.2em 0.2em 0.2em 25px;
<?php
} else { ?>
background-position: 97% 50%;
padding: 0.2em 25px 0.2em 0.2em;
<?php
}
?>
}
/* end messageboxes */
.tblcomment {
font-size: 70%;
font-weight: normal;
color: #000099;
}
.tblHeaders {
font-weight: bold;
color: <?php echo $GLOBALS['cfg']['ThColor']; ?>;
background: <?php echo $GLOBALS['cfg']['ThBackground']; ?>;
}
div.tools,
.tblFooters {
font-weight: normal;
color: <?php echo $GLOBALS['cfg']['ThColor']; ?>;
background: <?php echo $GLOBALS['cfg']['ThBackground']; ?>;
}
.tblHeaders a:link,
.tblHeaders a:active,
.tblHeaders a:visited,
div.tools a:link,
div.tools a:visited,
div.tools a:active,
.tblFooters a:link,
.tblFooters a:active,
.tblFooters a:visited {
color: #0000FF;
}
.tblHeaders a:hover,
div.tools a:hover,
.tblFooters a:hover {
color: #FF0000;
}
/* forbidden, no privilegs */
.noPrivileges {
color: #FF0000;
font-weight: bold;
}
/* disabled text */
.disabled,
.disabled a:link,
.disabled a:active,
.disabled a:visited {
color: #666666;
}
.disabled a:hover {
color: #666666;
text-decoration: none;
}
tr.disabled td,
td.disabled {
background-color: #cccccc;
}
.nowrap {
white-space: nowrap;
}
/**
* zoom search
*/
div#resizer {
width: 600px;
height: 400px;
}
div#querychart {
float: left;
width: 600px;
}
/**
* login form
*/
body#loginform h1,
body#loginform a.logo {
display: block;
text-align: center;
}
body#loginform {
margin-top: 1em;
text-align: center;
}
body#loginform div.container {
text-align: <?php echo $left; ?>;
width: 30em;
margin: 0 auto;
}
form.login label {
float: <?php echo $left; ?>;
width: 10em;
font-weight: bolder;
}
.commented_column {
border-bottom: 1px dashed black;
}
.column_attribute {
font-size: 70%;
}
/******************************************************************************/
/* specific elements */
/* topmenu */
ul#topmenu, ul#topmenu2, ul.tabs {
font-weight: bold;
list-style-type: none;
margin: 0;
padding: 0;
}
ul#topmenu2 {
margin: 0.25em 0.5em 0;
height: 2em;
clear: both;
}
ul#topmenu li, ul#topmenu2 li {
float: <?php echo $left; ?>;
margin: 0;
padding: 0;
vertical-align: middle;
}
#topmenu img, #topmenu2 img {
vertical-align: middle;
margin-<?php echo $right; ?>: 0.1em;
}
/* default tab styles */
ul#topmenu a, ul#topmenu span {
display: block;
margin: 2px 2px 0;
padding: 2px 2px 0;
white-space: nowrap;
}
ul#topmenu2 a {
display: block;
margin: 0.1em;
padding: 0.2em;
white-space: nowrap;
}
fieldset.caution a {
color: #FF0000;
}
fieldset.caution a:hover {
color: #ffffff;
background-color: #FF0000;
}
#topmenu {
margin-top: 0.5em;
padding: 0.1em 0.3em 0.1em 0.3em;
}
ul#topmenu ul {
-moz-box-shadow: 2px 2px 3px #666;
-webkit-box-shadow: 2px 2px 3px #666;
box-shadow: 2px 2px 3px #666;
}
ul#topmenu > li {
border-bottom: 1pt solid black;
}
/* default tab styles */
ul#topmenu a, ul#topmenu span {
background-color: <?php echo $GLOBALS['cfg']['BgOne']; ?>;
border: 0 solid <?php echo $GLOBALS['cfg']['BgTwo']; ?>;
border-width: 1pt 1pt 0 1pt;
-moz-border-radius: 0.4em 0.4em 0 0;
border-radius: 0.4em 0.4em 0 0;
}
ul#topmenu ul a {
border-width: 1pt 0 0 0;
-moz-border-radius: 0;
border-radius: 0;
}
ul#topmenu ul li:first-child a {
border-width: 0;
}
/* enabled hover/active tabs */
ul#topmenu > li > a:hover,
ul#topmenu > li > .tabactive {
margin: 0;
padding: 2px 4px;
text-decoration: none;
}
ul#topmenu ul a:hover,
ul#topmenu ul .tabactive {
text-decoration: none;
}
ul#topmenu a.tab:hover,
ul#topmenu .tabactive {
background-color: <?php echo $GLOBALS['cfg']['MainBackground']; ?>;
}
ul#topmenu2 a.tab:hover,
ul#topmenu2 a.tabactive {
background-color: <?php echo $GLOBALS['cfg']['BgOne']; ?>;
-moz-border-radius: 0.3em;
border-radius: 0.3em;
text-decoration: none;
}
/* to be able to cancel the bottom border, use <li class="active"> */
ul#topmenu > li.active {
border-bottom: 1pt solid <?php echo $GLOBALS['cfg']['MainBackground']; ?>;
}
/* end topmenu */
/* zoom search */
div#dataDisplay input, div#dataDisplay select {
margin: 0;
margin-<?php echo $right; ?>: 0.5em;
}
div#dataDisplay th {
line-height: 2em;
}
table#tableFieldsId {
width: 100%;
}
/* Calendar */
table.calendar {
width: 100%;
}
table.calendar td {
text-align: center;
}
table.calendar td a {
display: block;
}
table.calendar td a:hover {
background-color: #CCFFCC;
}
table.calendar th {
background-color: #D3DCE3;
}
table.calendar td.selected {
background-color: #FFCC99;
}
img.calendar {
border: none;
}
form.clock {
text-align: center;
}
/* end Calendar */
/* table stats */
div#tablestatistics table {
float: <?php echo $left; ?>;
margin-top: 0.5em;
margin-bottom: 0.5em;
margin-<?php echo $right; ?>: 0.5em;
min-width: 16em;
}
/* end table stats */
/* server privileges */
#tableuserrights td,
#tablespecificuserrights td,
#tabledatabases td {
vertical-align: middle;
}
/* end server privileges */
/* Heading */
#topmenucontainer {
background: white;
padding-<?php echo $right; ?>: 1em;
width: 100%;
}
#serverinfo {
background: white;
font-weight: bold;
padding-bottom: 0.5em;
width: 10000px;
overflow: hidden;
}
#serverinfo .item {
white-space: nowrap;
}
#goto_pagetop, #lock_page_icon {
position: fixed;
padding: .1em .3em;
top: 0;
z-index: 900;
background: white;
}
#goto_pagetop {
<?php echo $right; ?>: 0;
}
#lock_page_icon {
<?php echo $right; ?>: 2em;
}
#span_table_comment {
font-weight: bold;
font-style: italic;
white-space: nowrap;
margin-left: 10px;
color: #D6D6D6;
text-shadow: none;
}
#serverinfo img {
margin: 0 0.1em 0 0.2em;
}
#textSQLDUMP {
width: 95%;
height: 95%;
font-family: "Courier New", Courier, mono;
font-size: 110%;
}
#TooltipContainer {
position: absolute;
z-index: 99;
width: 20em;
height: auto;
overflow: visible;
visibility: hidden;
background-color: #ffffcc;
color: #006600;
border: 0.1em solid #000000;
padding: 0.5em;
}
/* user privileges */
#fieldset_add_user_login div.item {
border-bottom: 1px solid silver;
padding-bottom: 0.3em;
margin-bottom: 0.3em;
}
#fieldset_add_user_login label {
float: <?php echo $left; ?>;
display: block;
width: 10em;
max-width: 100%;
text-align: <?php echo $right; ?>;
padding-<?php echo $right; ?>: 0.5em;
}
#fieldset_add_user_login span.options #select_pred_username,
#fieldset_add_user_login span.options #select_pred_hostname,
#fieldset_add_user_login span.options #select_pred_password {
width: 100%;
max-width: 100%;
}
#fieldset_add_user_login span.options {
float: <?php echo $left; ?>;
display: block;
width: 12em;
max-width: 100%;
padding-<?php echo $right; ?>: 0.5em;
}
#fieldset_add_user_login input {
width: 12em;
clear: <?php echo $right; ?>;
max-width: 100%;
}
#fieldset_add_user_login span.options input {
width: auto;
}
#fieldset_user_priv div.item {
float: <?php echo $left; ?>;
width: 9em;
max-width: 100%;
}
#fieldset_user_priv div.item div.item {
float: none;
}
#fieldset_user_priv div.item label {
white-space: nowrap;
}
#fieldset_user_priv div.item select {
width: 100%;
}
#fieldset_user_global_rights fieldset {
float: <?php echo $left; ?>;
}
#fieldset_user_group_rights fieldset {
float: <?php echo $left; ?>;
}
#fieldset_user_global_rights>legend input {
margin-<?php echo $left; ?>: 2em;
}
/* end user privileges */
/* serverstatus */
.linkElem:hover {
text-decoration: underline;
color: #235a81;
cursor: pointer;
}
h3#serverstatusqueries span {
font-size:60%;
display:inline;
}
.buttonlinks {
float: <?php echo $right; ?>;
white-space: nowrap;
}
/* Also used for the variables page */
fieldset#tableFilter {
margin-bottom:1em;
}
div#serverStatusTabs {
margin-top:1em;
}
caption a.top {
float: <?php echo $right; ?>;
}
div#serverstatusquerieschart {
float:<?php echo $left; ?>;
width:500px;
height:350px;
padding-<?php echo $left; ?>: 30px;
}
div#serverstatus table#serverstatusqueriesdetails {
float: <?php echo $left; ?>;
}
table#serverstatustraffic {
float: <?php echo $left; ?>;
}
table#serverstatusconnections {
float: <?php echo $left; ?>;
margin-<?php echo $left; ?>: 30px;
}
table#serverstatusvariables {
width: 100%;
margin-bottom: 1em;
}
table#serverstatusvariables .name {
width: 18em;
white-space:nowrap;
}
table#serverstatusvariables .value {
width: 6em;
}
table#serverstatusconnections {
float: <?php echo $left; ?>;
margin-<?php echo $left; ?>: 30px;
}
div#serverstatus table tbody td.descr a,
div#serverstatus table .tblFooters a {
white-space: nowrap;
}
div.liveChart {
clear:both;
min-width:500px;
height:400px;
padding-bottom:80px;
}
#addChartDialog input[type="text"] {
margin: 0;
padding:3px;
}
div#chartVariableSettings {
border:1px solid #ddd;
background-color:#E6E6E6;
margin-left:10px;
}
table#chartGrid td {
padding: 3px;
margin: 0;
}
table#chartGrid div.monitorChart {
background: #EBEBEB;
overflow: hidden;
border: none;
}
div.tabLinks {
margin-left: 0.3em;
float: <?php echo $left; ?>;
padding: 5px 0px;
}
div.tabLinks a, div.tabLinks label {
margin-right: 7px;
}
div.tabLinks .icon {
margin: -0.2em 0.3em 0px 0px;
}
.popupContent {
display: none;
position: absolute;
border: 1px solid #CCC;
margin:0;
padding:3px;
-moz-box-shadow: 1px 1px 6px #ddd;
-webkit-box-shadow: 2px 2px 3px #666;
box-shadow: 2px 2px 3px #666;
background-color:white;
z-index: 2;
}
div#logTable {
padding-top: 10px;
clear: both;
}
div#logTable table {
width:100%;
}
.smallIndent {
padding-left: 7px;
}
/* end serverstatus */
/* server variables */
#serverVariables {
table-layout: fixed;
width: 100%;
}
#serverVariables .var-row > tr {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
line-height: 2em;
}
#serverVariables .var-header {
font-weight: bold;
color: <?php echo $GLOBALS['cfg']['ThColor']; ?>;
background: <?php echo $GLOBALS['cfg']['ThBackground']; ?>;
}
#serverVariables .var-header {
text-align: <?php echo $left; ?>;
}
#serverVariables .var-row {
padding: 0.5em;
min-height: 18px;
}
#serverVariables .var-action {
width: 120px;
}
#serverVariables .var-name {
float: <?php echo $left; ?>;
font-weight: bold;
}
#serverVariables .var-name.session {
font-weight: normal;
font-style: italic;
}
#serverVariables .var-value {
width: 50%;
float: <?php echo $right; ?>;
text-align: <?php echo $right; ?>;
}
/* server variables editor */
#serverVariables .editLink {
padding-<?php echo $right; ?>: 1em;
float: <?php echo $left; ?>;
font-family: sans-serif;
}
#serverVariables .serverVariableEditor {
width: 100%;
overflow: hidden;
}
#serverVariables .serverVariableEditor input {
width: 100%;
margin: 0 0.5em;
box-sizing: border-box;
-ms-box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
height: 2.2em;
}
#serverVariables .serverVariableEditor div {
display: block;
overflow: hidden;
padding-<?php echo $right; ?>: 1em;
}
#serverVariables .serverVariableEditor a {
float: <?php echo $right; ?>;
margin: 0 0.5em;
line-height: 2em;
}
/* end server variables */
/* profiling */
div#profilingchart {
width: 850px;
height: 370px;
float: left;
}
#profilingchart .jqplot-highlighter-tooltip{
top: auto !important;
left: 11px;
bottom:24px;
}
/* end profiling */
/* querybox */
div#sqlquerycontainer {
float: <?php echo $left; ?>;
width: 69%;
/* height: 15em; */
}
div#tablefieldscontainer {
float: <?php echo $right; ?>;
width: 29%;
/* height: 15em; */
}
div#tablefieldscontainer select {
width: 100%;
/* height: 12em; */
}
textarea#sqlquery {
width: 100%;
/* height: 100%; */
}
textarea#sql_query_edit {
height: 7em;
width: 95%;
display: block;
}
div#queryboxcontainer div#bookmarkoptions {
margin-top: .5em;
}
/* end querybox */
/* main page */
#maincontainer {
background-image: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('logo_right.png');?>);
background-position: <?php echo $right; ?> bottom;
background-repeat: no-repeat;
}
#mysqlmaininformation,
#pmamaininformation {
float: <?php echo $left; ?>;
width: 49%;
}
#maincontainer ul {
list-style-type: disc;
vertical-align: middle;
}
#maincontainer li {
margin: 0.2em 0em;
}
#full_name_layer {
position: absolute;
padding: 2px;
margin-top: -3px;
z-index: 801;
border: solid 1px #888;
background: #fff;
}
/* end main page */
/* iconic view for ul items */
li.no_bullets {
list-style-type:none !important;
margin-left: -25px !important; //align with other list items which have bullets
}
/* end iconic view for ul items */
#body_browse_foreigners {
background: <?php echo $GLOBALS['cfg']['NaviBackground']; ?>;
margin: .5em .5em 0 .5em;
}
#bodythemes {
width: 500px;
margin: auto;
text-align: center;
}
#bodythemes img {
border: .1em solid #000;
}
#bodythemes a:hover img {
border: .1em solid red;
}
#fieldset_select_fields {
float: <?php echo $left; ?>;
}
#selflink {
clear: both;
display: block;
margin-top: 1em;
margin-bottom: 1em;
width: 98%;
margin-left: 1%;
border-top: .1em solid silver;
text-align: <?php echo $right; ?>;
}
#table_innodb_bufferpool_usage,
#table_innodb_bufferpool_activity {
float: <?php echo $left; ?>;
}
#div_mysql_charset_collations table {
float: <?php echo $left; ?>;
}
#div_mysql_charset_collations table th,
#div_mysql_charset_collations table td {
padding: 0.4em;
}
#div_mysql_charset_collations table th#collationHeader {
width: 35%;
}
.operations_half_width {
width: 48%;
float: <?php echo $left; ?>;
}
.operations_half_width input[type=text],
.operations_half_width input[type=password],
.operations_half_width input[type=number],
.operations_half_width select {
width: 95%;
}
.operations_half_width input[type=text].halfWidth,
.operations_half_width input[type=password].halfWidth,
.operations_half_width input[type=number].halfWidth,
.operations_half_width select.halfWidth {
width: 40%;
}
.operations_half_width ul {
list-style-type: none;
padding: 0;
}
.operations_full_width {
width: 100%;
clear: both;
}
#qbe_div_table_list {
float: <?php echo $left; ?>;
}
#qbe_div_sql_query {
float: <?php echo $left; ?>;
}
label.desc {
width: 30em;
float: <?php echo $left; ?>;
}
label.desc sup {
position: absolute;
}
code.sql,
div.sqlvalidate {
display: block;
padding: 0.3em;
margin-top: 0;
margin-bottom: 0;
max-height: 10em;
overflow: auto;
}
.result_query div.sqlOuter,
div.sqlvalidate {
border: <?php echo $GLOBALS['cfg']['MainColor']; ?> solid 1px;
border-top: 0;
border-bottom: 0;
background: <?php echo $GLOBALS['cfg']['BgOne']; ?>;
}
#PMA_slidingMessage code.sql {
border: <?php echo $GLOBALS['cfg']['MainColor']; ?> solid 1px;
border-top: 0;
background: <?php echo $GLOBALS['cfg']['BgOne']; ?>;
}
#main_pane_left {
width: 60%;
min-width: 260px;
float: <?php echo $left; ?>;
padding-top: 1em;
}
#main_pane_right {
overflow: hidden;
min-width: 160px;
padding-top: 1em;
padding-<?php echo $left; ?>: 1em;
}
.group {
border-<?php echo $left; ?>: 0.3em solid <?php echo $GLOBALS['cfg']['ThBackground']; ?>;
margin-bottom: 1em;
}
.group h2 {
background: <?php echo $GLOBALS['cfg']['ThBackground']; ?>;
padding: 0.1em 0.3em;
margin-top: 0;
}
.group-cnt {
padding: 0 0 0 0.5em;
display: inline-block;
width: 98%;
}
textarea#partitiondefinition {
height:3em;
}
/* for elements that should be revealed only via js */
.hide {
display: none;
}
#list_server {
list-style-type: none;
padding: 0;
}
/**
* Progress bar styles
*/
div.upload_progress
{
width: 400px;
margin: 3em auto;
text-align: center;
}
div.upload_progress_bar_outer
{
border: 1px solid #000;
width: 202px;
position: relative;
margin: 0 auto 1em;
color: <?php echo $GLOBALS['cfg']['MainColor']; ?>;
}
div.upload_progress_bar_inner
{
background-color: <?php echo $GLOBALS['cfg']['NaviPointerBackground']; ?>;
width: 0;
height: 12px;
margin: 1px;
overflow: hidden;
color: <?php echo $GLOBALS['cfg']['BrowseMarkerColor']; ?>;
position: relative;
}
div.upload_progress_bar_outer div.percentage
{
position: absolute;
top: 0;
left: 0;
width: 202px;
}
div.upload_progress_bar_inner div.percentage
{
top: -1px;
left: -1px;
}
div#statustext {
margin-top: .5em;
}
table#serverconnection_src_remote,
table#serverconnection_trg_remote,
table#serverconnection_src_local,
table#serverconnection_trg_local {
float: left;
}
/**
* Validation error message styles
*/
input[type=text].invalid_value,
input[type=password].invalid_value,
input[type=number].invalid_value,
input[type=date].invalid_value,
select.invalid_value,
.invalid_value {
background: #FFCCCC;
}
/**
* Ajax notification styling
*/
.ajax_notification {
top: 0; /** The notification needs to be shown on the top of the page */
position: fixed;
margin-top: 0;
margin-right: auto;
margin-bottom: 0;
margin-left: auto;
padding: 3px 5px; /** Keep a little space on the sides of the text */
width: 350px;
background-color: #FFD700;
z-index: 1100; /** If this is not kept at a high z-index, the jQueryUI modal dialogs (z-index:1000) might hide this */
text-align: center;
display: block;
left: 0;
right: 0;
background-image: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('ajax_clock_small.gif');?>);
background-repeat: no-repeat;
background-position: 2%;
}
#loading_parent {
/** Need this parent to properly center the notification division */
position: relative;
width: 100%;
}
/**
* Export and Import styles
*/
.exportoptions h3, .importoptions h3 {
border-bottom: 1px #999999 solid;
font-size: 110%;
}
.exportoptions ul, .importoptions ul, .format_specific_options ul {
list-style-type: none;
margin-bottom: 15px;
}
.exportoptions li, .importoptions li {
margin: 7px;
}
.exportoptions label, .importoptions label, .exportoptions p, .importoptions p {
margin: 5px;
float: none;
}
#csv_options label.desc, #ldi_options label.desc, #latex_options label.desc, #output label.desc{
float: left;
width: 15em;
}
.exportoptions, .importoptions {
margin: 20px 30px 30px 10px
}
.format_specific_options h3 {
margin: 10px 0 0 10px;
border: 0;
}
.format_specific_options {
border: 1px solid #999;
margin: 7px 0;
padding: 3px;
}
p.desc {
margin: 5px;
}
/**
* Export styles only
*/
select#db_select,
select#table_select {
width: 400px;
}
.export_sub_options {
margin: 20px 0 0 30px;
}
.export_sub_options h4 {
border-bottom: 1px #999 solid;
}
.export_sub_options li.subgroup {
display: inline-block;
margin-top: 0;
}
.export_sub_options li {
margin-bottom: 0;
}
#output_quick_export {
display: none;
}
/**
* Import styles only
*/
.importoptions #import_notification {
margin: 10px 0;
font-style: italic;
}
input#input_import_file {
margin: 5px;
}
.formelementrow {
margin: 5px 0 5px 0;
}
#popup_background {
display: none;
position: fixed;
_position: absolute; /* hack for IE6 */
width: 100%;
height: 100%;
top: 0;
left: 0;
background: #000;
z-index: 1000;
overflow: hidden;
}
/**
* Create table styles
*/
#create_table_form table.table-name td {
vertical-align: middle;
}
/**
* Table structure styles
*/
#fieldsForm ul.table-structure-actions {
margin: 0;
padding: 0;
list-style: none;
}
#fieldsForm ul.table-structure-actions li {
float: <?php echo $left; ?>;
margin-<?php echo $right; ?>: 0.5em; /* same as padding of "table td" */
}
#fieldsForm ul.table-structure-actions .submenu li {
padding: 0.3em;
margin: 0.1em;
}
#structure-action-links a {
margin-<?php echo $right; ?>: 1em;
}
#addColumns input[type="radio"] {
margin: 0;
margin-<?php echo $left; ?>: 1em;
}
#addColumns input[type="submit"] {
margin-<?php echo $left; ?>: 1em;
}
/**
* Indexes
*/
#index_frm .index_info input,
#index_frm .index_info select {
width: 100%;
box-sizing: border-box;
-ms-box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
#index_frm .slider {
width: 10em;
margin: .6em;
float: <?php echo $left; ?>;
}
#index_frm .add_fields {
float: <?php echo $left; ?>;
}
#index_frm .add_fields input {
margin-<?php echo $left; ?>: 1em;
}
#index_frm input {
margin: 0;
}
#index_frm td {
vertical-align: middle;
}
table#index_columns {
width: 100%;
}
table#index_columns select {
width: 85%;
float: right;
}
#move_columns_dialog div {
padding: 1em;
}
#move_columns_dialog ul {
list-style: none;
margin: 0;
padding: 0;
}
#move_columns_dialog li {
background: <?php echo $GLOBALS['cfg']['ThBackground']; ?>;
border: 1px solid #aaa;
color: <?php echo $GLOBALS['cfg']['ThColor']; ?>;
font-weight: bold;
margin: .4em;
padding: .2em;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
}
/* config forms */
.config-form ul.tabs {
margin: 1.1em 0.2em 0;
padding: 0 0 0.3em 0;
list-style: none;
font-weight: bold;
}
.config-form ul.tabs li {
float: <?php echo $left; ?>;
}
.config-form ul.tabs li a {
display: block;
margin: 0.1em 0.2em 0;
padding: 0.1em 0.4em;
white-space: nowrap;
text-decoration: none;
border: 1px solid <?php echo $GLOBALS['cfg']['BgTwo']; ?>;
border-bottom: none;
}
.config-form ul.tabs li a:hover,
.config-form ul.tabs li a:active,
.config-form ul.tabs li a.active {
margin: 0;
padding: 0.1em 0.6em 0.2em;
}
.config-form ul.tabs li.active a {
background-color: <?php echo $GLOBALS['cfg']['BgOne']; ?>;
}
.config-form fieldset {
margin-top: 0;
padding: 0;
clear: both;
/*border-color: <?php echo $GLOBALS['cfg']['BgTwo']; ?>;*/
}
.config-form legend {
display: none;
}
.config-form fieldset p {
margin: 0;
padding: 0.5em;
background: <?php echo $GLOBALS['cfg']['BgTwo']; ?>;
}
.config-form fieldset .errors { /* form error list */
margin: 0 -2px 1em -2px;
padding: .5em 1.5em;
background: #FBEAD9;
border: 0 #C83838 solid;
border-width: 1px 0;
list-style: none;
font-family: sans-serif;
font-size: small;
}
.config-form fieldset .inline_errors { /* field error list */
margin: .3em .3em .3em 0;
padding: 0;
list-style: none;
color: #9A0000;
font-size: small;
}
.config-form fieldset th {
padding: .3em .3em .3em .5em;
text-align: left;
vertical-align: top;
width: 40%;
background: transparent;
}
.config-form fieldset .doc,
.config-form fieldset .disabled-notice {
margin-left: 1em;
}
.config-form fieldset .disabled-notice {
font-size: 80%;
text-transform: uppercase;
color: #E00;
cursor: help;
}
.config-form fieldset td {
padding-top: .3em;
padding-bottom: .3em;
vertical-align: top;
}
.config-form fieldset th small {
display: block;
font-weight: normal;
font-family: sans-serif;
font-size: x-small;
color: #444;
}
.config-form fieldset th,
.config-form fieldset td {
border-top: 1px <?php echo $GLOBALS['cfg']['BgTwo']; ?> solid;
}
fieldset .group-header th {
background: <?php echo $GLOBALS['cfg']['BgTwo']; ?>;
}
fieldset .group-header + tr th {
padding-top: .6em;
}
fieldset .group-field-1 th,
fieldset .group-header-2 th {
padding-left: 1.5em;
}
fieldset .group-field-2 th,
fieldset .group-header-3 th {
padding-left: 3em;
}
fieldset .group-field-3 th {
padding-left: 4.5em;
}
fieldset .disabled-field th,
fieldset .disabled-field th small,
fieldset .disabled-field td {
color: #666;
background-color: #ddd;
}
.config-form .lastrow {
border-top: 1px #000 solid;
}
.config-form .lastrow {
background: <?php echo $GLOBALS['cfg']['ThBackground']; ?>;
padding: .5em;
text-align: center;
}
.config-form .lastrow input {
font-weight: bold;
}
/* form elements */
.config-form span.checkbox {
padding: 2px;
display: inline-block;
}
.config-form .custom { /* customized field */
background: #FFC;
}
.config-form span.checkbox.custom {
padding: 1px;
border: 1px #EDEC90 solid;
background: #FFC;
}
.config-form .field-error {
border-color: #A11 !important;
}
.config-form input[type="text"],
.config-form input[type="password"],
.config-form input[type="number"],
.config-form select,
.config-form textarea {
border: 1px #A7A6AA solid;
height: auto;
}
.config-form input[type="text"]:focus,
.config-form input[type="password"]:focus,
.config-form input[type="number"]:focus,
.config-form select:focus,
.config-form textarea:focus {
border: 1px #6676FF solid;
background: #F7FBFF;
}
.config-form .field-comment-mark {
font-family: serif;
color: #007;
cursor: help;
padding: 0 0.2em;
font-weight: bold;
font-style: italic;
}
.config-form .field-comment-warning {
color: #A00;
}
/* error list */
.config-form dd {
margin-left: .5em;
}
.config-form dd:before {
content: "\25B8 ";
}
.click-hide-message {
cursor: pointer;
}
.prefsmanage_opts {
margin-<?php echo $left; ?>: 2em;
}
#prefs_autoload {
margin-bottom: .5em;
}
#placeholder .button {
position: absolute;
cursor: pointer;
}
#placeholder div.button {
font-size: smaller;
color: #999;
background-color: #eee;
padding: 2px;
}
.wrapper {
float: <?php echo $left; ?>;
margin-bottom: 0.5em;
}
.toggleButton {
position: relative;
cursor: pointer;
font-size: .8em;
text-align: center;
line-height: 1.4em;
height: 1.55em;
overflow: hidden;
border-right: .1em solid #888;
border-left: .1em solid #888;
}
.toggleButton table,
.toggleButton td,
.toggleButton img {
padding: 0;
position: relative;
}
.toggleButton .container {
position: absolute;
}
.toggleButton .container td {
background-image: none;
background: none;
}
.toggleButton .toggleOn {
color: #fff;
padding: 0 1em;
}
.toggleButton .toggleOff {
padding: 0 1em;
}
.doubleFieldset fieldset {
width: 48%;
float: <?php echo $left; ?>;
padding: 0;
}
.doubleFieldset fieldset.left {
margin-<?php echo $right; ?>: 1%;
}
.doubleFieldset fieldset.right {
margin-<?php echo $left; ?>: 1%;
}
.doubleFieldset legend {
margin-<?php echo $left; ?>: 0.5em;
}
.doubleFieldset div.wrap {
padding: 0.5em;
}
#table_name_col_no_outer {
margin-top: 30px;
}
#table_name_col_no {
position: fixed;
top: 44px;
z-index: 500;
width: 100%;
background: <?php echo $GLOBALS['cfg']['MainBackground']; ?>;
}
#table_columns input[type="text"],
#table_columns input[type="password"],
#table_columns input[type="number"],
#table_columns input[type="date"],
#table_columns select {
width: 10em;
box-sizing: border-box;
-ms-box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
#placeholder {
position: relative;
border: 1px solid #aaa;
float: <?php echo $right; ?>;
overflow: hidden;
}
.placeholderDrag {
cursor: move;
}
#placeholder .button {
position: absolute;
}
#left_arrow {
left: 8px;
top: 26px;
}
#right_arrow {
left: 26px;
top: 26px;
}
#up_arrow {
left: 17px;
top: 8px;
}
#down_arrow {
left: 17px;
top: 44px;
}
#zoom_in {
left: 17px;
top: 67px;
}
#zoom_world {
left: 17px;
top: 85px;
}
#zoom_out {
left: 17px;
top: 103px;
}
.colborder {
cursor: col-resize;
height: 100%;
margin-left: -5px;
position: absolute;
width: 5px;
}
.colborder_active {
border-right: 2px solid #a44;
}
.pma_table td {
position: static;
}
.pma_table th.draggable span,
.pma_table tbody td span {
display: block;
overflow: hidden;
}
.pma_table tbody td span code span {
display: inline;
}
.modal-copy input {
display: block;
width: 100%;
margin-top: 1.5em;
padding: .3em 0;
}
.cRsz {
position: absolute;
}
.draggable {
cursor: move;
}
.cCpy {
background: #000;
color: #FFF;
font-weight: bold;
margin: 0.1em;
padding: 0.3em;
position: absolute;
}
.cPointer {
background: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('col_pointer.png');?>);
height: 20px;
margin-left: -5px; /* must be minus half of its width */
margin-top: -10px;
position: absolute;
width: 10px;
}
.tooltip {
background: #333 !important;
opacity: .8 !important;
border: 1px solid #000 !important;
-moz-border-radius: .3em !important;
-webkit-border-radius: .3em !important;
border-radius: .3em !important;
text-shadow: -1px -1px #000 !important;
font-size: .8em !important;
font-weight: bold !important;
padding: 1px 3px !important;
}
.tooltip * {
background: none !important;
color: #FFF !important;
}
.data_full_width {
width: 100%;
}
.cDrop {
left: 0;
position: absolute;
top: 0;
}
.coldrop {
background: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('col_drop.png');?>);
cursor: pointer;
height: 16px;
margin-left: 0.5em;
margin-top: 0.3em;
position: absolute;
width: 16px;
}
.coldrop:hover,
.coldrop-hover {
background-color: #999;
}
.cList {
background: #EEE;
border: solid 1px #999;
position: absolute;
}
.cList .lDiv div {
padding: .2em .5em .2em .2em;
}
.cList .lDiv div:hover {
background: #DDD;
cursor: pointer;
}
.cList .lDiv div input {
cursor: pointer;
}
.showAllColBtn {
border-bottom: solid 1px #999;
border-top: solid 1px #999;
cursor: pointer;
font-size: .9em;
font-weight: bold;
padding: .35em 1em;
text-align: center;
}
.showAllColBtn:hover {
background: #DDD;
}
.navigation {
background: #E5E5E5;
border: 1px solid black;
margin: 0.8em 0;
}
.navigation td {
margin: 0;
padding: 0;
vertical-align: middle;
white-space: nowrap;
}
.navigation_separator {
color: #555;
display: inline-block;
text-align: center;
width: 1.2em;
text-shadow: 1px 0 #FFF;
}
.navigation input[type=submit] {
background: none;
border: 0;
margin: 0;
padding: 0.3em 0.5em;
min-width: 1.5em;
font-weight: bold;
}
.navigation input[type=submit]:hover, .navigation input.edit_mode_active {
background: #333;
color: white;
cursor: pointer;
}
.navigation select {
margin: 0 .8em;
}
.cEdit {
margin: 0;
padding: 0;
position: absolute;
}
.cEdit input[type=text],
.cEdit input[type=password],
.cEdit input[type=number] {
background: #FFF;
height: 100%;
margin: 0;
padding: 0;
}
.cEdit .edit_area {
background: #FFF;
border: 1px solid #999;
min-width: 10em;
padding: .3em .5em;
}
.cEdit .edit_area select,
.cEdit .edit_area textarea {
width: 97%;
}
.cEdit .cell_edit_hint {
color: #555;
font-size: .8em;
margin: .3em .2em;
}
.cEdit .edit_box {
overflow: hidden;
padding: 0;
}
.cEdit .edit_box_posting {
background: #FFF url(<?php echo $_SESSION['PMA_Theme']->getImgPath('ajax_clock_small.gif');?>) no-repeat right center;
padding-right: 1.5em;
}
.cEdit .edit_area_loading {
background: #FFF url(<?php echo $_SESSION['PMA_Theme']->getImgPath('ajax_clock_small.gif');?>) no-repeat center;
height: 10em;
}
.cEdit .edit_area_right {
position: absolute;
right: 0;
}
.cEdit .goto_link {
background: #EEE;
color: #555;
padding: .2em .3em;
}
.saving_edited_data {
background: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('ajax_clock_small.gif');?>) no-repeat left;
padding-left: 20px;
}
/* css for timepicker */
.ui-timepicker-div .ui-widget-header { margin-bottom: 8px; }
.ui-timepicker-div dl { text-align: left; }
.ui-timepicker-div dl dt { height: 25px; }
.ui-timepicker-div dl dd { margin: -25px 0 10px 85px; }
.ui-timepicker-div td { font-size: 90%; }
input.btn {
color: #333;
background-color: #D0DCE0;
}
body .ui-widget {
font-size: 1em;
}
.ui-dialog fieldset legend a {
color: #0000FF;
}
/* jqPlot */
/*rules for the plot target div. These will be cascaded down to all plot elements
according to css rules*/
.jqplot-target {
position: relative;
color: #222222;
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
font-size: 1em;
/* height: 300px;
width: 400px;*/
}
/*rules applied to all axes*/
.jqplot-axis {
font-size: 0.75em;
}
.jqplot-xaxis {
margin-top: 10px;
}
.jqplot-x2axis {
margin-bottom: 10px;
}
.jqplot-yaxis {
margin-right: 10px;
}
.jqplot-y2axis, .jqplot-y3axis, .jqplot-y4axis, .jqplot-y5axis, .jqplot-y6axis,
.jqplot-y7axis, .jqplot-y8axis, .jqplot-y9axis, .jqplot-yMidAxis {
margin-left: 10px;
margin-right: 10px;
}
/*rules applied to all axis tick divs*/
.jqplot-axis-tick, .jqplot-xaxis-tick, .jqplot-yaxis-tick, .jqplot-x2axis-tick,
.jqplot-y2axis-tick, .jqplot-y3axis-tick, .jqplot-y4axis-tick, .jqplot-y5axis-tick,
.jqplot-y6axis-tick, .jqplot-y7axis-tick, .jqplot-y8axis-tick, .jqplot-y9axis-tick,
.jqplot-yMidAxis-tick {
position: absolute;
white-space: pre;
}
.jqplot-xaxis-tick {
top: 0px;
/* initial position untill tick is drawn in proper place */
left: 15px;
/* padding-top: 10px;*/
vertical-align: top;
}
.jqplot-x2axis-tick {
bottom: 0px;
/* initial position untill tick is drawn in proper place */
left: 15px;
/* padding-bottom: 10px;*/
vertical-align: bottom;
}
.jqplot-yaxis-tick {
right: 0px;
/* initial position untill tick is drawn in proper place */
top: 15px;
/* padding-right: 10px;*/
text-align: right;
}
.jqplot-yaxis-tick.jqplot-breakTick {
right: -20px;
margin-right: 0px;
padding:1px 5px 1px 5px;
/* background-color: white;*/
z-index: 2;
font-size: 1.5em;
}
.jqplot-y2axis-tick, .jqplot-y3axis-tick, .jqplot-y4axis-tick, .jqplot-y5axis-tick,
.jqplot-y6axis-tick, .jqplot-y7axis-tick, .jqplot-y8axis-tick, .jqplot-y9axis-tick {
left: 0px;
/* initial position untill tick is drawn in proper place */
top: 15px;
/* padding-left: 10px;*/
/* padding-right: 15px;*/
text-align: left;
}
.jqplot-yMidAxis-tick {
text-align: center;
white-space: nowrap;
}
.jqplot-xaxis-label {
margin-top: 10px;
font-size: 11pt;
position: absolute;
}
.jqplot-x2axis-label {
margin-bottom: 10px;
font-size: 11pt;
position: absolute;
}
.jqplot-yaxis-label {
margin-right: 10px;
/* text-align: center;*/
font-size: 11pt;
position: absolute;
}
.jqplot-yMidAxis-label {
font-size: 11pt;
position: absolute;
}
.jqplot-y2axis-label, .jqplot-y3axis-label, .jqplot-y4axis-label,
.jqplot-y5axis-label, .jqplot-y6axis-label, .jqplot-y7axis-label,
.jqplot-y8axis-label, .jqplot-y9axis-label {
/* text-align: center;*/
font-size: 11pt;
margin-left: 10px;
position: absolute;
}
.jqplot-meterGauge-tick {
font-size: 0.75em;
color: #999999;
}
.jqplot-meterGauge-label {
font-size: 1em;
color: #999999;
}
table.jqplot-table-legend {
margin-top: 12px;
margin-bottom: 12px;
margin-left: 12px;
margin-right: 12px;
}
table.jqplot-table-legend, table.jqplot-cursor-legend {
background-color: rgba(255,255,255,0.6);
border: 1px solid #cccccc;
position: absolute;
font-size: 0.75em;
}
td.jqplot-table-legend {
vertical-align:middle;
}
/*
These rules could be used instead of assigning
element styles and relying on js object properties.
*/
/*
td.jqplot-table-legend-swatch {
padding-top: 0.5em;
text-align: center;
}
tr.jqplot-table-legend:first td.jqplot-table-legend-swatch {
padding-top: 0px;
}
*/
td.jqplot-seriesToggle:hover, td.jqplot-seriesToggle:active {
cursor: pointer;
}
.jqplot-table-legend .jqplot-series-hidden {
text-decoration: line-through;
}
div.jqplot-table-legend-swatch-outline {
border: 1px solid #cccccc;
padding:1px;
}
div.jqplot-table-legend-swatch {
width:0px;
height:0px;
border-top-width: 5px;
border-bottom-width: 5px;
border-left-width: 6px;
border-right-width: 6px;
border-top-style: solid;
border-bottom-style: solid;
border-left-style: solid;
border-right-style: solid;
}
.jqplot-title {
top: 0px;
left: 0px;
padding-bottom: 0.5em;
font-size: 1.2em;
}
table.jqplot-cursor-tooltip {
border: 1px solid #cccccc;
font-size: 0.75em;
}
.jqplot-cursor-tooltip {
border: 1px solid #cccccc;
font-size: 0.75em;
white-space: nowrap;
background: rgba(208,208,208,0.5);
padding: 1px;
}
.jqplot-highlighter-tooltip, .jqplot-canvasOverlay-tooltip {
border: 1px solid #cccccc;
font-size: 0.75em;
white-space: nowrap;
background: rgba(208,208,208,0.5);
padding: 1px;
}
.jqplot-point-label {
font-size: 0.75em;
z-index: 2;
}
td.jqplot-cursor-legend-swatch {
vertical-align: middle;
text-align: center;
}
div.jqplot-cursor-legend-swatch {
width: 1.2em;
height: 0.7em;
}
.jqplot-error {
/* Styles added to the plot target container when there is an error go here.*/
text-align: center;
}
.jqplot-error-message {
/* Styling of the custom error message div goes here.*/
position: relative;
top: 46%;
display: inline-block;
}
div.jqplot-bubble-label {
font-size: 0.8em;
/* background: rgba(90%, 90%, 90%, 0.15);*/
padding-left: 2px;
padding-right: 2px;
color: rgb(20%, 20%, 20%);
}
div.jqplot-bubble-label.jqplot-bubble-label-highlight {
background: rgba(90%, 90%, 90%, 0.7);
}
div.jqplot-noData-container {
text-align: center;
background-color: rgba(96%, 96%, 96%, 0.3);
}
.relationalTable select {
width: 125px;
margin-right: 5px;
}
.report-data {
height:13em;
overflow:scroll;
width:570px;
border: solid 1px;
background: white;
padding: 2px;
}
.report-description {
height:10em;
width:570px;
}
div#page_content div#tableslistcontainer table.data {
border-top: 0.1px solid #EEEEEE;
}
div#page_content form#db_search_form.ajax fieldset {
margin-top: -0.3em;
}
div#page_content div#tableslistcontainer, div#page_content div.notice, div#page_content div.result_query {
margin-top: 1em;
}
table.show_create {
margin-top: 1em;
}
table.show_create td {
border-right: 1px solid #bbb;
}
#alias_modal table th {
vertical-align: middle;
padding-left: 1em;
}
#alias_modal label.col-2 {
min-width: 20%;
display: inline-block;
}
#alias_modal select {
width: 25%;
margin-right: 2em;
}
#alias_modal label {
font-weight: bold;
}
.ui-dialog {
position: fixed;
}
.small_font {
font-size: smaller;
}
/* Console styles */
#pma_console_container {
width: 100%;
position: fixed;
bottom: 0;
<?php echo $left; ?>: 0;
z-index: 100;
}
#pma_console {
position: relative;
margin-<?php echo $left; ?>: 240px;
z-index: 100;
}
#pma_console>.templates {
display: none;
}
#pma_console .mid_text,
#pma_console .toolbar span {
vertical-align: middle;
}
#pma_console .toolbar {
position: relative;
background: #ccc;
border-top: solid 1px #aaa;
cursor: n-resize;
}
#pma_console .toolbar.collapsed:not(:hover) {
display: inline-block;
border-top-<?php echo $right; ?>-radius: 3px;
border-<?php echo $right; ?>: solid 1px #aaa;
}
#pma_console .toolbar.collapsed {
cursor: default;
}
#pma_console .toolbar.collapsed>.button {
display: none;
}
#pma_console .message span.text,
#pma_console .message span.action,
#pma_console .toolbar .button,
#pma_console .switch_button {
padding: 0 3px;
display: inline-block;
}
#pma_console .message span.action,
#pma_console .toolbar .button,
#pma_console .switch_button {
cursor: pointer;
}
#pma_console .message span.action:hover,
#pma_console .toolbar .button:hover,
#pma_console .switch_button:hover {
background: #ddd;
}
#pma_console .toolbar .button {
margin-<?php echo $right; ?>: .4em;
}
#pma_console .toolbar .button {
float: <?php echo $right; ?>;
}
#pma_console .content {
overflow-x: hidden;
overflow-y: auto;
margin-bottom: -65px;
border-top: solid 1px #aaa;
background: #fff;
padding-top: .4em;
}
#pma_console .content.console_dark_theme {
background: #000;
color: #fff;
}
#pma_console .content.console_dark_theme .CodeMirror-wrap {
background: #000;
color: #fff;
}
#pma_console .content.console_dark_theme .action_content {
color: #000;
}
#pma_console .content.console_dark_theme .message {
border-color: #373B41;
}
#pma_console .content.console_dark_theme .CodeMirror-cursor {
border-color: #fff;
}
#pma_console .content.console_dark_theme .cm-keyword {
color: #de935f;
}
#pma_console .message,
#pma_console .query_input {
position: relative;
font-family: Monaco, Consolas, monospace;
cursor: text;
margin: 0 10px .2em 1.4em;
}
#pma_console .message {
border-bottom: solid 1px #ccc;
padding-bottom: .2em;
}
#pma_console .message.expanded .action_content {
position: relative;
}
#pma_console .message:before,
#pma_console .query_input:before {
left: -0.7em;
position: absolute;
content: ">";
}
#pma_console .query_input:before {
top: -2px;
}
#pma_console .query_input textarea {
width: 100%;
height: 4em;
resize: vertical;
}
#pma_console .message:hover:before {
color: #7cf;
font-weight: bold;
}
#pma_console .message.expanded:before {
content: "]";
}
#pma_console .message.welcome:before {
display: none;
}
#pma_console .message.failed:before,
#pma_console .message.failed.expanded:before,
#pma_console .message.failed:hover:before {
content: "=";
color: #944;
}
#pma_console .message.pending:before {
opacity: .3;
}
#pma_console .message.collapsed>.query {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
#pma_console .message.expanded>.query {
display: block;
white-space: pre;
word-wrap: break-word;
}
#pma_console .message .text.targetdb,
#pma_console .message.collapsed .action.collapse,
#pma_console .message.expanded .action.expand,
#pma_console .message .action.requery,
#pma_console .message .action.profiling,
#pma_console .message .action.explain,
#pma_console .message .action.bookmark {
display: none;
}
#pma_console .message.select .action.profiling,
#pma_console .message.select .action.explain,
#pma_console .message.history .text.targetdb,
#pma_console .message.successed .text.targetdb,
#pma_console .message.history .action.requery,
#pma_console .message.history .action.bookmark,
#pma_console .message.bookmark .action.requery,
#pma_console .message.bookmark .action.bookmark,
#pma_console .message.successed .action.requery,
#pma_console .message.successed .action.bookmark {
display: inline-block;
}
#pma_console .message .action_content {
position: absolute;
bottom: 100%;
background: #ccc;
border: solid 1px #aaa;
border-top-<?php echo $left; ?>-radius: 3px;
}
html.ie8 #pma_console .message .action_content {
position: relative!important;
}
#pma_console .message.bookmark .text.targetdb,
#pma_console .message .text.query_time {
margin: 0;
display: inline-block;
}
#pma_console .message.failed .text.query_time,
#pma_console .message .text.failed {
display: none;
}
#pma_console .message.failed .text.failed {
display: inline-block;
}
#pma_console .message .text {
background: #fff;
}
#pma_console .message.collapsed:not(:hover) .action_content {
display: none;
}
#pma_console .message .bookmark_label {
padding: 0 4px;
top: 0;
background: #369;
color: #fff;
border-radius: 3px;
}
#pma_console .message .bookmark_label.shared {
background: #396;
}
#pma_console .message.expanded .bookmark_label {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
#pma_console .query_input {
position: relative;
}
#pma_console .mid_layer {
height: 100%;
width: 100%;
position: absolute;
top: 0;
/* For support IE8, this layer doesn't use filter:opacity or opacity,
js code will fade this layer opacity to 0.18(using animation) */
background: #666;
display: none;
cursor: pointer;
z-index: 200;
}
#pma_console .card {
position: absolute;
width: 94%;
height: 100%;
min-height: 48px;
<?php echo $left; ?>: 100%;
top: 0;
border-<?php echo $left; ?>: solid 1px #999;
z-index: 300;
transition: <?php echo $left; ?> 0.2s;
-ms-transition: <?php echo $left; ?> 0.2s;
-webkit-transition: <?php echo $left; ?> 0.2s;
-moz-transition: <?php echo $left; ?> 0.2s;
}
#pma_console .card.show {
<?php echo $left; ?>: 6%;
box-shadow: -2px 1px 4px -1px #999;
}
html.ie7 #pma_console .query_input {
display: none;
}
#pma_bookmarks .content.add_bookmark,
#pma_console_options .content {
padding: 4px 6px;
}
#pma_bookmarks .content.add_bookmark .options {
margin-<?php echo $left; ?>: 1.4em;
padding-bottom: .4em;
margin-bottom: .4em;
border-bottom: solid 1px #ccc;
}
#pma_bookmarks .content.add_bookmark .options button {
margin: 0 7px;
vertical-align: bottom;
}
#pma_bookmarks .content.add_bookmark input[type=text] {
margin: 0;
padding: 2px 4px;
}
/* Code mirror console style*/
.cm-s-pma .CodeMirror-code pre,
.cm-s-pma .CodeMirror-code {
font-family: Monaco, Consolas, monospace;
}
.cm-s-pma .CodeMirror-measure>pre,
.cm-s-pma .CodeMirror-code>pre,
.cm-s-pma .CodeMirror-lines {
padding: 0;
}
.cm-s-pma.CodeMirror {
resize: none;
height: auto;
width: 100%;
min-height: initial;
max-height: initial;
}
.firefox .cm-s-pma.CodeMirror {
font-size: 120%;
}
.cm-s-pma .CodeMirror-scroll {
padding-bottom: 2em;
cursor: text;
}
/* PMA drop-improt style */
.pma_drop_handler {
display: none;
position: fixed;
top: 0px;
left: 0px;
width: 100%;
background: rgba(0, 0, 0, 0.6);
height: 100%;
z-index: 999;
color: white;
font-size: 30pt;
text-align: center;
padding-top: 20%;
}
.pma_sql_import_status {
display: none;
position: fixed;
bottom: 0px;
right: 25px;
width: 400px;
border: 1px solid #999;
background: #f3f3f3;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
-moz-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>2px 2px 5px #ccc;
-webkit-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>2px 2px 5px #ccc;
box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>2px 2px 5px #ccc;
}
.pma_sql_import_status h2,
.pma_drop_result h2 {
background-color: #bbb;
padding: .1em .3em;
margin-top: 0;
margin-bottom: 0;
color: #fff;
font-size: 1.6em;
font-weight: normal;
text-shadow: 0 1px 0 #777;
-moz-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>1px 1px 15px #999 inset;
-webkit-box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>1px 1px 15px #999 inset;
box-shadow: <?php echo $GLOBALS['text_dir'] === 'rtl' ? '-' : ''; ?>1px 1px 15px #999 inset;
}
.pma_sql_import_status div {
height: 270px;
overflow-y:auto;
overflow-x:hidden;
list-style-type: none;
}
.pma_sql_import_status div li {
padding: 8px 10px;
border-bottom: 1px solid #bbb;
color: rgb(148, 14, 14);
background: white;
}
.pma_sql_import_status div li .filesize {
float: right;
}
.pma_sql_import_status h2 .minimize {
float: right;
margin-right: 5px;
padding: 0px 10px;
}
.pma_sql_import_status h2 .close {
float: right;
margin-right: 5px;
padding: 0px 10px;
display: none;
}
.pma_sql_import_status h2 .minimize:hover,
.pma_sql_import_status h2 .close:hover,
.pma_drop_result h2 .close:hover {
background: rgba(155, 149, 149, 0.78);
cursor: pointer;
}
.pma_drop_file_status {
color: #235a81;
}
.pma_drop_file_status span.underline:hover {
cursor: pointer;
text-decoration: underline;
}
.pma_drop_result {
position: fixed;
top: 10%;
left: 20%;
width: 60%;
background: white;
min-height: 300px;
z-index: 800;
-webkit-box-shadow: 0px 0px 15px #999;
border-radius: 10px;
cursor: move;
}
.pma_drop_result h2 .close {
float: right;
margin-right: 5px;
padding: 0px 10px;
}
#composite_index_list {
list-style-type: none;
list-style-position: inside;
}
span.drag_icon {
display: inline-block;
background-image: url('<?php echo $_SESSION['PMA_Theme']->getImgPath('s_sortable.png');?>');
background-position: center center;
background-repeat: no-repeat;
width: 1em;
height: 3em;
cursor: move;
}
.topmargin {
margin-top: 1em;
}
/* styles for sortable tables created with tablesorter jquery plugin */
th.header {
cursor: pointer;
color: #0000FF;
}
th.header:hover {
text-decoration: underline;
}
th.header .sorticon {
width: 16px;
height: 16px;
background-repeat: no-repeat;
background-position: right center;
display: inline-table;
vertical-align: middle;
float: right;
}
th.headerSortUp .sorticon, th.headerSortDown:hover .sorticon {
background-image: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('s_desc.png');?>);
}
th.headerSortDown .sorticon, th.headerSortUp:hover .sorticon {
background-image: url(<?php echo $_SESSION['PMA_Theme']->getImgPath('s_asc.png');?>);
}
/* end of styles of sortable tables */
| Xloka/phpmyadmin | themes/original/css/common.css.php | PHP | gpl-2.0 | 62,513 |
package org.openyu.commons.util.adapter;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;
import org.openyu.commons.jaxb.adapter.supporter.BaseXmlAdapterSupporter;
import org.openyu.commons.util.SerializeType;
// --------------------------------------------------
// reslove: JAXB can’t handle interfaces
// --------------------------------------------------
//<serializeTypes key="JDK">2</serializeTypes>
//--------------------------------------------------
public class SerializeTypeXmlAdapter
extends
BaseXmlAdapterSupporter<SerializeTypeXmlAdapter.SerializeTypeEntry, SerializeType> {
public SerializeTypeXmlAdapter() {
}
// --------------------------------------------------
public static class SerializeTypeEntry {
@XmlAttribute
public String key;
@XmlValue
public int value;
public SerializeTypeEntry(String key, int value) {
this.key = key;
this.value = value;
}
public SerializeTypeEntry() {
}
}
// --------------------------------------------------
public SerializeType unmarshal(SerializeTypeEntry value) throws Exception {
SerializeType result = null;
//
if (value != null) {
result = SerializeType.valueOf(value.key);
}
return result;
}
public SerializeTypeEntry marshal(SerializeType value) throws Exception {
SerializeTypeEntry result = null;
//
if (value != null) {
result = new SerializeTypeEntry(value.name(), value.getValue());
}
return result;
}
}
| mixaceh/openyu-commons | openyu-commons-core/src/main/java/org/openyu/commons/util/adapter/SerializeTypeXmlAdapter.java | Java | gpl-2.0 | 1,484 |
/*
* Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.bcel.internal.generic;
import java.io.DataOutputStream;
import java.io.IOException;
import com.sun.org.apache.bcel.internal.ExceptionConst;
import com.sun.org.apache.bcel.internal.util.ByteSequence;
/**
* NEWARRAY - Create new array of basic type (int, short, ...)
* <PRE>Stack: ..., count -> ..., arrayref</PRE>
* type must be one of T_INT, T_SHORT, ...
*
* @version $Id$
* @LastModified: Jun 2019
*/
public class NEWARRAY extends Instruction implements AllocationInstruction, ExceptionThrower,
StackProducer {
private byte type;
/**
* Empty constructor needed for Instruction.readInstruction.
* Not to be used otherwise.
*/
NEWARRAY() {
}
public NEWARRAY(final byte type) {
super(com.sun.org.apache.bcel.internal.Const.NEWARRAY, (short) 2);
this.type = type;
}
public NEWARRAY(final BasicType type) {
this(type.getType());
}
/**
* Dump instruction as byte code to stream out.
* @param out Output stream
*/
@Override
public void dump( final DataOutputStream out ) throws IOException {
out.writeByte(super.getOpcode());
out.writeByte(type);
}
/**
* @return numeric code for basic element type
*/
public final byte getTypecode() {
return type;
}
/**
* @return type of constructed array
*/
public final Type getType() {
return new ArrayType(BasicType.getType(type), 1);
}
/**
* @return mnemonic for instruction
*/
@Override
public String toString( final boolean verbose ) {
return super.toString(verbose) + " " + com.sun.org.apache.bcel.internal.Const.getTypeName(type);
}
/**
* Read needed data (e.g. index) from file.
*/
@Override
protected void initFromFile( final ByteSequence bytes, final boolean wide ) throws IOException {
type = bytes.readByte();
super.setLength(2);
}
@Override
public Class<?>[] getExceptions() {
return new Class<?>[] {
ExceptionConst.NEGATIVE_ARRAY_SIZE_EXCEPTION
};
}
/**
* Call corresponding visitor method(s). The order is:
* Call visitor methods of implemented interfaces first, then
* call methods according to the class hierarchy in descending order,
* i.e., the most specific visitXXX() call comes last.
*
* @param v Visitor object
*/
@Override
public void accept( final Visitor v ) {
v.visitAllocationInstruction(this);
v.visitExceptionThrower(this);
v.visitStackProducer(this);
v.visitNEWARRAY(this);
}
}
| md-5/jdk10 | src/java.xml/share/classes/com/sun/org/apache/bcel/internal/generic/NEWARRAY.java | Java | gpl-2.0 | 3,578 |
<?php
global $wpdb;
if (( current_user_can('gestionar_datos') ) && ($pagRes == 0))
$sql = "SELECT * FROM adeada_encuestas";
else
$sql = "SELECT * FROM adeada_encuestas WHERE id_usuario='".get_current_user_id( )."'";
$resultEncuestas = $wpdb->get_results($sql);
$filas = array();
$columnas = array(52);
$indexArr = 0;
if($resultEncuestas){
foreach ($resultEncuestas as $rEncuestas) {
$columnas[0] = $rEncuestas->id_encuesta;
$columnas[1] = get_userdata($rEncuestas->id_usuario)->user_login;
$columnas[2] = $rEncuestas->concepto;
$columnas[3] = $rEncuestas->estado;
$columnas[4] = $rEncuestas->fec_alta;
$columnas[5] = $rEncuestas->fec_mod;
$sql = "SELECT id_pregunta,id_encuesta,puntos FROM `adeada_respuestas` WHERE id_encuesta='".$rEncuestas->id_encuesta."'";
$resultRespuestas = $wpdb->get_results($sql);
$col=6;
if($resultRespuestas){
foreach ($resultRespuestas as $rRespuestas) {
//echo " ++++ ".$rRespuestas["puntos"];
$columnas[$col] = $rRespuestas->puntos;
$col++;
}
}
$filas[$indexArr] = $columnas;
$indexArr++;
}
}
/*echo "<table>";
echo "<tr><th>ver</th><th>encuesta</th><th>Usuario</th><th>Concepto</th><th>Estado</th><th>Fecha alta</th><th>Fecha Modificación</th><th>E1</th><th>E2</th><th>E3</th><th>E4</th><th>E5</th><th>E6</th><th>E7</th><th>E8</th><th>E9</th><th>E10</th><th>P1</th><th>P2</th><th>P3</th><th>P4</th><th>P5</th><th>P6</th><th>P7</th><th>P8</th><th>P9</th><th>P10</th><th>R1</th><th>R2</th><th>R3</th><th>R4</th><th>R5</th><th>R6</th><th>R7</th><th>R8</th><th>R9</th><th>R10</th><th>PR1</th><th>PR2</th><th>PR3</th><th>PR4</th><th>PR5</th><th>PR6</th><th>PR7</th><th>PR8</th><th>PR9</th><th>PR10</th><th>RS1</th><th>RS2</th><th>RS3</th></tr>";
for ($i=0;$i<$indexArr;$i++){
echo "<tr>";
echo "<td><div><a href='?page_id=8&id_encuesta=".$filas[$i][0]."'>".$filas[$i][0]."</a></div></td>";
for ($j=0;$j<49;$j++)//6+43
echo "<td>".$filas[$i][$j]."</td>";
echo "</tr>";
}
echo "</table>";*/
echo "<div id='resultadoTabla'><table>";
//echo "<tr><th colspan='3' style='border:0;'> </th><th><a href='?page_id=8'>Nuevo</a></th></tr>";
echo "<tr><th>Fecha alta</th><th>Fecha Fin</th><th>Estado</th><th>Acciones</th></tr>";
for ($i=0;$i<$indexArr;$i++){
echo "<tr>";
echo "<td>".$filas[$i][4]."</td>";
echo "<td>".$filas[$i][5]."</td>";
$contResp = 0;
for ($j=0;$j<49;$j++)//6+43
if ($filas[$i][$j] != null)
$contResp++;
$strCompletado = "Completo";
$strAccion = "Ver resultado";
if ($filas[$i][3] == 0){
$strCompletado = round($contResp*100/43)."%";
$strAccion = "Continuar";
}
echo "<td>".$strCompletado."</td>";
echo "<td><div><a href='?page_id=8&id_encuesta=".$filas[$i][0]."'>".$strAccion."</a></div></td>";
echo "</tr>";
}
echo "</table>";
echo "<p>Si desea realizar un nuevo <strong>Autodiagnóstico</strong> pulse en: <strong><a href='?page_id=8'>Nuevo</a></strong></p>";
echo "</div>";
?>
| Esleelkartea/herramienta_para_autodiagnostico_ADEADA | programa/plugins/adeada/test/resultado2.php | PHP | gpl-2.0 | 3,368 |
module Katello
module Resources
module Candlepin
class Owner < CandlepinResource
extend OwnerResource
class << self
# Set the contentPrefix at creation time so that the client will get
# content only for the org it has been subscribed to
def create(key, description)
attrs = {:key => key, :displayName => description, :contentPrefix => "/#{key}/$env"}
owner_json = self.post(path, attrs.to_json, self.default_headers).body
JSON.parse(owner_json).with_indifferent_access
end
# create the first user for owner
def create_user(_key, username, password)
# create user with superadmin flag (no role, permissions etc)
CPUser.create(:username => name_to_key(username), :password => name_to_key(password), :superAdmin => true)
end
def destroy(key)
self.delete(path(key), User.cp_oauth_header).code.to_i
end
def find(key)
owner_json = self.get(path(key), {'accept' => 'application/json'}.merge(User.cp_oauth_header)).body
JSON.parse(owner_json).with_indifferent_access
end
def update(key, attrs)
owner = find(key)
owner.merge!(attrs)
self.put(path(key), JSON.generate(owner), self.default_headers).body
end
def import(organization_name, path_to_file, options)
path = join_path(path(organization_name), 'imports')
if options[:force] || SETTINGS[:katello].key?(:force_manifest_import)
path += "?force=#{SETTINGS[:katello][:force_manifest_import]}"
end
self.post(path, {:import => File.new(path_to_file, 'rb')}, self.default_headers.except('content-type'))
end
def product_content(organization_name)
Product.all(organization_name, [:id, :productContent])
end
def destroy_imports(organization_name, wait_until_complete = false)
response_json = self.delete(join_path(path(organization_name), 'imports'), self.default_headers)
response = JSON.parse(response_json).with_indifferent_access
if wait_until_complete && response['state'] == 'CREATED'
while !response['state'].nil? && response['state'] != 'FINISHED' && response['state'] != 'ERROR'
path = join_path('candlepin', response['statusPath'][1..-1])
response_json = self.get(path, self.default_headers)
response = JSON.parse(response_json).with_indifferent_access
end
end
response
end
def imports(organization_name)
imports_json = self.get(join_path(path(organization_name), 'imports'), self.default_headers)
::Katello::Util::Data.array_with_indifferent_access JSON.parse(imports_json)
end
def pools(owner_label, filter = {})
filter[:add_future] ||= true
params = hash_to_query(filter)
if owner_label
# hash_to_query escapes the ":!" to "%3A%21" which candlepin rejects
params += '&attribute=unmapped_guests_only:!true'
json_str = self.get(join_path(path(owner_label), 'pools') + params, self.default_headers).body
else
json_str = self.get(join_path('candlepin', 'pools') + params, self.default_headers).body
end
::Katello::Util::Data.array_with_indifferent_access JSON.parse(json_str)
end
def statistics(key)
json_str = self.get(join_path(path(key), 'statistics'), self.default_headers).body
::Katello::Util::Data.array_with_indifferent_access JSON.parse(json_str)
end
def generate_ueber_cert(key)
ueber_cert_json = self.post(join_path(path(key), "uebercert"), {}.to_json, self.default_headers).body
JSON.parse(ueber_cert_json).with_indifferent_access
end
def get_ueber_cert(key)
ueber_cert_json = self.get(join_path(path(key), "uebercert"), {'accept' => 'application/json'}.merge(User.cp_oauth_header)).body
JSON.parse(ueber_cert_json).with_indifferent_access
end
def get_ueber_cert_pkcs12(key, name = nil, password = nil)
certs = get_ueber_cert(key)
c = OpenSSL::X509::Certificate.new certs["cert"]
p = OpenSSL::PKey::RSA.new certs["key"]
OpenSSL::PKCS12.create(password, name, p, c, nil, "PBE-SHA1-3DES", "PBE-SHA1-3DES")
end
def events(key)
response = self.get(join_path(path(key), 'events'), self.default_headers).body
::Katello::Util::Data.array_with_indifferent_access JSON.parse(response)
end
def service_levels(uuid)
response = Candlepin::CandlepinResource.get(join_path(path(uuid), 'servicelevels'), self.default_headers).body
if response.empty?
return []
else
JSON.parse(response)
end
end
def auto_attach(key)
response = self.post(join_path(path(key), 'entitlements'), "", self.default_headers).body
if response.empty?
return nil
else
JSON.parse(response)
end
end
end
end
end
end
end
| jlsherrill/katello | app/lib/katello/resources/candlepin/owner.rb | Ruby | gpl-2.0 | 5,461 |
<?php
defined('_JEXEC') or die('Direct Access to ' . basename(__FILE__) . 'is not allowed.');
/**
*
* @package VirtueMart
* @subpackage vmpayment
* @version $Id: refundnotification.php 8431 2014-10-14 14:11:46Z alatak $
* @author Valérie Isaksen
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2004 - October 24 2014 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*
*/
class amazonHelperRefundNotification extends amazonHelper {
public function __construct (OffAmazonPaymentsNotifications_Model_RefundNotification $refundNotification, $method) {
parent::__construct($refundNotification, $method);
}
function onNotificationUpdateOrderHistory ($order, $payments) {
$order_history = array();
$amazonState = "";
$reasonCode = "";
if (!$this->amazonData->isSetRefundDetails()) {
$this->debugLog('NO isSetRefundDetails' . __FUNCTION__ . var_export($this->amazonData, true), 'error');
return;
}
$details = $this->amazonData->getRefundDetails();
if (!$details->isSetRefundStatus()) {
$this->debugLog('NO isSetRefundStatus' . __FUNCTION__ . var_export($this->amazonData, true), 'error');
return;
}
$status = $details->getRefundStatus();
if (!$status->isSetState()) {
$this->debugLog('NO isSetState' . __FUNCTION__ . var_export($this->amazonData, true), 'error');
return;
}
$amazonState = $status->getState();
if ($status->isSetReasonCode()) {
$reasonCode = $status->getReasonCode();
}
// default value
$order_history['customer_notified'] = 1;
if ($amazonState == 'Completed') {
$order_history['order_status'] = $this->_currentMethod->status_refunded;
$order_history['comments'] = vmText::_('VMPAYMENT_AMAZON_COMMENT_STATUS_REFUND_COMPLETED');
} elseif ($amazonState == 'Declined') {
$order_history['customer_notified'] = 0;
$order_history['comments'] = vmText::sprintf('VMPAYMENT_AMAZON_COMMENT_STATUS_REFUND_DECLINED', $reasonCode);
$order_history['order_status'] = $order['details']['BT']->order_status;
} elseif ($amazonState == 'Pending') {
$order_history['comments'] = vmText::_('VMPAYMENT_AMAZON_COMMENT_STATUS_REFUND_PENDING');
$order_history['order_status'] = $this->_currentMethod->status_orderconfirmed;
}
$orderModel = VmModel::getModel('orders');
$orderModel->updateStatusForOneOrder($order['details']['BT']->virtuemart_order_id, $order_history, false);
return $amazonState;
}
/**
* move to Pending => GetRefundDetails
* move to Declined => GetRefundDetails
* move to Completed => GetRefundDetails
* @param $order
* @param $payments
* @param $amazonState
* @return bool|string
*/
/*
public function onNotificationNextOperation($order, $payments, $amazonState) {
return false;
}
*/
public function getReferenceId () {
if ($this->amazonData->isSetRefundDetails()) {
$details = $this->amazonData->getRefundDetails();
if ($details->isSetRefundReferenceId()) {
return $this->getVmReferenceId($details->getRefundReferenceId());
}
}
return NULL;
}
public function getAmazonId () {
if ($this->amazonData->isSetRefundDetails()) {
$details = $this->amazonData->getRefundDetails();
if ($details->isSetAmazonRefundId()) {
return $details->getAmazonRefundId();
}
}
return NULL;
}
public function getStoreInternalData () {
//$amazonInternalData = $this->getStoreResultParams();
$amazonInternalData = new stdClass();
if ($this->amazonData->isSetRefundDetails()) {
$details = $this->amazonData->getRefundDetails();
if ($details->isSetAmazonRefundId()) {
$amazonInternalData->amazon_response_amazonRefundId = $details->getAmazonRefundId();
}
if ($details->isSetRefundStatus()) {
$status = $details->getRefundStatus();
if ($status->isSetState()) {
$amazonInternalData->amazon_response_state = $status->getState();
}
if ($status->isSetReasonCode()) {
$amazonInternalData->amazon_response_reasonCode = $status->getReasonCode();
}
if ($status->isSetReasonDescription()) {
$amazonInternalData->amazon_response_reasonDescription = $status->getReasonDescription();
}
}
}
return $amazonInternalData;
}
function getContents () {
$contents = $this->tableStart("Refund Notification");
if ($this->amazonData->isSetRefundDetails()) {
$contents .= $this->getRowFirstCol("RefundDetails");
$refundDetails = $this->amazonData->getRefundDetails();
if ($refundDetails->isSetAmazonRefundId()) {
$contents .= $this->getRow("AmazonRefundId: ", $refundDetails->getAmazonRefundId());
}
if ($refundDetails->isSetRefundReferenceId()) {
$contents .= $this->getRow("RefundReferenceId: ", $refundDetails->getRefundReferenceId());
}
if ($refundDetails->isSetRefundType()) {
$contents .= $this->getRow("RefundType: ", $refundDetails->getRefundType());
}
if ($refundDetails->isSetRefundAmount()) {
$more = '';
$refundAmount = $refundDetails->getRefundAmount();
if ($refundAmount->isSetAmount()) {
$more .= "<br /> Amount " . $refundAmount->getAmount();
}
if ($refundAmount->isSetCurrencyCode()) {
$more .= "<br /> CurrencyCode: " . $refundAmount->getCurrencyCode();
}
$contents .= $this->getRow("RefundAmount: ", $more);
}
if ($refundDetails->isSetFeeRefunded()) {
$more = '';
$feeRefunded = $refundDetails->getFeeRefunded();
if ($feeRefunded->isSetAmount()) {
$more .= "<br /> Amount " . $feeRefunded->getAmount();
}
if ($feeRefunded->isSetCurrencyCode()) {
$more .= "<br /> CurrencyCode " . $feeRefunded->getCurrencyCode();
}
$contents .= $this->getRow("FeeRefunded: ", $more);
}
if ($refundDetails->isSetCreationTimestamp()) {
$contents .= $this->getRow("CreationTimestamp: ", $refundDetails->getCreationTimestamp());
}
if ($refundDetails->isSetRefundStatus()) {
$more = '';
$refundStatus = $refundDetails->getRefundStatus();
if ($refundStatus->isSetState()) {
$more .= "<br /> State " . $refundStatus->getState();
}
if ($refundStatus->isSetLastUpdateTimestamp()) {
$more .= "<br /> LastUpdateTimestamp " . $refundStatus->getLastUpdateTimestamp();
}
if ($refundStatus->isSetReasonCode()) {
$more .= "<br /> ReasonCode " . $refundStatus->getReasonCode();
}
if ($refundStatus->isSetReasonDescription()) {
$more .= "<br /> ReasonDescription " . $refundStatus->getReasonDescription();
}
$contents .= $this->getRow("RefundStatus: ", $more);
}
if ($refundDetails->isSetSoftDescriptor()) {
$contents .= $this->getRow("SoftDescriptor: ", $refundDetails->getSoftDescriptor());
}
}
$contents .= $this->tableEnd();
return $contents;
}
}
| adrian2020my/vichi | plugins/vmpayment/amazon/helpers/refundnotification.php | PHP | gpl-2.0 | 7,067 |
/* This file is part of the KDE project
* Copyright (c) 2009 Jan Hambrecht <jaham@gmx.net>
*
* 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 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "ComponentTransferEffectConfigWidget.h"
#include "KoFilterEffect.h"
#include <KNumInput>
#include <KComboBox>
#include <KLineEdit>
#include <KLocale>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QStackedWidget>
#include <QtGui/QRadioButton>
#include <QtGui/QButtonGroup>
const qreal ValueStep = 0.1;
ComponentTransferEffectConfigWidget::ComponentTransferEffectConfigWidget(QWidget *parent)
: KoFilterEffectConfigWidgetBase(parent), m_effect(0)
, m_currentChannel(ComponentTransferEffect::ChannelR)
{
QGridLayout * g = new QGridLayout(this);
QButtonGroup * group = new QButtonGroup(this);
QRadioButton * butR = new QRadioButton("R", this);
QRadioButton * butG = new QRadioButton("G", this);
QRadioButton * butB = new QRadioButton("B", this);
QRadioButton * butA = new QRadioButton("A", this);
g->addWidget(butR, 0, 0);
g->addWidget(butG, 0, 1);
g->addWidget(butB, 0, 2);
g->addWidget(butA, 0, 3);
group->addButton(butR, ComponentTransferEffect::ChannelR);
group->addButton(butG, ComponentTransferEffect::ChannelG);
group->addButton(butB, ComponentTransferEffect::ChannelB);
group->addButton(butA, ComponentTransferEffect::ChannelA);
butR->setChecked(true);
g->addWidget(new QLabel(i18n("Function"), this), 1, 0, 1, 2);
m_function = new KComboBox(this);
m_function->addItem(i18n("Identity"));
m_function->addItem(i18n("Table"));
m_function->addItem(i18n("Discrete"));
m_function->addItem(i18n("Linear"));
m_function->addItem(i18n("Gamma"));
g->addWidget(m_function, 1, 2, 1, 2);
m_stack = new QStackedWidget(this);
m_stack->setContentsMargins(0, 0, 0, 0);
g->addWidget(m_stack, 2, 0, 1, 4);
// Identity widget
m_stack->addWidget(new QWidget(this));
// Table widget
QWidget * tableWidget = new QWidget(m_stack);
QGridLayout * tableLayout = new QGridLayout(tableWidget);
tableLayout->addWidget(new QLabel(i18n("Values"), tableWidget), 0, 0);
m_tableValues = new KLineEdit(tableWidget);
tableLayout->addWidget(m_tableValues, 0, 1);
tableLayout->setContentsMargins(0, 0, 0, 0);
tableLayout->addItem(new QSpacerItem(0, 1, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding), 1, 0);
m_stack->addWidget(tableWidget);
// Discrete widget
QWidget * discreteWidget = new QWidget(m_stack);
QGridLayout * discreteLayout = new QGridLayout(discreteWidget);
discreteLayout->addWidget(new QLabel(i18n("Values"), discreteWidget), 0, 0);
m_discreteValues = new KLineEdit(discreteWidget);
discreteLayout->addWidget(m_discreteValues, 0, 1);
discreteLayout->setContentsMargins(0, 0, 0, 0);
discreteLayout->addItem(new QSpacerItem(0, 1, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding), 1, 0);
m_stack->addWidget(discreteWidget);
// Linear widget
QWidget * linearWidget = new QWidget(m_stack);
QGridLayout * linearLayout = new QGridLayout(linearWidget);
linearLayout->addWidget(new QLabel(i18n("Slope"), linearWidget), 0, 0);
m_slope = new KDoubleNumInput(linearWidget);
m_slope->setRange(m_slope->minimum(), m_slope->maximum(), ValueStep, false);
linearLayout->addWidget(m_slope, 0, 1);
linearLayout->addWidget(new QLabel(i18n("Intercept")), 1, 0);
m_intercept = new KDoubleNumInput(linearWidget);
m_intercept->setRange(m_intercept->minimum(), m_intercept->maximum(), ValueStep, false);
linearLayout->addWidget(m_intercept, 1, 1);
linearLayout->addItem(new QSpacerItem(0, 1, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding), 2, 0);
linearLayout->setContentsMargins(0, 0, 0, 0);
linearWidget->setLayout(linearLayout);
m_stack->addWidget(linearWidget);
QWidget * gammaWidget = new QWidget(m_stack);
QGridLayout * gammaLayout = new QGridLayout(gammaWidget);
gammaLayout->addWidget(new QLabel(i18n("Amplitude"), gammaWidget), 0, 0);
m_amplitude = new KDoubleNumInput(gammaWidget);
m_amplitude->setRange(m_amplitude->minimum(), m_amplitude->maximum(), ValueStep, false);
gammaLayout->addWidget(m_amplitude, 0, 1);
gammaLayout->addWidget(new QLabel(i18n("Exponent"), gammaWidget), 1, 0);
m_exponent = new KDoubleNumInput(gammaWidget);
m_exponent->setRange(m_exponent->minimum(), m_exponent->maximum(), ValueStep, false);
gammaLayout->addWidget(m_exponent, 1, 1);
gammaLayout->addWidget(new QLabel(i18n("Offset"), gammaWidget), 2, 0);
m_offset = new KDoubleNumInput(gammaWidget);
m_offset->setRange(m_offset->minimum(), m_offset->maximum(), ValueStep, false);
gammaLayout->addWidget(m_offset, 2, 1);
gammaLayout->addItem(new QSpacerItem(0, 1, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding), 3, 0);
gammaLayout->setContentsMargins(0, 0, 0, 0);
gammaWidget->setLayout(gammaLayout);
m_stack->addWidget(gammaWidget);
setLayout(g);
connect(m_function, SIGNAL(currentIndexChanged(int)), m_stack, SLOT(setCurrentIndex(int)));
connect(m_function, SIGNAL(currentIndexChanged(int)), this, SLOT(functionChanged(int)));
connect(m_tableValues, SIGNAL(editingFinished()), this, SLOT(tableValuesChanged()));
connect(m_discreteValues, SIGNAL(editingFinished()), this, SLOT(discreteValuesChanged()));
connect(m_slope, SIGNAL(valueChanged(double)), this, SLOT(slopeChanged(double)));
connect(m_intercept, SIGNAL(valueChanged(double)), this, SLOT(interceptChanged(double)));
connect(m_amplitude, SIGNAL(valueChanged(double)), this, SLOT(amplitudeChanged(double)));
connect(m_exponent, SIGNAL(valueChanged(double)), this, SLOT(exponentChanged(double)));
connect(m_offset, SIGNAL(valueChanged(double)), this, SLOT(offsetChanged(double)));
connect(group, SIGNAL(buttonClicked(int)), this, SLOT(channelSelected(int)));
}
void ComponentTransferEffectConfigWidget::updateControls()
{
m_function->blockSignals(true);
QString values;
switch (m_effect->function(m_currentChannel)) {
case ComponentTransferEffect::Identity:
m_function->setCurrentIndex(0);
break;
case ComponentTransferEffect::Table:
m_function->setCurrentIndex(1);
m_tableValues->blockSignals(true);
foreach(qreal v, m_effect->tableValues(m_currentChannel)) {
values += QString("%1;").arg(v);
}
m_tableValues->setText(values);
m_tableValues->blockSignals(false);
break;
case ComponentTransferEffect::Discrete:
m_function->setCurrentIndex(2);
m_discreteValues->blockSignals(true);
foreach(qreal v, m_effect->tableValues(m_currentChannel)) {
values += QString("%1;").arg(v);
}
m_discreteValues->setText(values);
m_discreteValues->blockSignals(false);
break;
case ComponentTransferEffect::Linear:
m_function->setCurrentIndex(3);
m_slope->blockSignals(true);
m_slope->setValue(m_effect->slope(m_currentChannel));
m_slope->blockSignals(false);
m_intercept->blockSignals(true);
m_intercept->setValue(m_effect->intercept(m_currentChannel));
m_intercept->blockSignals(false);
break;
case ComponentTransferEffect::Gamma:
m_function->setCurrentIndex(4);
m_amplitude->blockSignals(true);
m_amplitude->setValue(m_effect->amplitude(m_currentChannel));
m_amplitude->blockSignals(false);
m_exponent->blockSignals(true);
m_exponent->setValue(m_effect->exponent(m_currentChannel));
m_exponent->blockSignals(false);
m_offset->blockSignals(true);
m_offset->setValue(m_effect->offset(m_currentChannel));
m_offset->blockSignals(false);
break;
}
m_function->blockSignals(false);
m_stack->setCurrentIndex(m_function->currentIndex());
}
bool ComponentTransferEffectConfigWidget::editFilterEffect(KoFilterEffect * filterEffect)
{
m_effect = dynamic_cast<ComponentTransferEffect*>(filterEffect);
if (!m_effect)
return false;
updateControls();
return true;
}
void ComponentTransferEffectConfigWidget::slopeChanged(double slope)
{
if (!m_effect)
return;
m_effect->setSlope(m_currentChannel, slope);
emit filterChanged();
}
void ComponentTransferEffectConfigWidget::interceptChanged(double intercept)
{
if (!m_effect)
return;
m_effect->setIntercept(m_currentChannel, intercept);
emit filterChanged();
}
void ComponentTransferEffectConfigWidget::amplitudeChanged(double amplitude)
{
if (!m_effect)
return;
m_effect->setAmplitude(m_currentChannel, amplitude);
emit filterChanged();
}
void ComponentTransferEffectConfigWidget::exponentChanged(double exponent)
{
if (!m_effect)
return;
m_effect->setExponent(m_currentChannel, exponent);
emit filterChanged();
}
void ComponentTransferEffectConfigWidget::offsetChanged(double offset)
{
if (!m_effect)
return;
m_effect->setOffset(m_currentChannel, offset);
emit filterChanged();
}
void ComponentTransferEffectConfigWidget::tableValuesChanged()
{
QStringList values = m_tableValues->text().split(';', QString::SkipEmptyParts);
QList<qreal> tableValues;
foreach(const QString &v, values) {
tableValues.append(v.toDouble());
}
m_effect->setTableValues(m_currentChannel, tableValues);
emit filterChanged();
}
void ComponentTransferEffectConfigWidget::discreteValuesChanged()
{
QStringList values = m_discreteValues->text().split(';', QString::SkipEmptyParts);
QList<qreal> tableValues;
foreach(const QString &v, values) {
tableValues.append(v.toDouble());
}
m_effect->setTableValues(m_currentChannel, tableValues);
emit filterChanged();
}
void ComponentTransferEffectConfigWidget::functionChanged(int index)
{
if (!m_effect)
return;
m_effect->setFunction(m_currentChannel, static_cast<ComponentTransferEffect::Function>(index));
emit filterChanged();
}
void ComponentTransferEffectConfigWidget::channelSelected(int channel)
{
m_currentChannel = static_cast<ComponentTransferEffect::Channel>(channel);
updateControls();
}
#include "ComponentTransferEffectConfigWidget.moc"
| TheTypoMaster/calligra-history | karbon/plugins/filtereffects/ComponentTransferEffectConfigWidget.cpp | C++ | gpl-2.0 | 11,086 |
#include <config.h>
#include <sampler/SamplerFactory.h>
/* We must have a real destructor, even though it doesn't do anything,
* otherwise the destructors for child classes never get called */
SamplerFactory::~SamplerFactory()
{
}
| kunyang1987/JAGS-MCQMC | src/lib/sampler/SamplerFactory.cc | C++ | gpl-2.0 | 234 |
var Cylon = require('cylon');
Cylon.robot({
connections:{
leapmotion: {adaptor: 'leapmotion'},
ardrone: {adaptor: 'ardrone', port: '192.168.1.1'}
},
devices: {
leapmotion: {driver: 'leapmotion', connection: 'leapmotion'},
drone: {driver: 'ardrone', connection: 'ardrone'},
//nav: { driver: 'ardroneNav' }
},
work: function(my){
// my.drone.config('general:navdata_demo', 'TRUE');
// my.nav.on('update', function(data) {
// console.log(data);
// }),
my.leapmotion.on('hand', function(hand){
if (hand.type === 'right'){
if (hand.pitch() <= 0.25 && hand.pitch() >= -0.15){
console.log("Hover");
my.drone.hover();
}else{
my.drone.forward(hand.pitch());
console.log(hand.pitch());
}
if (hand.roll() <= 0.1 && hand.roll() >= -0.1){
console.log("No Turn");
my.drone.hover();
}else{
console.log("Turn");
my.drone.left(hand.roll());
}
if (hand.palmPosition[1] >= 150){
console.log("takeoff");
my.drone.takeoff();
}else{
console.log("land");
my.drone.land();
}
}
});
}
}).start();
| AlphaNerds/alphaDrone | node_modules/cylon-leapmotion/examples/leap/leapDrone.js | JavaScript | gpl-2.0 | 1,236 |
<?php
/**
* MyBB 1.6
* Copyright 2010 MyBB Group, All Rights Reserved
*
* Website: http://mybb.com
* License: http://mybb.com/about/license
*
* $Id$
*/
class Moderation
{
/**
* Close one or more threads
*
* @param array Thread IDs
* @return boolean true
*/
function close_threads($tids)
{
global $db, $plugins;
if(!is_array($tids))
{
$tids = array($tids);
}
// Make sure we only have valid values
$tids = array_map('intval', $tids);
$plugins->run_hooks("class_moderation_close_threads", $tids);
$tid_list = implode(',', $tids);
$openthread = array(
"closed" => 1,
);
$db->update_query("threads", $openthread, "tid IN ($tid_list) AND closed NOT LIKE 'moved|%'");
return true;
}
/**
* Open one or more threads
*
* @param int Thread IDs
* @return boolean true
*/
function open_threads($tids)
{
global $db, $plugins;
if(!is_array($tids))
{
$tids = array($tids);
}
// Make sure we only have valid values
$tids = array_map('intval', $tids);
$plugins->run_hooks("class_moderation_open_threads", $tids);
$tid_list = implode(',', $tids);
$closethread = array(
"closed" => 0,
);
$db->update_query("threads", $closethread, "tid IN ($tid_list)");
return true;
}
/**
* Stick one or more threads
*
* @param int Thread IDs
* @return boolean true
*/
function stick_threads($tids)
{
global $db, $plugins;
if(!is_array($tids))
{
$tids = array($tids);
}
// Make sure we only have valid values
$tids = array_map('intval', $tids);
$plugins->run_hooks("class_moderation_stick_threads", $tids);
$tid_list = implode(',', $tids);
$stickthread = array(
"sticky" => 1,
);
$db->update_query("threads", $stickthread, "tid IN ($tid_list)");
return true;
}
/**
* Unstick one or more thread
*
* @param int Thread IDs
* @return boolean true
*/
function unstick_threads($tids)
{
global $db, $plugins;
if(!is_array($tids))
{
$tids = array($tids);
}
// Make sure we only have valid values
$tids = array_map('intval', $tids);
$plugins->run_hooks("class_moderation_unstick_threads", $tids);
$tid_list = implode(',', $tids);
$unstickthread = array(
"sticky" => 0,
);
$db->update_query("threads", $unstickthread, "tid IN ($tid_list)");
return true;
}
/**
* Remove redirects that redirect to the specified thread
*
* @param int Thread ID of the thread
* @return boolean true
*/
function remove_redirects($tid)
{
global $db, $plugins;
$plugins->run_hooks("class_moderation_remove_redirects", $tid);
// Delete the redirects
$tid = intval($tid);
$db->delete_query("threads", "closed='moved|$tid'");
return true;
}
/**
* Delete a thread
*
* @param int Thread ID of the thread
* @return boolean true
*/
function delete_thread($tid)
{
global $db, $cache, $plugins;
$tid = intval($tid);
$plugins->run_hooks("class_moderation_delete_thread_start", $tid);
$thread = get_thread($tid);
$userposts = array();
// Find the pid, uid, visibility, and forum post count status
$query = $db->query("
SELECT p.pid, p.uid, p.visible, f.usepostcounts
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."forums f ON (f.fid=p.fid)
WHERE p.tid='{$tid}'
");
$pids = array();
$num_unapproved_posts = $num_approved_posts = 0;
while($post = $db->fetch_array($query))
{
$pids[] = $post['pid'];
$usepostcounts = $post['usepostcounts'];
if(!function_exists("remove_attachments"))
{
require MYBB_ROOT."inc/functions_upload.php";
}
// Remove attachments
remove_attachments($post['pid']);
// If the post is unapproved, count it!
if($post['visible'] == 0 || $thread['visible'] == 0)
{
$num_unapproved_posts++;
}
else
{
$num_approved_posts++;
// Count the post counts for each user to be subtracted
++$userposts[$post['uid']];
}
}
// Remove post count from users
if($usepostcounts != 0)
{
if(is_array($userposts))
{
foreach($userposts as $uid => $subtract)
{
$db->update_query("users", array('postnum' => "postnum-{$subtract}"), "uid='".intval($uid)."'", 1, true);
}
}
}
// Delete posts and their attachments
if($pids)
{
$pids = implode(',', $pids);
$db->delete_query("posts", "pid IN ($pids)");
$db->delete_query("attachments", "pid IN ($pids)");
$db->delete_query("reportedposts", "pid IN ($pids)");
}
// Implied counters for unapproved thread
if($thread['visible'] == 0)
{
$num_unapproved_posts += $num_approved_posts;
}
// Delete threads, redirects, subscriptions, polls, and poll votes
$db->delete_query("threads", "tid='$tid'");
$db->delete_query("threads", "closed='moved|$tid'");
$db->delete_query("threadsubscriptions", "tid='$tid'");
$db->delete_query("polls", "tid='$tid'");
$db->delete_query("pollvotes", "pid='".$thread['poll']."'");
$db->delete_query("threadsread", "tid='$tid'");
$db->delete_query("threadratings", "tid='$tid'");
$updated_counters = array(
"posts" => "-{$num_approved_posts}",
"unapprovedposts" => "-{$num_unapproved_posts}"
);
if($thread['visible'] == 1)
{
$updated_counters['threads'] = -1;
}
else
{
$updated_counters['unapprovedthreads'] = -1;
}
if(substr($thread['closed'], 0, 5) != "moved")
{
// Update forum count
update_forum_counters($thread['fid'], $updated_counters);
}
$plugins->run_hooks("class_moderation_delete_thread", $tid);
return true;
}
/**
* Delete a poll
*
* @param int Poll id
* @return boolean true
*/
function delete_poll($pid)
{
global $db, $plugins;
$pid = intval($pid);
$plugins->run_hooks("class_moderation_delete_poll", $pid);
$db->delete_query("polls", "pid='$pid'");
$db->delete_query("pollvotes", "pid='$pid'");
$pollarray = array(
'poll' => '0',
);
$db->update_query("threads", $pollarray, "poll='$pid'");
return true;
}
/**
* Approve one or more threads
*
* @param array Thread IDs
* @return boolean true
*/
function approve_threads($tids)
{
global $db, $cache, $plugins;
if(!is_array($tids))
{
$tids = array($tids);
}
// Make sure we only have valid values
$tids = array_map('intval', $tids);
foreach($tids as $tid)
{
$thread = get_thread($tid);
if($thread['visible'] == 1 || !$thread['tid'])
{
continue;
}
$tid_list[] = $thread['tid'];
$forum = get_forum($thread['fid']);
$forum_counters[$forum['fid']]['num_threads']++;
$forum_counters[$forum['fid']]['num_posts'] += $thread['replies']+1; // Remove implied visible from count
if($forum['usepostcounts'] != 0)
{
// On approving thread restore user post counts
$query = $db->simple_select("posts", "COUNT(pid) as posts, uid", "tid='{$tid}' AND (visible='1' OR pid='{$thread['firstpost']}') AND uid > 0 GROUP BY uid");
while($counter = $db->fetch_array($query))
{
$db->update_query("users", array('postnum' => "postnum+{$counter['posts']}"), "uid='".$counter['uid']."'", 1, true);
}
}
$posts_to_approve[] = $thread['firstpost'];
}
if(is_array($tid_list))
{
$tid_moved_list = "";
$comma = "";
foreach($tid_list as $tid)
{
$tid_moved_list .= "{$comma}'moved|{$tid}'";
$comma = ",";
}
$tid_list = implode(',', $tid_list);
$approve = array(
"visible" => 1
);
$db->update_query("threads", $approve, "tid IN ($tid_list) OR closed IN ({$tid_moved_list})");
$db->update_query("posts", $approve, "pid IN (".implode(',', $posts_to_approve).")");
$plugins->run_hooks("class_moderation_approve_threads", $tids);
if(is_array($forum_counters))
{
foreach($forum_counters as $fid => $counters)
{
// Update stats
$update_array = array(
"threads" => "+{$counters['num_threads']}",
"unapprovedthreads" => "-{$counters['num_threads']}",
"posts" => "+{$counters['num_posts']}",
"unapprovedposts" => "-{$counters['num_posts']}"
);
update_forum_counters($fid, $update_array);
}
}
}
return true;
}
/**
* Unapprove one or more threads
*
* @param array Thread IDs
* @return boolean true
*/
function unapprove_threads($tids)
{
global $db, $cache, $plugins;
if(!is_array($tids))
{
$tids = array($tids);
}
// Make sure we only have valid values
$tids = array_map('intval', $tids);
$tid_list = implode(',', $tids);
$tid_moved_list = "";
$comma = "";
foreach($tids as $tid)
{
$tid_moved_list .= "{$comma}'moved|{$tid}'";
$comma = ",";
}
foreach($tids as $tid)
{
$thread = get_thread($tid);
$forum = get_forum($thread['fid']);
if($thread['visible'] == 1)
{
$forum_counters[$forum['fid']]['num_threads']++;
$forum_counters[$forum['fid']]['num_posts'] += $thread['replies']+1; // Add implied invisible to count
// On unapproving thread update user post counts
if($forum['usepostcounts'] != 0)
{
$query = $db->simple_select("posts", "COUNT(pid) AS posts, uid", "tid='{$tid}' AND (visible='1' OR pid='{$thread['firstpost']}') AND uid > 0 GROUP BY uid");
while($counter = $db->fetch_array($query))
{
$db->update_query("users", array('postnum' => "postnum-{$counter['posts']}"), "uid='".$counter['uid']."'", 1, true);
}
}
}
$posts_to_unapprove[] = $thread['firstpost'];
}
$approve = array(
"visible" => 0
);
$db->update_query("threads", $approve, "tid IN ($tid_list) OR closed IN ({$tid_moved_list})");
$db->update_query("posts", $approve, "pid IN (".implode(',', $posts_to_unapprove).")");
$plugins->run_hooks("class_moderation_unapprove_threads", $tids);
if(is_array($forum_counters))
{
foreach($forum_counters as $fid => $counters)
{
// Update stats
$update_array = array(
"threads" => "-{$counters['num_threads']}",
"unapprovedthreads" => "+{$counters['num_threads']}",
"posts" => "-{$counters['num_posts']}",
"unapprovedposts" => "+{$counters['num_posts']}"
);
update_forum_counters($fid, $update_array);
}
}
return true;
}
/**
* Delete a specific post
*
* @param int Post ID
* @return boolean true
*/
function delete_post($pid)
{
global $db, $cache, $plugins;
$pid = $plugins->run_hooks("class_moderation_delete_post_start", $pid);
// Get pid, uid, fid, tid, visibility, forum post count status of post
$pid = intval($pid);
$query = $db->query("
SELECT p.pid, p.uid, p.fid, p.tid, p.visible, f.usepostcounts, t.visible as threadvisible
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
LEFT JOIN ".TABLE_PREFIX."forums f ON (f.fid=p.fid)
WHERE p.pid='$pid'
");
$post = $db->fetch_array($query);
// If post counts enabled in this forum and it hasn't already been unapproved, remove 1
if($post['usepostcounts'] != 0 && $post['visible'] != 0 && $post['threadvisible'] != 0)
{
$db->update_query("users", array("postnum" => "postnum-1"), "uid='{$post['uid']}'", 1, true);
}
if(!function_exists("remove_attachments"))
{
require MYBB_ROOT."inc/functions_upload.php";
}
// Remove attachments
remove_attachments($pid);
// Delete the post
$db->delete_query("posts", "pid='$pid'");
// Remove any reports attached to this post
$db->delete_query("reportedposts", "pid='$pid'");
$num_unapproved_posts = $num_approved_posts = 0;
// Update unapproved post count
if($post['visible'] == 0 || $post['threadvisible'] == 0)
{
++$num_unapproved_posts;
}
else
{
++$num_approved_posts;
}
$plugins->run_hooks("class_moderation_delete_post", $post['pid']);
// Update stats
$update_array = array(
"replies" => "-{$num_approved_posts}",
"unapprovedposts" => "-{$num_unapproved_posts}"
);
update_thread_counters($post['tid'], $update_array);
// Update stats
$update_array = array(
"posts" => "-{$num_approved_posts}",
"unapprovedposts" => "-{$num_unapproved_posts}"
);
update_forum_counters($post['fid'], $update_array);
return true;
}
/**
* Merge posts within thread
*
* @param array Post IDs to be merged
* @param int Thread ID (Set to 0 if posts from multiple threads are
* selected)
* @return int ID of the post into which all other posts are merged
*/
function merge_posts($pids, $tid=0, $sep="new_line")
{
global $db, $plugins;
// Make sure we only have valid values
$pids = array_map('intval', $pids);
$tid = intval($tid);
$pidin = implode(',', $pids);
$attachment_count = 0;
$first = 1;
// Get the messages to be merged
$query = $db->query("
SELECT p.pid, p.uid, p.fid, p.tid, p.visible, p.message, f.usepostcounts, t.visible AS threadvisible, t.replies AS threadreplies, t.firstpost AS threadfirstpost, t.unapprovedposts AS threadunapprovedposts
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
LEFT JOIN ".TABLE_PREFIX."forums f ON (f.fid=p.fid)
WHERE p.pid IN($pidin)
ORDER BY p.dateline ASC
");
$num_unapproved_posts = $num_approved_posts = 0;
$message = '';
while($post = $db->fetch_array($query))
{
if($first == 1)
{ // all posts will be merged into this one
$masterpid = $post['pid'];
$message = $post['message'];
$fid = $post['fid'];
$mastertid = $post['tid'];
$first = 0;
}
else
{
// these are the selected posts
if($sep == "new_line")
{
$message .= "\n\n {$post['message']}";
}
else
{
$message .= "[hr]{$post['message']}";
}
if($post['visible'] == 1 && $post['threadvisible'] == 1)
{
// Subtract 1 approved post from post's thread
if(!$thread_counters[$post['tid']]['replies'])
{
$thread_counters[$post['tid']]['replies'] = $post['threadreplies'];
}
--$thread_counters[$post['tid']]['replies'];
// Subtract 1 approved post from post's forum
if(!isset($forum_counters[$post['fid']]['num_posts']))
{
$forum_counters[$post['fid']]['num_posts'] = 0;
}
--$forum_counters[$post['fid']]['num_posts'];
// Subtract 1 from user's post count
if($post['usepostcounts'] != 0)
{
// Update post count of the user of the merged posts
$db->update_query("users", array("postnum" => "postnum-1"), "uid='{$post['uid']}'", 1, true);
}
}
elseif($post['visible'] == 0)
{
// Subtract 1 unapproved post from post's thread
if(!$thread_counters[$post['tid']]['unapprovedposts'])
{
$thread_counters[$post['tid']]['unapprovedposts'] = $post['threadunapprovedposts'];
}
--$thread_counters[$post['tid']]['unapprovedposts'];
// Subtract 1 unapproved post from post's forum
if(!isset($forum_counters[$post['fid']]['unapprovedposts']))
{
$forum_counters[$post['fid']]['unapprovedposts'] = 0;
}
--$forum_counters[$post['fid']]['unapprovedposts'];
}
}
}
$query2 = $db->simple_select("attachments", "COUNT(aid) as count", "pid IN({$pidin}) AND visible='1'");
$attachment_count = $db->fetch_field($query2, "count");
$db->update_query("threads", array("attachmentcount" => $attachment_count), "tid = '{$mastertid}'");
// Update the message
$mergepost = array(
"message" => $db->escape_string($message),
);
$db->update_query("posts", $mergepost, "pid = '{$masterpid}'");
// Delete the extra posts
$db->delete_query("posts", "pid IN({$pidin}) AND pid != '{$masterpid}'");
// Update pid for attachments
$mergepost2 = array(
"pid" => $masterpid,
);
$db->update_query("attachments", $mergepost2, "pid IN({$pidin})");
// If the first post of a thread is merged out, the thread should be deleted
$query = $db->simple_select("threads", "tid, fid, visible", "firstpost IN({$pidin}) AND firstpost != '{$masterpid}'");
while($thread = $db->fetch_array($query))
{
$this->delete_thread($thread['tid']);
// Subtract 1 thread from the forum's stats
if($thread['visible'])
{
if(!isset($forum_counters[$thread['fid']]['threads']))
{
$forum_counters[$thread['fid']]['threads'] = 0;
}
--$forum_counters[$thread['fid']]['threads'];
}
else
{
if(!isset($forum_counters[$thread['fid']]['unapprovedthreads']))
{
$forum_counters[$thread['fid']]['unapprovedthreads'] = 0;
}
--$forum_counters[$thread['fid']]['unapprovedthreads'];
}
}
$arguments = array("pids" => $pids, "tid" => $tid);
$plugins->run_hooks("class_moderation_merge_posts", $arguments);
if(is_array($thread_counters))
{
foreach($thread_counters as $tid => $counters)
{
$db->update_query("threads", $counters, "tid='{$tid}'");
update_thread_data($tid);
}
}
update_thread_data($mastertid);
update_forum_lastpost($fid);
if(is_array($forum_counters))
{
foreach($forum_counters as $fid => $counters)
{
$updated_forum_stats = array(
'posts' => signed($counters['num_posts']),
'unapprovedposts' => signed($counters['unapprovedposts']),
'threads' => signed($counters['threads']),
);
update_forum_counters($fid, $updated_forum_stats);
}
}
return $masterpid;
}
/**
* Move/copy thread
*
* @param int Thread to be moved
* @param int Destination forum
* @param string Method of movement (redirect, copy, move)
* @param int Expiry timestamp for redirect
* @return int Thread ID
*/
function move_thread($tid, $new_fid, $method="redirect", $redirect_expire=0)
{
global $db, $plugins;
// Get thread info
$tid = intval($tid);
$new_fid = intval($new_fid);
$redirect_expire = intval($redirect_expire);
$thread = get_thread($tid, true);
$newforum = get_forum($new_fid);
$fid = $thread['fid'];
$forum = get_forum($fid);
$num_threads = $num_unapproved_threads = $num_posts = $num_unapproved_threads = 0;
switch($method)
{
case "redirect": // move (and leave redirect) thread
$arguments = array("tid" => $tid, "new_fid" => $new_fid);
$plugins->run_hooks("class_moderation_move_thread_redirect", $arguments);
if($thread['visible'] == 1)
{
$num_threads++;
$num_posts = $thread['replies']+1;
}
else
{
$num_unapproved_threads++;
// Implied forum unapproved count for unapproved threads
$num_unapproved_posts = $thread['replies']+1;
}
$num_unapproved_posts += $thread['unapprovedposts'];
$db->delete_query("threads", "closed='moved|$tid' AND fid='$new_fid'");
$changefid = array(
"fid" => $new_fid,
);
$db->update_query("threads", $changefid, "tid='$tid'");
$db->update_query("posts", $changefid, "tid='$tid'");
// If the thread has a prefix and the destination forum doesn't accept that prefix, remove the prefix
if($thread['prefix'] != 0)
{
$query = $db->simple_select("threadprefixes", "COUNT(*) as num_prefixes", "(CONCAT(',',forums,',') LIKE '%,$new_fid,%' OR forums='-1') AND pid='".$thread['prefix']."'");
if($db->fetch_field($query, "num_prefixes") == 0)
{
$sqlarray = array(
"prefix" => 0,
);
$db->update_query("threads", $sqlarray, "tid='$tid'");
}
}
$threadarray = array(
"fid" => $thread['fid'],
"subject" => $db->escape_string($thread['subject']),
"icon" => $thread['icon'],
"uid" => $thread['uid'],
"username" => $db->escape_string($thread['username']),
"dateline" => $thread['dateline'],
"lastpost" => $thread['lastpost'],
"lastposteruid" => $thread['lastposteruid'],
"lastposter" => $db->escape_string($thread['lastposter']),
"views" => 0,
"replies" => 0,
"closed" => "moved|$tid",
"sticky" => $thread['sticky'],
"visible" => intval($thread['visible']),
"notes" => ''
);
$redirect_tid = $db->insert_query("threads", $threadarray);
if($redirect_expire)
{
$this->expire_thread($redirect_tid, $redirect_expire);
}
// If we're moving back to a forum where we left a redirect, delete the rediect
$query = $db->simple_select("threads", "tid", "closed LIKE 'moved|".intval($tid)."' AND fid='".intval($new_fid)."'");
while($movedthread = $db->fetch_array($query))
{
$db->delete_query("threads", "tid='".intval($movedthread['tid'])."'", 1);
}
break;
case "copy":// copy thread
$threadarray = array(
"fid" => $new_fid,
"subject" => $db->escape_string($thread['subject']),
"icon" => $thread['icon'],
"uid" => $thread['uid'],
"username" => $db->escape_string($thread['username']),
"dateline" => $thread['dateline'],
"firstpost" => 0,
"lastpost" => $thread['lastpost'],
"lastposteruid" => $thread['lastposteruid'],
"lastposter" => $db->escape_string($thread['lastposter']),
"views" => $thread['views'],
"replies" => $thread['replies'],
"closed" => $thread['closed'],
"sticky" => $thread['sticky'],
"visible" => intval($thread['visible']),
"unapprovedposts" => $thread['unapprovedposts'],
"attachmentcount" => $thread['attachmentcount'],
"prefix" => $thread['prefix'],
"notes" => ''
);
if($thread['visible'] == 1)
{
++$num_threads;
$num_posts = $thread['replies']+1;
// Fetch count of unapproved posts in this thread
$query = $db->simple_select("posts", "COUNT(pid) AS unapproved", "tid='{$thread['tid']}' AND visible=0");
$num_unapproved_posts = $db->fetch_field($query, "unapproved");
}
else
{
$num_unapproved_threads++;
$num_unapproved_posts = $thread['replies']+1;
}
$arguments = array("tid" => $tid, "new_fid" => $new_fid);
$plugins->run_hooks("class_moderation_copy_thread", $arguments);
// If the thread has a prefix and the destination forum doesn't accept that prefix, don't copy the prefix
if($threadarray['prefix'] != 0)
{
$query = $db->simple_select("threadprefixes", "COUNT(*) as num_prefixes", "(CONCAT(',',forums,',') LIKE '%,$new_fid,%' OR forums='-1') AND pid='".$thread['prefix']."'");
if($db->fetch_field($query, "num_prefixes") == 0)
{
$threadarray['prefix'] = 0;
}
}
$newtid = $db->insert_query("threads", $threadarray);
if($thread['poll'] != 0)
{
$query = $db->simple_select("polls", "*", "tid = '{$thread['tid']}'");
$poll = $db->fetch_array($query);
$poll_array = array(
'tid' => $newtid,
'question' => $db->escape_string($poll['question']),
'dateline' => $poll['dateline'],
'options' => $db->escape_string($poll['options']),
'votes' => $poll['votes'],
'numoptions' => $poll['numoptions'],
'numvotes' => $poll['numvotes'],
'timeout' => $poll['timeout'],
'closed' => $poll['closed'],
'multiple' => $poll['multiple'],
'public' => $poll['public']
);
$new_pid = $db->insert_query("polls", $poll_array);
$query = $db->simple_select("pollvotes", "*", "pid = '{$poll['pid']}'");
while($pollvote = $db->fetch_array($query))
{
$pollvote_array = array(
'pid' => $new_pid,
'uid' => $pollvote['uid'],
'voteoption' => $pollvote['voteoption'],
'dateline' => $pollvote['dateline'],
);
$db->insert_query("pollvotes", $pollvote_array);
}
$db->update_query("threads", array('poll' => $new_pid), "tid='{$newtid}'");
}
$query = $db->simple_select("posts", "*", "tid = '{$thread['tid']}'");
while($post = $db->fetch_array($query))
{
$post_array = array(
'tid' => $newtid,
'fid' => $new_fid,
'subject' => $db->escape_string($post['subject']),
'icon' => $post['icon'],
'uid' => $post['uid'],
'username' => $db->escape_string($post['username']),
'dateline' => $post['dateline'],
'ipaddress' => $post['ipaddress'],
'includesig' => $post['includesig'],
'smilieoff' => $post['smilieoff'],
'edituid' => $post['edituid'],
'edittime' => $post['edittime'],
'visible' => $post['visible'],
'message' => $db->escape_string($post['message']),
);
$pid = $db->insert_query("posts", $post_array);
// Properly set our new firstpost in our new thread
if($thread['firstpost'] == $post['pid'])
{
$db->update_query("threads", array('firstpost' => $pid), "tid='{$newtid}'");
}
// Insert attachments for this post
$query2 = $db->simple_select("attachments", "*", "pid = '{$post['pid']}'");
while($attachment = $db->fetch_array($query2))
{
$attachment_array = array(
'pid' => $pid,
'uid' => $attachment['uid'],
'filename' => $db->escape_string($attachment['filename']),
'filetype' => $attachment['filetype'],
'filesize' => $attachment['filesize'],
'attachname' => $attachment['attachname'],
'downloads' => $attachment['downloads'],
'visible' => $attachment['visible'],
'thumbnail' => $attachment['thumbnail']
);
$new_aid = $db->insert_query("attachments", $attachment_array);
$post['message'] = str_replace("[attachment={$attachment['aid']}]", "[attachment={$new_aid}]", $post['message']);
}
if(strpos($post['message'], "[attachment=") !== false)
{
$db->update_query("posts", array('message' => $db->escape_string($post['message'])), "pid='{$pid}'");
}
}
update_thread_data($newtid);
$the_thread = $newtid;
break;
default:
case "move": // plain move thread
$arguments = array("tid" => $tid, "new_fid" => $new_fid);
$plugins->run_hooks("class_moderation_move_simple", $arguments);
if($thread['visible'] == 1)
{
$num_threads++;
$num_posts = $thread['replies']+1;
}
else
{
$num_unapproved_threads++;
// Implied forum unapproved count for unapproved threads
$num_unapproved_posts = $thread['replies']+1;
}
$num_unapproved_posts = $thread['unapprovedposts'];
$sqlarray = array(
"fid" => $new_fid,
);
$db->update_query("threads", $sqlarray, "tid='$tid'");
$db->update_query("posts", $sqlarray, "tid='$tid'");
// If the thread has a prefix and the destination forum doesn't accept that prefix, remove the prefix
if($thread['prefix'] != 0)
{
$query = $db->simple_select("threadprefixes", "COUNT(*) as num_prefixes", "(CONCAT(',',forums,',') LIKE '%,$new_fid,%' OR forums='-1') AND pid='".$thread['prefix']."'");
if($db->fetch_field($query, "num_prefixes") == 0)
{
$sqlarray = array(
"prefix" => 0,
);
$db->update_query("threads", $sqlarray, "tid='$tid'");
}
}
// If we're moving back to a forum where we left a redirect, delete the rediect
$query = $db->simple_select("threads", "tid", "closed LIKE 'moved|".intval($tid)."' AND fid='".intval($new_fid)."'");
while($movedthread = $db->fetch_array($query))
{
$db->delete_query("threads", "tid='".intval($movedthread['tid'])."'", 1);
}
break;
}
// Do post count changes if changing between countable and non-countable forums
$query = $db->query("
SELECT COUNT(p.pid) AS posts, u.uid, p.visible
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=p.uid)
WHERE tid='$tid'
GROUP BY u.uid, p.visible
ORDER BY posts DESC
");
while($posters = $db->fetch_array($query))
{
$pcount = "";
if($forum['usepostcounts'] == 1 && $newforum['usepostcounts'] == 0 && $posters['visible'] == 1)
{
$pcount = "-{$posters['posts']}";
}
else if($forum['usepostcounts'] == 0 && $newforum['userpostcounts'] == 1 && $posters['visible'] == 1)
{
$pcount = "+{$posters['posts']}";
}
if(!empty($pcount))
{
$db->update_query("users", array("postnum" => "postnum{$pcount}"), "uid='{$posters['uid']}'", 1, true);
}
}
// Update forum counts
$update_array = array(
"threads" => "+{$num_threads}",
"unapprovedthreads" => "+{$num_unapproved_threads}",
"posts" => "+{$num_posts}",
"unapprovedposts" => "+{$num_unapproved_posts}"
);
update_forum_counters($new_fid, $update_array);
if($method != "copy")
{
$update_array = array(
"threads" => "-{$num_threads}",
"unapprovedthreads" => "-{$num_unapproved_threads}",
"posts" => "-{$num_posts}",
"unapprovedposts" => "-{$num_unapproved_posts}"
);
update_forum_counters($fid, $update_array);
}
if(isset($newtid))
{
return $newtid;
}
else
{
// Remove thread subscriptions for the users who no longer have permission to view the thread
$this->remove_thread_subscriptions($tid, false, $new_fid);
return $tid;
}
}
/**
* Merge one thread into another
*
* @param int Thread that will be merged into destination
* @param int Destination thread
* @param string New thread subject
* @return boolean true
*/
function merge_threads($mergetid, $tid, $subject)
{
global $db, $mybb, $mergethread, $thread, $plugins;
$mergetid = intval($mergetid);
$tid = intval($tid);
if(!isset($mergethread['tid']) || $mergethread['tid'] != $mergetid)
{
$query = $db->simple_select("threads", "*", "tid='{$mergetid}'");
$mergethread = $db->fetch_array($query);
}
if(!isset($thread['tid']) || $thread['tid'] != $tid)
{
$query = $db->simple_select("threads", "*", "tid='{$tid}'");
$thread = $db->fetch_array($query);
}
$pollsql = '';
if($mergethread['poll'])
{
$pollsql['poll'] = $mergethread['poll'];
$sqlarray = array(
"tid" => $tid,
);
$db->update_query("polls", $sqlarray, "tid='".intval($mergethread['tid'])."'");
}
else
{
$query = $db->simple_select("threads", "*", "poll='{$mergethread['poll']}' AND tid != '{$mergetid}'");
$pollcheck = $db->fetch_array($query);
if(!$pollcheck['poll'])
{
$db->delete_query("polls", "pid='{$mergethread['poll']}'");
$db->delete_query("pollvotes", "pid='{$mergethread['poll']}'");
}
}
$subject = $db->escape_string($subject);
$sqlarray = array(
"tid" => $tid,
"fid" => $thread['fid'],
"replyto" => 0,
);
$db->update_query("posts", $sqlarray, "tid='{$mergetid}'");
$pollsql['subject'] = $subject;
$db->update_query("threads", $pollsql, "tid='{$tid}'");
$sqlarray = array(
"closed" => "moved|{$tid}",
);
$db->update_query("threads", $sqlarray, "closed='moved|{$mergetid}'");
$sqlarray = array(
"tid" => $tid,
);
// Update the thread ratings
$new_numrating = $thread['numratings'] + $mergethread['numratings'];
$new_threadrating = $thread['totalratings'] + $mergethread['totalratings'];
$sqlarray = array(
"numratings" => $new_numrating,
"totalratings" => $new_threadrating
);
$db->update_query("threads", $sqlarray, "tid = '{$tid}'");
// Check if we have a thread subscription already for our new thread
$subscriptions = array(
$tid => array(),
$mergetid => array()
);
$query = $db->simple_select("threadsubscriptions", "tid, uid", "tid='{$mergetid}' OR tid='{$tid}'");
while($subscription = $db->fetch_array($query))
{
$subscriptions[$subscription['tid']][] = $subscription['uid'];
}
// Update any subscriptions for the merged thread
if(is_array($subscriptions[$mergetid]))
{
$update_users = array();
foreach($subscriptions[$mergetid] as $user)
{
if(!in_array($user, $subscriptions[$tid]))
{
// User doesn't have a $tid subscription
$update_users[] = $user;
}
}
if(!empty($update_users))
{
$update_array = array(
"tid" => $tid
);
$update_users = implode(",", $update_users);
$db->update_query("threadsubscriptions", $update_array, "tid = '{$mergetid}' AND uid IN ({$update_users})");
}
}
// Remove source thread subscriptions
$db->delete_query("threadsubscriptions", "tid = '{$mergetid}'");
update_first_post($tid);
$arguments = array("mergetid" => $mergetid, "tid" => $tid, "subject" => $subject);
$plugins->run_hooks("class_moderation_merge_threads", $arguments);
$this->delete_thread($mergetid);
// In some cases the thread we may be merging with may cause us to have a new firstpost if it is an older thread
// Therefore resync the visible field to make sure they're the same if they're not
$query = $db->simple_select("posts", "pid, visible", "tid='{$tid}'", array('order_by' => 'dateline', 'order_dir' => 'asc', 'limit' => 1));
$new_firstpost = $db->fetch_array($query);
if($thread['visible'] != $new_firstpost['visible'])
{
$db->update_query("posts", array('visible' => $thread['visible']), "pid='{$new_firstpost['pid']}'");
$mergethread['visible'] = $thread['visible'];
}
$updated_stats = array(
"replies" => '+'.($mergethread['replies']+1),
"attachmentcount" => "+{$mergethread['attachmentcount']}",
"unapprovedposts" => "+{$mergethread['unapprovedposts']}"
);
update_thread_counters($tid, $updated_stats);
// Thread is not in current forum
if($mergethread['fid'] != $thread['fid'])
{
// If new thread is unapproved, implied counter comes in to effect
if($thread['visible'] == 0 || $mergethread['visible'] == 0)
{
$updated_stats = array(
"unapprovedposts" => '+'.($mergethread['replies']+1+$mergethread['unapprovedposts'])
);
}
else
{
$updated_stats = array(
"posts" => '+'.($mergethread['replies']+1),
"unapprovedposts" => "+{$mergethread['unapprovedposts']}"
);
}
update_forum_counters($thread['fid'], $updated_stats);
// If old thread is unapproved, implied counter comes in to effect
if($mergethread['visible'] == 0)
{
$updated_stats = array(
"unapprovedposts" => '-'.($mergethread['replies']+1+$mergethread['unapprovedposts'])
);
}
else
{
$updated_stats = array(
"posts" => '-'.($mergethread['replies']+1),
"unapprovedposts" => "-{$mergethread['unapprovedposts']}"
);
}
update_forum_counters($mergethread['fid'], $updated_stats);
}
// If we're in the same forum we need to at least update the last post information
else
{
update_forum_lastpost($thread['fid']);
}
return true;
}
/**
* Split posts into a new/existing thread
*
* @param array PIDs of posts to split
* @param int Original thread ID (this is only used as a base for the new
* thread; it can be set to 0 when the posts specified are coming from more
* than 1 thread)
* @param int Destination forum
* @param string New thread subject
* @param int TID if moving into existing thread
* @return int New thread ID
*/
function split_posts($pids, $tid, $moveto, $newsubject, $destination_tid=0)
{
global $db, $thread, $plugins;
$tid = intval($tid);
$moveto = intval($moveto);
$newtid = intval($destination_tid);
// Get forum infos
$query = $db->simple_select("forums", "fid, usepostcounts, posts, threads, unapprovedposts, unapprovedthreads");
while($forum = $db->fetch_array($query))
{
$forum_cache[$forum['fid']] = $forum;
}
// Make sure we only have valid values
$pids = array_map('intval', $pids);
$pids_list = implode(',', $pids);
// Get the icon for the first split post
$query = $db->simple_select("posts", "icon, visible", "pid=".intval($pids[0]));
$post_info = $db->fetch_array($query);
$icon = $post_info['icon'];
$visible = $post_info['visible'];
if($destination_tid == 0)
{
// Splitting into a new thread
$thread = get_thread($tid);
// Create the new thread
$newsubject = $db->escape_string($newsubject);
$query = array(
"fid" => $moveto,
"subject" => $newsubject,
"icon" => intval($icon),
"uid" => intval($thread['uid']),
"username" => $db->escape_string($thread['username']),
"dateline" => intval($thread['dateline']),
"lastpost" => intval($thread['lastpost']),
"lastposter" => $db->escape_string($thread['lastposter']),
"replies" => count($pids)-1,
"visible" => intval($visible),
"notes" => ''
);
$newtid = $db->insert_query("threads", $query);
$forum_counters[$moveto]['threads'] = $forum_cache[$moveto]['threads'];
$forum_counters[$moveto]['unapprovedthreads'] = $forum_cache[$moveto]['unapprovedthreads'];
if($visible)
{
++$forum_counters[$moveto]['threads'];
}
else
{
// Unapproved thread?
++$forum_counters[$moveto]['unapprovedthreads'];
}
}
// Get attachment counts for each post
/*$query = $db->simple_select("attachments", "COUNT(aid) as count, pid", "pid IN ($pids_list)");
$query = $db->query("
SELECT COUNT(aid) as count, p.pid,
");
$attachment_sum = 0;
while($attachment = $db->fetch_array($query))
{
$attachments[$attachment['pid']] = $attachment['count'];
$attachment_sum += $attachment['count'];
}
$thread_counters[$newtid]['attachmentcount'] = '+'.$attachment_sum;*/
// Get selected posts before moving forums to keep old fid
//$original_posts_query = $db->simple_select("posts", "fid, visible, pid", "pid IN ($pids_list)");
$original_posts_query = $db->query("
SELECT p.pid, p.tid, p.fid, p.visible, p.uid, t.visible as threadvisible, t.replies as threadreplies, t.unapprovedposts as threadunapprovedposts, t.attachmentcount as threadattachmentcount, COUNT(a.aid) as postattachmentcount
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."threads t ON (p.tid=t.tid)
LEFT JOIN ".TABLE_PREFIX."attachments a ON (a.pid=p.pid)
WHERE p.pid IN ($pids_list)
GROUP BY p.pid, p.tid, p.fid, p.visible, p.uid, t.visible, t.replies, t.unapprovedposts,t.attachmentcount
");
// Move the selected posts over
$sqlarray = array(
"tid" => $newtid,
"fid" => $moveto,
"replyto" => 0
);
$db->update_query("posts", $sqlarray, "pid IN ($pids_list)");
// Get posts being merged
while($post = $db->fetch_array($original_posts_query))
{
if($post['visible'] == 1)
{
// Modify users' post counts
if($forum_cache[$post['fid']]['usepostcounts'] == 1 && $forum_cache[$moveto]['usepostcounts'] == 0)
{
// Moving into a forum that doesn't count post counts
if(!isset($user_counters[$post['uid']]))
{
$user_counters[$post['uid']] = 0;
}
--$user_counters[$post['uid']];
}
elseif($forum_cache[$post['fid']]['usepostcounts'] == 0 && $forum_cache[$moveto]['usepostcounts'] == 1)
{
// Moving into a forum that does count post counts
if(!isset($user_counters[$post['uid']]))
{
$user_counters[$post['uid']] = 0;
}
++$user_counters[$post['uid']];
}
// Subtract 1 from the old thread's replies
if(!isset($thread_counters[$post['tid']]['replies']))
{
$thread_counters[$post['tid']]['replies'] = $post['threadreplies'];
}
--$thread_counters[$post['tid']]['replies'];
// Add 1 to the new thread's replies
++$thread_counters[$newtid]['replies'];
if($moveto != $post['fid'])
{
// Only need to change forum info if the old forum is different from new forum
// Subtract 1 from the old forum's posts
if(!isset($forum_counters[$post['fid']]['posts']))
{
$forum_counters[$post['fid']]['posts'] = $forum_cache[$post['fid']]['posts'];
}
--$forum_counters[$post['fid']]['posts'];
// Add 1 to the new forum's posts
if(!isset($forum_counters[$moveto]['posts']))
{
$forum_counters[$moveto]['posts'] = $forum_cache[$moveto]['posts'];
}
++$forum_counters[$moveto]['posts'];
}
}
elseif($post['visible'] == 0)
{
// Unapproved post
// Subtract 1 from the old thread's unapproved posts
if(!isset($thread_counters[$post['tid']]['unapprovedposts']))
{
$thread_counters[$post['tid']]['unapprovedposts'] = $post['threadunapprovedposts'];
}
--$thread_counters[$post['tid']]['unapprovedposts'];
// Add 1 to the new thread's unapproved posts
++$thread_counters[$newtid]['unapprovedposts'];
if($moveto != $post['fid'])
{
// Only need to change forum info if the old forum is different from new forum
// Subtract 1 from the old forum's unapproved posts
if(!isset($forum_counters[$post['fid']]['unapprovedposts']))
{
$forum_counters[$post['fid']]['unapprovedposts'] = $forum_cache[$post['fid']]['unapprovedposts'];
}
--$forum_counters[$post['fid']]['unapprovedposts'];
// Add 1 to the new forum's unapproved posts
if(!isset($forum_counters[$moveto]['unapprovedposts']))
{
$forum_counters[$moveto]['unapprovedposts'] = $forum_cache[$moveto]['unapprovedposts'];
}
++$forum_counters[$moveto]['unapprovedposts'];
}
}
// Subtract attachment counts from old thread and add to new thread (which are counted regardless of post or attachment unapproval at time of coding)
if(!isset($thread_counters[$post['tid']]['attachmentcount']))
{
$thread_counters[$post['tid']]['attachmentcount'] = $post['threadattachmentcount'];
}
$thread_counters[$post['tid']]['attachmentcount'] -= $post['postattachmentcount'];
$thread_counters[$newtid]['attachmentcount'] += $post['postattachmentcount'];
}
if($destination_tid == 0 && $thread_counters[$newtid]['replies'] > 0)
{
// If splitting into a new thread, subtract one from the thread's reply count to compensate for the original post
--$thread_counters[$newtid]['replies'];
}
$arguments = array("pids" => $pids, "tid" => $tid, "moveto" => $moveto, "newsubject" => $newsubject, "destination_tid" => $destination_tid);
$plugins->run_hooks("class_moderation_split_posts", $arguments);
// Update user post counts
if(is_array($user_counters))
{
foreach($user_counters as $uid => $change)
{
if($change >= 0)
{
$change = '+'.$change; // add the addition operator for query
}
$db->update_query("users", array("postnum" => "postnum{$change}"), "uid='{$uid}'", 1, true);
}
}
// Update thread counters
if(is_array($thread_counters))
{
foreach($thread_counters as $tid => $counters)
{
if($tid == $newtid)
{
// Update the subject of the first post in the new thread
$query = $db->simple_select("posts", "pid", "tid='$newtid'", array('order_by' => 'dateline', 'limit' => 1));
$newthread = $db->fetch_array($query);
$sqlarray = array(
"subject" => $newsubject,
"replyto" => 0
);
$db->update_query("posts", $sqlarray, "pid='{$newthread['pid']}'");
}
else
{
// Update the subject of the first post in the old thread
$query = $db->query("
SELECT p.pid, t.subject
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."threads t ON (p.tid=t.tid)
WHERE p.tid='{$tid}'
ORDER BY p.dateline ASC
LIMIT 1
");
$oldthread = $db->fetch_array($query);
$sqlarray = array(
"subject" => $db->escape_string($oldthread['subject']),
"replyto" => 0
);
$db->update_query("posts", $sqlarray, "pid='{$oldthread['pid']}'");
}
$db->update_query("threads", $counters, "tid='{$tid}'");
update_thread_data($tid);
// Update first post columns
update_first_post($tid);
}
}
update_thread_data($newtid);
update_first_post($newtid);
// Update forum counters
if(is_array($forum_counters))
{
foreach($forum_counters as $fid => $counters)
{
update_forum_counters($fid, $counters);
}
}
return $newtid;
}
/**
* Move multiple threads to new forum
*
* @param array Thread IDs
* @param int Destination forum
* @return boolean true
*/
function move_threads($tids, $moveto)
{
global $db, $plugins;
// Make sure we only have valid values
$tids = array_map('intval', $tids);
$tid_list = implode(',', $tids);
$moveto = intval($moveto);
$newforum = get_forum($moveto);
$total_posts = $total_unapproved_posts = $total_threads = $total_unapproved_threads = 0;
$query = $db->simple_select("threads", "fid, visible, replies, unapprovedposts, tid", "tid IN ($tid_list)");
while($thread = $db->fetch_array($query))
{
$forum = get_forum($thread['fid']);
$total_posts += $thread['replies']+1;
$total_unapproved_posts += $thread['unapprovedposts'];
$forum_counters[$thread['fid']]['posts'] += $thread['replies']+1;
$forum_counters[$thread['fid']]['unapprovedposts'] += $thread['unapprovedposts'];
if($thread['visible'] == 1)
{
$forum_counters[$thread['fid']]['threads']++;
++$total_threads;
}
else
{
$forum_counters[$thread['fid']]['unapprovedthreads']++;
$forum_counters[$thread['fid']]['unapprovedposts'] += $thread['replies']; // Implied unapproved posts counter for unapproved threads
++$total_unapproved_threads;
}
$query1 = $db->query("
SELECT COUNT(p.pid) AS posts, p.visible, u.uid
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=p.uid)
WHERE p.tid = '{$thread['tid']}'
GROUP BY p.visible, u.uid
ORDER BY posts DESC
");
while($posters = $db->fetch_array($query1))
{
$pcount = "";
if($newforum['usepostcounts'] != 0 && $forum['usepostcounts'] == 0 && $posters['visible'] != 0)
{
$pcount = "+{$posters['posts']}";
}
else if($newforum['usepostcounts'] == 0 && $forum['usepostcounts'] != 0 && $posters['visible'] != 0)
{
$pcount = "-{$posters['posts']}";
}
if(!empty($pcount))
{
$db->update_query("users", array("postnum" => "postnum{$pcount}"), "uid='{$posters['uid']}'", 1, true);
}
}
}
$sqlarray = array(
"fid" => $moveto,
);
$db->update_query("threads", $sqlarray, "tid IN ($tid_list)");
$db->update_query("posts", $sqlarray, "tid IN ($tid_list)");
// If any of the thread has a prefix and the destination forum doesn't accept that prefix, remove the prefix
$query = $db->simple_select("threads", "tid, prefix", "tid IN ($tid_list) AND prefix != 0");
while($thread = $db->fetch_array($query))
{
$query = $db->simple_select("threadprefixes", "COUNT(*) as num_prefixes", "(CONCAT(',',forums,',') LIKE '%,$moveto,%' OR forums='-1') AND pid='".$thread['prefix']."'");
if($db->fetch_field($query, "num_prefixes") == 0)
{
$sqlarray = array(
"prefix" => 0,
);
$db->update_query("threads", $sqlarray, "tid = '{$thread['tid']}'");
}
}
$arguments = array("tids" => $tids, "moveto" => $moveto);
$plugins->run_hooks("class_moderation_move_threads", $arguments);
if(is_array($forum_counters))
{
foreach($forum_counters as $fid => $counter)
{
$updated_count = array(
"posts" => "-{$counter['posts']}",
"unapprovedposts" => "-{$counter['unapprovedposts']}"
);
if($counter['threads'])
{
$updated_count['threads'] = "-{$counter['threads']}";
}
if($counter['unapprovedthreads'])
{
$updated_count['unapprovedthreads'] = "-{$counter['unapprovedthreads']}";
}
update_forum_counters($fid, $updated_count);
}
}
$updated_count = array(
"threads" => "+{$total_threads}",
"unapprovedthreads" => "+{$total_unapproved_threads}",
"posts" => "+{$total_posts}",
"unapprovedposts" => "+{$total_unapproved_posts}"
);
update_forum_counters($moveto, $updated_count);
// Remove thread subscriptions for the users who no longer have permission to view the thread
$this->remove_thread_subscriptions($tid_list, false, $moveto);
return true;
}
/**
* Approve multiple posts
*
* @param array PIDs
* @return boolean true
*/
function approve_posts($pids)
{
global $db, $cache;
$num_posts = 0;
// Make sure we only have valid values
$pids = array_map('intval', $pids);
$pid_list = implode(',', $pids);
$pids = $threads_to_update = array();
// Make visible
$approve = array(
"visible" => 1,
);
// We have three cases we deal with in these code segments:
// 1) We're approving specific unapproved posts
// 1.1) if the thread is approved
// 1.2) if the thread is unapproved
// 2) We're approving the firstpost of the thread, therefore approving the thread itself
// 3) We're doing both 1 and 2
$query = $db->query("
SELECT p.tid
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
WHERE p.pid IN ($pid_list) AND p.visible = '0' AND t.firstpost = p.pid AND t.visible = 0
");
while($post = $db->fetch_array($query))
{
// This is the first post in the thread so we're approving the whole thread.
$threads_to_update[] = $post['tid'];
}
if(!empty($threads_to_update))
{
$this->approve_threads($threads_to_update);
}
$query = $db->query("
SELECT p.pid, p.tid, f.fid, f.usepostcounts, p.uid, t.visible AS threadvisible
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
LEFT JOIN ".TABLE_PREFIX."forums f ON (f.fid=p.fid)
WHERE p.pid IN ($pid_list) AND p.visible = '0' AND t.firstpost != p.pid
");
while($post = $db->fetch_array($query))
{
$pids[] = $post['pid'];
++$thread_counters[$post['tid']]['unapprovedposts'];
++$thread_counters[$post['tid']]['replies'];
// If the thread of this post is unapproved then we've already taken into account this counter as implied.
// Updating it again would cause it to double count
if($post['threadvisible'] != 0)
{
++$forum_counters[$post['fid']]['num_posts'];
}
// If post counts enabled in this forum and the thread is approved, add 1
if($post['usepostcounts'] != 0 && $post['threadvisible'] == 1)
{
$db->update_query("users", array("postnum" => "postnum+1"), "uid='{$post['uid']}'", 1, true);
}
}
if(empty($pids) && empty($threads_to_update))
{
return false;
}
if(!empty($pids))
{
$where = "pid IN (".implode(',', $pids).")";
$db->update_query("posts", $approve, $where);
}
if(is_array($thread_counters))
{
foreach($thread_counters as $tid => $counters)
{
$counters_update = array(
"unapprovedposts" => "-".$counters['unapprovedposts'],
"replies" => "+".$counters['replies']
);
update_thread_counters($tid, $counters_update);
update_thread_data($tid);
}
}
if(is_array($forum_counters))
{
foreach($forum_counters as $fid => $counters)
{
$updated_forum_stats = array(
"posts" => "+{$counters['num_posts']}",
"unapprovedposts" => "-{$counters['num_posts']}",
"threads" => "+{$counters['num_threads']}",
"unapprovedthreads" => "-{$counters['num_threads']}"
);
update_forum_counters($fid, $updated_forum_stats);
}
}
return true;
}
/**
* Unapprove multiple posts
*
* @param array PIDs
* @return boolean true
*/
function unapprove_posts($pids)
{
global $db, $cache;
// Make sure we only have valid values
$pids = array_map('intval', $pids);
$pid_list = implode(',', $pids);
$pids = $threads_to_update = array();
// Make invisible
$approve = array(
"visible" => 0,
);
// We have three cases we deal with in these code segments:
// 1) We're unapproving specific approved posts
// 1.1) if the thread is approved
// 1.2) if the thread is unapproved
// 2) We're unapproving the firstpost of the thread, therefore unapproving the thread itself
// 3) We're doing both 1 and 2
$query = $db->query("
SELECT p.tid
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
WHERE p.pid IN ($pid_list) AND p.visible = '1' AND t.firstpost = p.pid AND t.visible = 1
");
while($post = $db->fetch_array($query))
{
// This is the first post in the thread so we're unapproving the whole thread.
$threads_to_update[] = $post['tid'];
}
if(!empty($threads_to_update))
{
$this->unapprove_threads($threads_to_update);
}
$thread_counters = array();
$forum_counters = array();
$query = $db->query("
SELECT p.pid, p.tid, f.fid, f.usepostcounts, p.uid, t.visible AS threadvisible
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
LEFT JOIN ".TABLE_PREFIX."forums f ON (f.fid=p.fid)
WHERE p.pid IN ($pid_list) AND p.visible = '1' AND t.firstpost != p.pid
");
while($post = $db->fetch_array($query))
{
$pids[] = $post['pid'];
++$thread_counters[$post['tid']]['unapprovedposts'];
++$thread_counters[$post['tid']]['replies'];
// If the thread of this post is unapproved then we've already taken into account this counter as implied.
// Updating it again would cause it to double count
if($post['threadvisible'] != 0)
{
++$forum_counters[$post['fid']]['num_posts'];
}
// If post counts enabled in this forum and the thread is approved, subtract 1
if($post['usepostcounts'] != 0 && $post['threadvisible'] == 1)
{
$db->update_query("users", array("postnum" => "postnum-1"), "uid='{$post['uid']}'", 1, true);
}
}
if(empty($pids) && empty($threads_to_update))
{
return false;
}
if(!empty($pids))
{
$where = "pid IN (".implode(',', $pids).")";
$db->update_query("posts", $approve, $where);
}
if(is_array($thread_counters))
{
foreach($thread_counters as $tid => $counters)
{
$counters_update = array(
"unapprovedposts" => "+".$counters['unapprovedposts'],
"replies" => "-".$counters['replies']
);
update_thread_counters($tid, $counters_update);
update_thread_data($tid);
}
}
if(is_array($forum_counters))
{
foreach($forum_counters as $fid => $counters)
{
$updated_forum_stats = array(
"posts" => "-{$counters['num_posts']}",
"unapprovedposts" => "+{$counters['num_posts']}",
"threads" => "-{$counters['num_threads']}",
"unapprovedthreads" => "+{$counters['num_threads']}"
);
update_forum_counters($fid, $updated_forum_stats);
}
}
return true;
}
/**
* Change thread subject
*
* @param mixed Thread ID(s)
* @param string Format of new subject (with {subject})
* @return boolean true
*/
function change_thread_subject($tids, $format)
{
global $db, $mybb, $plugins;
// Get tids into list
if(!is_array($tids))
{
$tids = array(intval($tids));
}
// Make sure we only have valid values
$tids = array_map('intval', $tids);
$tid_list = implode(',', $tids);
// Get original subject
$query = $db->simple_select("threads", "subject, tid", "tid IN ($tid_list)");
while($thread = $db->fetch_array($query))
{
// Update threads and first posts with new subject
$subject = str_replace('{username}', $mybb->user['username'], $format);
$subject = str_replace('{subject}', $thread['subject'], $subject);
$new_subject = array(
"subject" => $db->escape_string($subject)
);
$db->update_query("threads", $new_subject, "tid='{$thread['tid']}'", 1);
$db->update_query("posts", $new_subject, "tid='{$thread['tid']}' AND replyto='0'", 1);
}
$arguments = array("tids" => $tids, "format" => $format);
$plugins->run_hooks("class_moderation_change_thread_subject", $arguments);
return true;
}
/**
* Add thread expiry
*
* @param int Thread ID
* @param int Timestamp when the thread is deleted
* @return boolean true
*/
function expire_thread($tid, $deletetime)
{
global $db, $plugins;
$tid = intval($tid);
$update_thread = array(
"deletetime" => intval($deletetime)
);
$db->update_query("threads", $update_thread, "tid='{$tid}'");
$arguments = array("tid" => $tid, "deletetime" => $deletetime);
$plugins->run_hooks("class_moderation_expire_thread", $arguments);
return true;
}
/**
* Toggle post visibility (approved/unapproved)
*
* @param array Post IDs
* @param int Thread ID
* @param int Forum ID
* @return boolean true
*/
function toggle_post_visibility($pids)
{
global $db;
// Make sure we only have valid values
$pids = array_map('intval', $pids);
$pid_list = implode(',', $pids);
$query = $db->simple_select("posts", 'pid, visible', "pid IN ($pid_list)");
while($post = $db->fetch_array($query))
{
if($post['visible'] == 1)
{
$unapprove[] = $post['pid'];
}
else
{
$approve[] = $post['pid'];
}
}
if(is_array($unapprove))
{
$this->unapprove_posts($unapprove);
}
if(is_array($approve))
{
$this->approve_posts($approve);
}
return true;
}
/**
* Toggle thread visibility (approved/unapproved)
*
* @param array Thread IDs
* @param int Forum ID
* @return boolean true
*/
function toggle_thread_visibility($tids, $fid)
{
global $db;
// Make sure we only have valid values
$tids = array_map('intval', $tids);
$fid = intval($fid);
$tid_list = implode(',', $tids);
$query = $db->simple_select("threads", 'tid, visible', "tid IN ($tid_list)");
while($thread = $db->fetch_array($query))
{
if($thread['visible'] == 1)
{
$unapprove[] = $thread['tid'];
}
else
{
$approve[] = $thread['tid'];
}
}
if(is_array($unapprove))
{
$this->unapprove_threads($unapprove, $fid);
}
if(is_array($approve))
{
$this->approve_threads($approve, $fid);
}
return true;
}
/**
* Toggle threads open/closed
*
* @param array Thread IDs
* @return boolean true
*/
function toggle_thread_status($tids)
{
global $db;
// Make sure we only have valid values
$tids = array_map('intval', $tids);
$tid_list = implode(',', $tids);
$query = $db->simple_select("threads", 'tid, closed', "tid IN ($tid_list)");
while($thread = $db->fetch_array($query))
{
if($thread['closed'] == 1)
{
$open[] = $thread['tid'];
}
elseif($thread['closed'] == 0)
{
$close[] = $thread['tid'];
}
}
if(is_array($open))
{
$this->open_threads($open);
}
if(is_array($close))
{
$this->close_threads($close);
}
return true;
}
/**
* Remove thread subscriptions (from one or multiple threads in the same forum)
*
* @param int $tids Thread ID, or an array of thread IDs from the same forum.
* @param boolean $all True (default) to delete all subscriptions, false to only delete subscriptions from users with no permission to read the thread
* @param int $fid (Only applies if $all is false) The forum ID of the thread
* @return boolean true
*/
function remove_thread_subscriptions($tids, $all = true, $fid = 0)
{
global $db, $plugins;
// Format thread IDs
if(!is_array($tids))
{
$tids = array($tids);
}
// Make sure we only have valid values
$tids = array_map('intval', $tids);
$fid = intval($fid);
$tids_csv = implode(',', $tids);
// Delete only subscriptions from users who no longer have permission to read the thread.
if(!$all)
{
// Get groups that cannot view the forum or its threads
$forum_parentlist = get_parent_list($fid);
$query = $db->simple_select("forumpermissions", "gid", "fid IN ({$forum_parentlist}) AND (canview=0 OR canviewthreads=0)");
$groups = array();
while($group = $db->fetch_array($query))
{
$groups[] = $group['gid'];
switch($db->type)
{
case "pgsql":
case "sqlite":
$additional_groups .= " OR ','||u.additionalgroups||',' LIKE ',{$group['gid']},'";
break;
default:
$additional_groups .= " OR CONCAT(',',u.additionalgroups,',') LIKE ',{$group['gid']},'";
}
}
// If there are groups found, delete subscriptions from users in these groups
if(count($groups) > 0)
{
$groups_csv = implode(',', $groups);
$query = $db->query("
SELECT s.tid, u.uid
FROM ".TABLE_PREFIX."threadsubscriptions s
LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=s.uid)
WHERE s.tid IN ({$tids_csv})
AND (u.usergroup IN ({$groups_csv}){$additional_groups})
");
while($subscription = $db->fetch_array($query))
{
$db->delete_query("threadsubscriptions", "uid='{$subscription['uid']}' AND tid='{$subscription['tid']}'");
}
}
}
// Delete all subscriptions of this thread
else
{
$db->delete_query("threadsubscriptions", "tid IN ({$tids_csv})");
}
$arguments = array("tids" => $tids, "all" => $all, "fid" => $fid);
$plugins->run_hooks("class_moderation_remove_thread_subscriptions", $arguments);
return true;
}
/**
* Apply a thread prefix (to one or multiple threads in the same forum)
*
* @param int $tids Thread ID, or an array of thread IDs from the same forum.
* @param int $prefix Prefix ID to apply to the threads
*/
function apply_thread_prefix($tids, $prefix = 0)
{
global $db, $plugins;
// Format thread IDs
if(!is_array($tids))
{
$tids = array($tids);
}
// Make sure we only have valid values
$tids = array_map('intval', $tids);
$tids_csv = implode(',', $tids);
$update_thread = array('prefix' => intval($prefix));
$db->update_query('threads', $update_thread, "tid IN ({$tids_csv})");
$arguments = array('tids' => $tids, 'prefix' => $prefix);
$plugins->run_hooks('class_moderation_apply_thread_prefix', $arguments);
return true;
}
}
?> | marhazk/AeraSite | AeraSite/forum/inc/class_moderation.php | PHP | gpl-2.0 | 62,991 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Data;
namespace EventAI
{
public static class Extensions
{
/// <summary>
/// Reads the NULL-terminated string from the current stream.
/// </summary>
/// <param name="reader">Stream to read from.</param>
/// <returns>Resulting string.</returns>
public static string ReadCString(this BinaryReader reader)
{
byte num;
List<byte> temp = new List<byte>();
while ((num = reader.ReadByte()) != 0)
{
temp.Add(num);
}
return Encoding.UTF8.GetString(temp.ToArray());
}
/// <summary>
/// Reads the struct from the current stream.
/// </summary>
/// <typeparam name="T">Struct type.</typeparam>
/// <param name="reader">Stream to read from.</param>
/// <returns>Resulting struct.</returns>
public static unsafe T ReadStruct<T>(this BinaryReader reader) where T : struct
{
byte[] rawData = reader.ReadBytes(Marshal.SizeOf(typeof(T)));
GCHandle handle = GCHandle.Alloc(rawData, GCHandleType.Pinned);
T returnObject = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
return returnObject;
}
public static StringBuilder AppendLineIfNotNull(this StringBuilder builder, string line)
{
if (!String.IsNullOrEmpty(line))
return builder.AppendLine(line);
return builder;
}
public static StringBuilder AppendFormatIfNotNull(this StringBuilder builder, string format, string arg)
{
if (!String.IsNullOrEmpty(arg))
{
return builder.AppendFormat(format, arg);
}
return builder;
}
public static StringBuilder AppendFormatIfNotNull(this StringBuilder builder, string format, uint arg)
{
if (arg != 0)
{
return builder.AppendFormat(format, arg);
}
return builder;
}
public static StringBuilder AppendFormatIfNotNull(this StringBuilder builder, string format, int arg)
{
if (arg != 0)
{
return builder.AppendFormat(format, arg);
}
return builder;
}
public static StringBuilder AppendFormatIfNotNull(this StringBuilder builder, string format, float arg)
{
if (arg != 0.0f)
{
return builder.AppendFormat(format, arg);
}
return builder;
}
public static StringBuilder AppendFormatLine(this StringBuilder builder, string format, params object[] arg0)
{
return builder.AppendFormat(format, arg0).AppendLine();
}
public static StringBuilder AppendFormatLineIfNotNull(this StringBuilder builder, string format, string arg)
{
if (!String.IsNullOrEmpty(arg))
{
return builder.AppendFormat(format, arg).AppendLine();
}
return builder;
}
public static StringBuilder AppendFormatLineIfNotNull(this StringBuilder builder, string format, int arg)
{
if (arg != 0)
{
return builder.AppendFormat(format, arg).AppendLine();
}
return builder;
}
public static StringBuilder AppendFormatLineIfNotNull(this StringBuilder builder, string format, uint arg)
{
if (arg != 0)
{
return builder.AppendFormat(format, arg).AppendLine();
}
return builder;
}
public static StringBuilder AppendFormatLineIfNotNull(this StringBuilder builder, string format, float arg)
{
if (arg != 0.0f)
{
return builder.AppendFormat(format, arg).AppendLine();
}
return builder;
}
public static uint ToUInt32(this Object val)
{
if (val == null)
return 0;
uint num;
uint.TryParse(val.ToString(), out num);
return num;
}
public static int ToInt32(this Object val)
{
if (val == null)
return 0;
int num;
int.TryParse(val.ToString(), out num);
return num;
}
public static float ToFloat(this Object val)
{
if (val == null)
return 0.0f;
float num;
float.TryParse(val.ToString().Replace(',', '.'), out num);
return num;
}
public static String NormaliseString(this String text, String remove)
{
var str = String.Empty;
if (remove != String.Empty)
{
text = text.Replace(remove, String.Empty);
}
foreach (var s in text.Split('_'))
{
int i = 0;
foreach (var c in s.ToCharArray())
{
str += i == 0 ? c.ToString().ToUpper() : c.ToString().ToLower();
i++;
}
str += " ";
}
return str.Remove(str.Length - 1);
}
public static void SetCheckedItemFromFlag(this CheckedListBox _name, uint _value)
{
for (int i = 0; i < _name.Items.Count; ++i)
{
double pow = Math.Pow(2, i);
int x = (int)Math.Truncate(_value / pow);
bool check = (x % 2) != 0;
_name.SetItemChecked(i, check);
}
}
public static int GetFlagsValue(this CheckedListBox clb)
{
int val = 0;
foreach (int elem in clb.CheckedIndices)
{
val += (int)Math.Pow(2, elem);
}
return val;
}
public static void SetFlags(this CheckedListBox _clb, Type enums)
{
_clb.Items.Clear();
foreach (var elem in Enum.GetValues(enums))
{
_clb.Items.Add(elem.ToString().NormaliseString(String.Empty));
}
}
public static void SetFlags(this CheckedListBox _clb, Type enums, String remove)
{
_clb.Items.Clear();
foreach (var elem in Enum.GetValues(enums))
{
_clb.Items.Add(elem.ToString().NormaliseString(remove));
}
}
public static string RemExc(this String str)
{
return str.Replace(@"'", @"\'").Replace("\"", "\\\"");
}
public static bool ContainText(this String text, String str)
{
return (text.ToUpper().IndexOf(str.ToUpper(), StringComparison.CurrentCultureIgnoreCase) != -1);
}
}
}
| Kreegoth/Darkportalwow | sql_FULL_DB/Infinitys_EventAI_Creator/EventAI/Extensions/Extensions.cs | C# | gpl-2.0 | 7,159 |
<?php
if (!defined('TYPO3_MODE')) {
die('Access denied.');
}
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_pagerenderer.php']['render-preProcess']['wsless'] = 'EXT:ws_less/Classes/Hooks/RenderPreProcessorHook.php:&WapplerSystems\WsLess\Hooks\RenderPreProcessorHook->renderPreProcessorProc';
// Caching the pages - default expire 3600 seconds
if (!is_array($TYPO3_CONF_VARS['SYS']['caching']['cacheConfigurations']['ws_less'])) {
$TYPO3_CONF_VARS['SYS']['caching']['cacheConfigurations']['ws_less'] = array(
'frontend' => 'TYPO3\\CMS\\Core\\Cache\\Frontend\\VariableFrontend',
'backend' => 'TYPO3\\CMS\\Core\\Cache\\Backend\\FileBackend',
'options' => array(
'defaultLifetime' => 3600*24*7,
),
);
}
?> | mneuhaus/brunex-test | typo3conf/ext/ws_less/ext_localconf.php | PHP | gpl-2.0 | 735 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_newsfeeds
*
* @copyright (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\Component\Newsfeeds\Administrator\View\Newsfeed;
\defined('_JEXEC') or die;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Helper\ContentHelper;
use Joomla\CMS\Language\Associations;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\View\GenericDataException;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;
use Joomla\CMS\Toolbar\ToolbarHelper;
/**
* View to edit a newsfeed.
*
* @since 1.6
*/
class HtmlView extends BaseHtmlView
{
/**
* The item object for the newsfeed
*
* @var \JObject
* @since 1.6
*/
protected $item;
/**
* The form object for the newsfeed
*
* @var \JForm
* @since 1.6
*/
protected $form;
/**
* The model state of the newsfeed
*
* @var \JObject
* @since 1.6
*/
protected $state;
/**
* Execute and display a template script.
*
* @param string $tpl The name of the template file to parse; automatically searches through the template paths.
*
* @return void
*
* @since 1.6
*/
public function display($tpl = null)
{
$this->state = $this->get('State');
$this->item = $this->get('Item');
$this->form = $this->get('Form');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
throw new GenericDataException(implode("\n", $errors), 500);
}
// If we are forcing a language in modal (used for associations).
if ($this->getLayout() === 'modal' && $forcedLanguage = Factory::getApplication()->input->get('forcedLanguage', '', 'cmd'))
{
// Set the language field to the forcedLanguage and disable changing it.
$this->form->setValue('language', null, $forcedLanguage);
$this->form->setFieldAttribute('language', 'readonly', 'true');
// Only allow to select categories with All language or with the forced language.
$this->form->setFieldAttribute('catid', 'language', '*,' . $forcedLanguage);
// Only allow to select tags with All language or with the forced language.
$this->form->setFieldAttribute('tags', 'language', '*,' . $forcedLanguage);
}
$this->addToolbar();
parent::display($tpl);
}
/**
* Add the page title and toolbar.
*
* @return void
*
* @since 1.6
*/
protected function addToolbar()
{
Factory::getApplication()->input->set('hidemainmenu', true);
$user = Factory::getUser();
$isNew = ($this->item->id == 0);
$checkedOut = !(is_null($this->item->checked_out) || $this->item->checked_out == $user->get('id'));
// Since we don't track these assets at the item level, use the category id.
$canDo = ContentHelper::getActions('com_newsfeeds', 'category', $this->item->catid);
$title = $isNew ? Text::_('COM_NEWSFEEDS_MANAGER_NEWSFEED_NEW') : Text::_('COM_NEWSFEEDS_MANAGER_NEWSFEED_EDIT');
ToolbarHelper::title($title, 'rss newsfeeds');
$toolbarButtons = [];
// If not checked out, can save the item.
if (!$checkedOut && ($canDo->get('core.edit') || count($user->getAuthorisedCategories('com_newsfeeds', 'core.create')) > 0))
{
ToolbarHelper::apply('newsfeed.apply');
$toolbarButtons[] = ['save', 'newsfeed.save'];
}
if (!$checkedOut && count($user->getAuthorisedCategories('com_newsfeeds', 'core.create')) > 0)
{
$toolbarButtons[] = ['save2new', 'newsfeed.save2new'];
}
// If an existing item, can save to a copy.
if (!$isNew && $canDo->get('core.create'))
{
$toolbarButtons[] = ['save2copy', 'newsfeed.save2copy'];
}
ToolbarHelper::saveGroup(
$toolbarButtons,
'btn-success'
);
if (empty($this->item->id))
{
ToolbarHelper::cancel('newsfeed.cancel');
}
else
{
ToolbarHelper::cancel('newsfeed.cancel', 'JTOOLBAR_CLOSE');
if (ComponentHelper::isEnabled('com_contenthistory') && $this->state->params->get('save_history', 0) && $canDo->get('core.edit'))
{
ToolbarHelper::versions('com_newsfeeds.newsfeed', $this->item->id);
}
}
if (!$isNew && Associations::isEnabled() && ComponentHelper::isEnabled('com_associations'))
{
ToolbarHelper::custom('newsfeed.editAssociations', 'contract', '', 'JTOOLBAR_ASSOCIATIONS', false, false);
}
ToolbarHelper::divider();
ToolbarHelper::help('JHELP_COMPONENTS_NEWSFEEDS_FEEDS_EDIT');
}
}
| Llewellynvdm/joomla-cms | administrator/components/com_newsfeeds/src/View/Newsfeed/HtmlView.php | PHP | gpl-2.0 | 4,432 |
#include "ScriptFacade.h"
#include "Data/Snapshot/Snapshots.h"
#include "Data/ViewManager.h"
#include "Data/Animator/Animator.h"
#include "Data/Animator/AnimatorType.h"
#include "Data/Image/Controller.h"
#include "Data/Colormap/Colormap.h"
#include "Data/Colormap/Colormaps.h"
#include "Data/Util.h"
#include "Data/Histogram/Histogram.h"
#include "Data/Layout/Layout.h"
#include "Data/Preferences/PreferencesSave.h"
#include "Data/Statistics.h"
#include "Data/Image/GridControls.h"
#include <QDebug>
using Carta::State::ObjectManager;
//using Carta::State::CartaObject;
const QString ScriptFacade::TOGGLE = "toggle";
const QString ScriptFacade::ERROR = "error";
const QString ScriptFacade::UNKNOWN_ERROR = "An unknown error has occurred";
ScriptFacade * ScriptFacade::getInstance (){
static ScriptFacade * sc = new ScriptFacade ();
return sc;
}
ScriptFacade::ScriptFacade(){
m_viewManager = Carta::Data::Util::findSingletonObject<Carta::Data::ViewManager>();
int numControllers = m_viewManager->getControllerCount();
for (int i = 0; i < numControllers; i++) {
QString imageView = getImageViewId( i );
Carta::State::CartaObject* obj = _getObject( imageView );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
connect( controller, & Carta::Data::Controller::saveImageResult, this, & ScriptFacade::saveImageResultCB );
}
}
}
}
QString ScriptFacade::getColorMapId( int index ) const {
return m_viewManager->getObjectId( Carta::Data::Colormap::CLASS_NAME, index);
}
QStringList ScriptFacade::getColorMaps() const {
Carta::Data::Colormaps* maps = Carta::Data::Util::findSingletonObject<Carta::Data::Colormaps>();
return maps->getColorMaps();
}
QString ScriptFacade::getImageViewId( int index ) const {
return m_viewManager->getObjectId( Carta::Data::Controller::PLUGIN_NAME, index );
}
QString ScriptFacade::getAnimatorViewId( int index ) const {
return m_viewManager->getObjectId( Carta::Data::Animator::CLASS_NAME, index );
}
QString ScriptFacade::getHistogramViewId( int index ) const {
return m_viewManager->getObjectId( Carta::Data::Histogram::CLASS_NAME, index );
}
QString ScriptFacade::getStatisticsViewId( int index ) const {
return m_viewManager->getObjectId( Carta::Data::Statistics::CLASS_NAME, index );
}
QStringList ScriptFacade::getImageViews() {
QStringList imageViewList;
int numControllers = m_viewManager->getControllerCount();
for (int i = 0; i < numControllers; i++) {
QString imageView = getImageViewId( i );
imageViewList << imageView;
}
if (numControllers == 0) {
imageViewList = QStringList("");
}
return imageViewList;
}
QStringList ScriptFacade::getColorMapViews() {
QStringList colorMapViewList;
int numColorMaps = m_viewManager->getColormapCount();
for (int i = 0; i < numColorMaps; i++) {
QString colorMapView = getColorMapId( i );
colorMapViewList << colorMapView;
}
if (numColorMaps == 0) {
colorMapViewList = QStringList("");
}
return colorMapViewList;
}
QStringList ScriptFacade::getAnimatorViews() {
QStringList animatorViewList;
int numAnimators = m_viewManager->getAnimatorCount();
for (int i = 0; i < numAnimators; i++) {
QString animatorView = getAnimatorViewId( i );
animatorViewList << animatorView;
}
if (numAnimators == 0) {
animatorViewList = QStringList("");
}
return animatorViewList;
}
QStringList ScriptFacade::getHistogramViews() {
QStringList histogramViewList;
int numHistograms = m_viewManager->getHistogramCount();
for (int i = 0; i < numHistograms; i++) {
QString histogramView = getHistogramViewId( i );
histogramViewList << histogramView;
}
if (numHistograms == 0) {
histogramViewList = QStringList("");
}
return histogramViewList;
}
QStringList ScriptFacade::getStatisticsViews() {
QStringList statisticsViewList;
int numStatistics = m_viewManager->getStatisticsCount();
for (int i = 0; i < numStatistics; i++) {
QString statisticsView = getStatisticsViewId( i );
statisticsViewList << statisticsView;
}
if (numStatistics == 0) {
statisticsViewList = QStringList("");
}
return statisticsViewList;
}
QStringList ScriptFacade::addLink( const QString& sourceId, const QString& destId ){
QStringList resultList("");
QString result = m_viewManager->linkAdd( sourceId, destId );
if ( result != "" ) {
resultList = QStringList( result );
}
return resultList;
}
QStringList ScriptFacade::removeLink( const QString& sourceId, const QString& destId ){
QStringList resultList("");
QString result = m_viewManager->linkRemove( sourceId, destId );
if ( result != "" ) {
resultList = QStringList( result );
}
return resultList;
}
QStringList ScriptFacade::setImageLayout(){
m_viewManager->setImageView();
QStringList result("");
return result;
}
QStringList ScriptFacade::setPlugins( const QStringList& names ) {
QStringList resultList("");
bool result = m_viewManager->setPlugins( names );
if ( result == false ) {
resultList = _logErrorMessage( ERROR, "There was an error setting the plugins: " + names.join( ',' ) );
}
return resultList;
}
QStringList ScriptFacade::getPluginList() const {
QStringList resultList;
Carta::Data::Layout* layout = Carta::Data::Util::findSingletonObject<Carta::Data::Layout>();
resultList = layout->getPluginList();
return resultList;
}
QStringList ScriptFacade::loadFile( const QString& objectId, const QString& fileName ){
QStringList resultList("");
bool result = m_viewManager->loadFile( objectId, fileName );
if ( result == false ) {
resultList = _logErrorMessage( ERROR, "Could not load file " + fileName );
}
return resultList;
}
QStringList ScriptFacade::setAnalysisLayout(){
m_viewManager->setAnalysisView();
QStringList result("");
return result;
}
QStringList ScriptFacade::setCustomLayout( int rows, int cols ){
QStringList resultList;
Carta::Data::Layout* layout = Carta::Data::Util::findSingletonObject<Carta::Data::Layout>();
QString resultStr = layout->setLayoutSize( rows, cols );
resultList = QStringList( resultStr );
return resultList;
}
QStringList ScriptFacade::setColorMap( const QString& colormapId, const QString& colormapName ){
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( colormapId );
if ( obj != nullptr ){
Carta::Data::Colormap* colormap = dynamic_cast<Carta::Data::Colormap*>(obj);
if ( colormap != nullptr ){
QString result = colormap->setColorMap( colormapName );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified colormap view could not be found: " + colormapId );
}
return resultList;
}
QStringList ScriptFacade::reverseColorMap( const QString& colormapId, const QString& reverseStr ){
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( colormapId );
if ( obj != nullptr ){
Carta::Data::Colormap* colormap = dynamic_cast<Carta::Data::Colormap*>(obj);
if ( colormap != nullptr ){
bool reverse = false;
bool validBool = true;
if ( reverseStr == TOGGLE ){
reverse = ! colormap->isReversed();
}
else {
reverse = Carta::Data::Util::toBool( reverseStr, &validBool );
}
if ( validBool ){
QString result = colormap->reverseColorMap( reverse );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, "An invalid value was passed to reverse color map: " + reverseStr );
}
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified colormap view could not be found: " + colormapId );
}
return resultList;
}
QStringList ScriptFacade::invertColorMap( const QString& colormapId, const QString& invertStr ){
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( colormapId );
if ( obj != nullptr ){
Carta::Data::Colormap* colormap = dynamic_cast<Carta::Data::Colormap*>(obj);
if ( colormap != nullptr ){
bool invert = false;
bool validBool = true;
if ( invertStr == TOGGLE ){
invert = ! colormap->isInverted();
}
else {
invert = Carta::Data::Util::toBool( invertStr, &validBool );
}
if ( validBool ){
QString result = colormap->invertColorMap( invert );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, "An unrecognized parameter was passed to invert color map: " + invertStr );
}
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified colormap view could not be found: " + colormapId );
}
return resultList;
}
QStringList ScriptFacade::setColorMix( const QString& colormapId, double red, double green, double blue ){
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( colormapId );
if ( obj != nullptr ){
Carta::Data::Colormap* colormap = dynamic_cast<Carta::Data::Colormap*>(obj);
if ( colormap != nullptr ){
QString result = colormap->setColorMix( red, green, blue );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified colormap view could not be found: " + colormapId );
}
return resultList;
}
QStringList ScriptFacade::setGamma( const QString& colormapId, double gamma ){
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( colormapId );
if ( obj != nullptr ){
Carta::Data::Colormap* colormap = dynamic_cast<Carta::Data::Colormap*>(obj);
if ( colormap != nullptr ){
QString result = colormap->setGamma( gamma );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified colormap view could not be found: " + colormapId );
}
return resultList;
}
QStringList ScriptFacade::setDataTransform( const QString& colormapId, const QString& transformString ){
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( colormapId );
if ( obj != nullptr ){
Carta::Data::Colormap* colormap = dynamic_cast<Carta::Data::Colormap*>(obj);
if ( colormap != nullptr ){
QString result = colormap->setDataTransform( transformString );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified colormap view could not be found: " + colormapId );
}
return resultList;
}
QStringList ScriptFacade::showImageAnimator( const QString& animatorId ){
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( animatorId );
if ( obj != nullptr ){
Carta::Data::Animator* animator = dynamic_cast<Carta::Data::Animator*>(obj);
if ( animator != nullptr){
QString animId;
animator->addAnimator( "Image", animId );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified animator could not be found: " + animatorId );
}
return resultList;
}
QStringList ScriptFacade::getMaxImageCount( const QString& animatorId ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( animatorId );
if ( obj != nullptr ){
Carta::Data::Animator* animator = dynamic_cast<Carta::Data::Animator*>(obj);
if ( animator != nullptr){
int result = animator->getMaxImageCount();
resultList = QStringList( QString::number( result ) );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified animator could not be found: " + animatorId );
}
return resultList;
}
QStringList ScriptFacade::getChannelIndex( const QString& animatorId ){
QStringList resultList("");
ObjectManager* objMan = ObjectManager::objectManager();
QString id = objMan->parseId( animatorId );
Carta::State::CartaObject* obj = objMan->getObject( id );
if ( obj != nullptr ){
Carta::Data::Animator* animator = dynamic_cast<Carta::Data::Animator*>(obj);
if ( animator != nullptr){
Carta::Data::AnimatorType* animType = animator->getAnimator( "Channel");
if ( animType != nullptr ){
int frame = animType->getFrame();
resultList = QStringList( QString::number( frame ) );
}
else {
resultList = QStringList( ERROR );
resultList.append( "Could not get channel animator." );
}
}
else {
resultList = QStringList( ERROR );
resultList.append( "An unknown error has occurred." );
}
}
else {
resultList = QStringList( ERROR );
resultList.append( "The specified animator could not be found." );
}
return resultList;
}
QStringList ScriptFacade::setChannel( const QString& animatorId, int index ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( animatorId );
if ( obj != nullptr ){
Carta::Data::Animator* animator = dynamic_cast<Carta::Data::Animator*>(obj);
if ( animator != nullptr){
Carta::Data::AnimatorType* animType = animator->getAnimator( "Channel");
if ( animType != nullptr ){
animType->setFrame( index );
}
else {
qDebug()<<"Could not get channel animator";
}
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified animator could not be found: " + animatorId );
}
return resultList;
}
QStringList ScriptFacade::setImage( const QString& animatorId, int index ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( animatorId );
if ( obj != nullptr ){
Carta::Data::Animator* animator = dynamic_cast<Carta::Data::Animator*>(obj);
if ( animator != nullptr){
animator->changeImageIndex( index );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified animator could not be found: " + animatorId );
}
return resultList;
}
QStringList ScriptFacade::setClipValue( const QString& controlId, double clipValue ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->setClipValue( clipValue );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified controller could not be found: " + controlId );
}
return resultList;
}
/*QStringList ScriptFacade::saveImage( const QString& controlId, const QString& filename ) {
QStringList resultList("");
ObjectManager* objMan = ObjectManager::objectManager();
QString id = objMan->parseId( controlId );
Carta::State::CartaObject* obj = objMan->getObject( id );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
bool result = controller->saveImage( filename );
if ( !result ) {
resultList = QStringList( "Could not save image to " + filename );
}
}
else {
resultList = QStringList( ERROR );
resultList.append( UNKNOWN_ERROR );
}
}
else {
resultList = QStringList( ERROR );
resultList.append( "The specified image view could not be found." );
}
return resultList;
}*/
QStringList ScriptFacade::saveFullImage( const QString& controlId, const QString& filename, int width, int height,
double scale, /*Qt::AspectRatioMode aspectRatioMode*/ const QString& aspectModeStr ){
ObjectManager* objMan = ObjectManager::objectManager();
//Save the state so the view will update and parse parameters to make
//sure they are valid before calling save.
Carta::Data::PreferencesSave* prefSave = Carta::Data::Util::findSingletonObject<Carta::Data::PreferencesSave>();
QStringList errorList("");
QString widthError = prefSave->setWidth( width );
QString heightError = prefSave->setHeight( height );
QString aspectModeError = prefSave->setAspectRatioMode( aspectModeStr );
if ( widthError.isEmpty() && heightError.isEmpty() && aspectModeError.isEmpty() ){
QString id = objMan->parseId( controlId );
Carta::State::CartaObject* obj = objMan->getObject( id );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
controller->saveImage( filename, scale );
}
}
}
else {
if ( !widthError.isEmpty()){
errorList.append( widthError );
}
if ( !heightError.isEmpty()){
errorList.append( heightError );
}
if ( !aspectModeError.isEmpty() ){
errorList.append( aspectModeError );
}
}
return errorList;
}
void ScriptFacade::saveImageResultCB( bool result ){
emit saveImageResult( result );
}
QStringList ScriptFacade::saveSnapshot( const QString& sessionId, const QString& saveName, bool saveLayout, bool savePreferences, bool saveData, const QString& description ){
Carta::State::ObjectManager* objMan = ObjectManager::objectManager();
Carta::Data::Snapshots* m_snapshots = objMan->createObject<Carta::Data::Snapshots>();
QString result = m_snapshots->saveSnapshot( sessionId, saveName, saveLayout, savePreferences, saveData, description );
QStringList resultList(result);
return resultList;
}
QStringList ScriptFacade::getSnapshots( const QString& sessionId ){
Carta::State::ObjectManager* objMan = ObjectManager::objectManager();
Carta::Data::Snapshots* snapshots = objMan->createObject<Carta::Data::Snapshots>();
QStringList resultList;
QList<Carta::Data::Snapshot> snapshotList = snapshots->getSnapshots( sessionId );
int count = snapshotList.size();
if ( count == 0 ) {
resultList = QStringList("");
}
for ( int i = 0; i < count; i++ ){
resultList.append( snapshotList[i].getName() );
}
return resultList;
}
QStringList ScriptFacade::getSnapshotObjects( const QString& sessionId ){
Carta::State::ObjectManager* objMan = ObjectManager::objectManager();
Carta::Data::Snapshots* snapshots = objMan->createObject<Carta::Data::Snapshots>();
QStringList resultList;
QList<Carta::Data::Snapshot> snapshotList = snapshots->getSnapshots( sessionId );
int count = snapshotList.size();
if ( count == 0 ) {
resultList = QStringList("");
}
for ( int i = 0; i < count; i++ ){
resultList.append( snapshotList[i].toString() );
}
return resultList;
}
QStringList ScriptFacade::deleteSnapshot( const QString& sessionId, const QString& saveName ){
Carta::State::ObjectManager* objMan = ObjectManager::objectManager();
Carta::Data::Snapshots* snapshots = objMan->createObject<Carta::Data::Snapshots>();
QString result = snapshots->deleteSnapshot( sessionId, saveName );
QStringList resultList(result);
return resultList;
}
QStringList ScriptFacade::restoreSnapshot( const QString& sessionId, const QString& saveName ){
Carta::State::ObjectManager* objMan = ObjectManager::objectManager();
Carta::Data::Snapshots* snapshots = objMan->createObject<Carta::Data::Snapshots>();
QString result = snapshots->restoreSnapshot( sessionId, saveName );
QStringList resultList(result);
return resultList;
}
QStringList ScriptFacade::getLinkedColorMaps( const QString& controlId ) {
QStringList resultList;
ObjectManager* objMan = ObjectManager::objectManager();
for ( int i = 0; i < m_viewManager->getColormapCount(); i++ ){
QString colormapId = getColorMapId( i );
QString id = objMan->parseId( colormapId );
Carta::State::CartaObject* obj = objMan->getObject( id );
if ( obj != nullptr ){
Carta::Data::Colormap* colormap = dynamic_cast<Carta::Data::Colormap*>(obj);
QList<QString> oldLinks = colormap->getLinks();
if (oldLinks.contains( controlId )) {
resultList.append( colormapId );
}
}
else {
resultList = _logErrorMessage( ERROR, "Could not find colormap." );
}
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::getLinkedAnimators( const QString& controlId ) {
QStringList resultList;
ObjectManager* objMan = ObjectManager::objectManager();
for ( int i = 0; i < m_viewManager->getAnimatorCount(); i++ ){
QString animatorId = getAnimatorViewId( i );
QString id = objMan->parseId( animatorId );
Carta::State::CartaObject* obj = objMan->getObject( id );
if ( obj != nullptr ){
Carta::Data::Animator* animator = dynamic_cast<Carta::Data::Animator*>(obj);
QList<QString> oldLinks = animator->getLinks();
if (oldLinks.contains( controlId )) {
resultList.append( animatorId );
}
}
else {
resultList = _logErrorMessage( ERROR, "Could not find animator." );
}
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::getLinkedHistograms( const QString& controlId ) {
QStringList resultList;
ObjectManager* objMan = ObjectManager::objectManager();
for ( int i = 0; i < m_viewManager->getHistogramCount(); i++ ){
QString histogramId = getHistogramViewId( i );
QString id = objMan->parseId( histogramId );
Carta::State::CartaObject* obj = objMan->getObject( id );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
QList<QString> oldLinks = histogram->getLinks();
if (oldLinks.contains( controlId )) {
resultList.append( histogramId );
}
}
else {
resultList = _logErrorMessage( ERROR, "Could not find histogram." );
}
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::getLinkedStatistics( const QString& controlId ) {
QStringList resultList;
ObjectManager* objMan = ObjectManager::objectManager();
for ( int i = 0; i < m_viewManager->getStatisticsCount(); i++ ){
QString statisticsId = getStatisticsViewId( i );
QString id = objMan->parseId( statisticsId );
Carta::State::CartaObject* obj = objMan->getObject( id );
if ( obj != nullptr ){
Carta::Data::Statistics* statistics = dynamic_cast<Carta::Data::Statistics*>(obj);
QList<QString> oldLinks = statistics->getLinks();
if (oldLinks.contains( controlId )) {
resultList.append( statisticsId );
}
}
else {
resultList = _logErrorMessage( ERROR, "Could not find statistics view." );
}
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::centerOnPixel( const QString& controlId, double x, double y ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
controller->centerOnPixel( x, y );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::setZoomLevel( const QString& controlId, double zoomLevel ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
controller->setZoomLevel( zoomLevel );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::getZoomLevel( const QString& controlId ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
double zoomLevel = controller->getZoomLevel( );
resultList = QStringList( QString::number( zoomLevel ) );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::resetZoom( const QString& controlId ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
controller->resetZoom();
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::centerImage( const QString& controlId ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
controller->resetPan();
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::getImageDimensions( const QString& controlId ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
resultList = controller->getImageDimensions( );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::getOutputSize( const QString& controlId ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
resultList = controller->getOutputSize( );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::getPixelCoordinates( const QString& controlId, double ra, double dec ){
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
resultList = controller->getPixelCoordinates( ra, dec );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::getPixelValue( const QString& controlId, double x, double y ){
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString resultStr = controller->getPixelValue( x, y );
resultList = QStringList( resultStr );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::getPixelUnits( const QString& controlId ){
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString resultStr = controller->getPixelUnits();
resultList = QStringList( resultStr );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::getCoordinates( const QString& controlId, double x, double y, const Carta::Lib::KnownSkyCS system ){
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
resultList = controller->getCoordinates( x, y, system );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::getImageNames( const QString& controlId ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
int imageCount = controller->getStackedImageCount();
if ( imageCount == 0 ) {
resultList = QStringList("");
}
for ( int i = 0; i < imageCount; i++ ) {
resultList.append( controller->getImageName( i ) );
}
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::closeImage( const QString& controlId, const QString& imageName ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->closeImage( imageName );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::setClipBuffer( const QString& histogramId, int bufferAmount ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
QString result = histogram->setClipBuffer( bufferAmount );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
return resultList;
}
QStringList ScriptFacade::setUseClipBuffer( const QString& histogramId, const QString& useBufferStr ) {
QStringList resultList;
bool validBool = false;
bool useBuffer = Carta::Data::Util::toBool( useBufferStr, &validBool );
if ( validBool || useBufferStr.toLower() == TOGGLE ) {
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
if ( useBufferStr.toLower() == TOGGLE ) {
bool currentUseBuffer = histogram->getUseClipBuffer();
useBuffer = !currentUseBuffer;
}
QString result = histogram->setUseClipBuffer( useBuffer );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
}
else {
resultList = _logErrorMessage( ERROR, "Set clip buffer parameter must be true/false or 'toggle': " + useBufferStr );
}
return resultList;
}
QStringList ScriptFacade::setClipRange( const QString& histogramId, double minRange, double maxRange ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
QString result = histogram->setClipRange( minRange, maxRange );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
return resultList;
}
QStringList ScriptFacade::setClipRangePercent( const QString& histogramId, double minPercent, double maxPercent ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
QString result = histogram->setClipRangePercent( minPercent, maxPercent );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
return resultList;
}
QStringList ScriptFacade::getClipRange( const QString& histogramId ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
std::pair<double, double> clipRange = histogram->getClipRange();
resultList << QString::number( clipRange.first) << QString::number( clipRange.second );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
return resultList;
}
QStringList ScriptFacade::applyClips( const QString& histogramId ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
histogram->applyClips();
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
return resultList;
}
QStringList ScriptFacade::getIntensity( const QString& controlId, int frameLow, int frameHigh, double percentile ) {
QStringList resultList;
double intensity;
bool valid;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
valid = controller->getIntensity( frameLow, frameHigh, percentile, &intensity );
if ( valid ) {
resultList = QStringList( QString::number( intensity ) );
}
else {
resultList = _logErrorMessage( ERROR, "Could not get intensity for the specified parameters." );
}
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::setBinCount( const QString& histogramId, int binCount ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
QString result = histogram->setBinCount( binCount );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
return resultList;
}
QStringList ScriptFacade::setBinWidth( const QString& histogramId, double binWidth ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
QString result = histogram->setBinWidth( binWidth );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
return resultList;
}
QStringList ScriptFacade::setPlaneMode( const QString& histogramId, const QString& planeMode ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
QString result = histogram->setPlaneMode( planeMode );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
return resultList;
}
QStringList ScriptFacade::setPlaneRange( const QString& histogramId, double minPlane, double maxPlane) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
QString result = histogram->setPlaneRange( minPlane, maxPlane );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
return resultList;
}
QStringList ScriptFacade::setChannelUnit( const QString& histogramId, const QString& units ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
QString result = histogram->setChannelUnit( units );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
return resultList;
}
QStringList ScriptFacade::setGraphStyle( const QString& histogramId, const QString& style ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
QString result = histogram->setGraphStyle( style );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
return resultList;
}
QStringList ScriptFacade::setLogCount( const QString& histogramId, const QString& logCountStr ) {
QStringList resultList;
bool validBool = false;
bool logCount = Carta::Data::Util::toBool( logCountStr, &validBool );
if ( validBool || logCountStr.toLower() == TOGGLE ) {
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
if ( logCountStr.toLower() == TOGGLE ) {
bool currentLogCount = histogram->getLogCount();
logCount = !currentLogCount;
}
QString result = histogram->setLogCount( logCount );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
}
else {
resultList = _logErrorMessage( ERROR, "Set log count parameter must be true/false or 'toggle': " + logCountStr );
}
return resultList;
}
QStringList ScriptFacade::setColored( const QString& histogramId, const QString& coloredStr ) {
QStringList resultList;
bool validBool = false;
bool colored = Carta::Data::Util::toBool( coloredStr, &validBool );
if ( validBool || coloredStr.toLower() == TOGGLE ) {
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
if ( coloredStr.toLower() == TOGGLE ) {
bool currentColored = histogram->getColored();
colored = !currentColored;
}
QString result = histogram->setColored( colored );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
}
else {
resultList = _logErrorMessage( ERROR, "Set colored parameter must be true/false or 'toggle': " + coloredStr );
}
return resultList;
}
QStringList ScriptFacade::saveHistogram( const QString& histogramId, const QString& filename, int width, int height ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( histogramId );
if ( obj != nullptr ){
Carta::Data::Histogram* histogram = dynamic_cast<Carta::Data::Histogram*>(obj);
if ( histogram != nullptr ){
QString widthError;
QString heightError;
//Only set the width and height if the user intends to use
//the non-default save sizes.
if ( width > 0 || height > 0 ){
Carta::Data::PreferencesSave* prefSave = Carta::Data::Util::findSingletonObject<Carta::Data::PreferencesSave>();
if ( width > 0 ){
widthError = prefSave->setWidth( width );
}
if ( height > 0 ){
heightError = prefSave->setHeight( height );
}
}
if ( widthError.isEmpty() && heightError.isEmpty()){
QString result = histogram->saveHistogram( filename );
if ( !result.isEmpty() ){
resultList = _logErrorMessage( ERROR, result );
}
}
else {
if ( !widthError.isEmpty() ){
resultList = _logErrorMessage( ERROR, widthError );
}
if ( !heightError.isEmpty() ){
resultList = _logErrorMessage( ERROR, heightError );
}
}
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified histogram view could not be found: " + histogramId );
}
return resultList;
}
QStringList ScriptFacade::setGridAxesColor( const QString& controlId, int red, int green, int blue ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
resultList = controller->getGridControls()->setAxesColor( red, green, blue );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::setGridAxesThickness( const QString& controlId, int thickness ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setAxesThickness( thickness );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::setGridAxesTransparency( const QString& controlId, int transparency ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setAxesTransparency( transparency );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::setGridApplyAll( const QString& controlId, bool applyAll ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
controller->getGridControls()->setApplyAll( applyAll );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId );
}
return resultList;
}
QStringList ScriptFacade::setGridCoordinateSystem( const QString& controlId, const QString& coordSystem ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setCoordinateSystem( coordSystem );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::setGridFontFamily( const QString& controlId, const QString& fontFamily ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setFontFamily( fontFamily );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::setGridFontSize( const QString& controlId, int fontSize ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setFontSize( fontSize );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::setGridColor( const QString& controlId, int redAmount, int greenAmount, int blueAmount ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
resultList = controller->getGridControls()->setGridColor( redAmount, greenAmount, blueAmount );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::setGridSpacing( const QString& controlId, double spacing ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setGridSpacing( spacing );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::setGridThickness( const QString& controlId, int thickness ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setGridThickness( thickness );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::setGridTransparency( const QString& controlId, int transparency ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setGridTransparency( transparency );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::setGridLabelColor( const QString& controlId, int redAmount, int greenAmount, int blueAmount ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
resultList = controller->getGridControls()->setLabelColor( redAmount, greenAmount, blueAmount );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::setShowGridAxis( const QString& controlId, bool showAxis ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setShowAxis( showAxis );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
return resultList;
}
QStringList ScriptFacade::setShowGridCoordinateSystem( const QString& controlId, bool showCoordinateSystem ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setShowCoordinateSystem( showCoordinateSystem );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
return resultList;
}
QStringList ScriptFacade::setShowGridLines( const QString& controlId, bool showGridLines ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setShowGridLines( showGridLines );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
return resultList;
}
QStringList ScriptFacade::setShowGridInternalLabels( const QString& controlId, bool showInternalLabels ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setShowInternalLabels( showInternalLabels );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
return resultList;
}
QStringList ScriptFacade::setShowGridStatistics( const QString& controlId, bool showStatistics ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setShowStatistics( showStatistics );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
return resultList;
}
QStringList ScriptFacade::setShowGridTicks( const QString& controlId, bool showTicks ) {
QStringList resultList("");
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setShowTicks( showTicks );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
return resultList;
}
QStringList ScriptFacade::setGridTickColor( const QString& controlId, int redAmount, int greenAmount, int blueAmount ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
resultList = controller->getGridControls()->setTickColor( redAmount, greenAmount, blueAmount );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::setGridTickThickness( const QString& controlId, int tickThickness ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setTickThickness( tickThickness );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::setGridTickTransparency( const QString& controlId, int transparency ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setTickTransparency( transparency );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
QStringList ScriptFacade::setGridTheme( const QString& controlId, const QString& theme ) {
QStringList resultList;
Carta::State::CartaObject* obj = _getObject( controlId );
if ( obj != nullptr ){
Carta::Data::Controller* controller = dynamic_cast<Carta::Data::Controller*>(obj);
if ( controller != nullptr ){
QString result = controller->getGridControls()->setTheme( theme );
resultList = QStringList( result );
}
else {
resultList = _logErrorMessage( ERROR, UNKNOWN_ERROR );
}
}
else {
resultList = _logErrorMessage( ERROR, "The specified image view could not be found: " + controlId);
}
if ( resultList.length() == 0 ) {
resultList = QStringList("");
}
return resultList;
}
Carta::State::CartaObject* ScriptFacade::_getObject( const QString& id ) {
ObjectManager* objMan = ObjectManager::objectManager();
QString objId = objMan->parseId( id );
Carta::State::CartaObject* obj = objMan->getObject( objId );
return obj;
}
QStringList ScriptFacade::_logErrorMessage( const QString& key, const QString& value ) {
QStringList result( key );
result.append( value );
return result;
}
| pfederl/CARTAvis | carta/cpp/core/ScriptedClient/ScriptFacade.cpp | C++ | gpl-2.0 | 66,537 |
// Type definitions for WebRTC
// Project: http://dev.w3.org/2011/webrtc/
// Definitions by: Ken Smith <https://github.com/smithkl42/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Taken from http://dev.w3.org/2011/webrtc/editor/getusermedia.html
// version: W3C Editor's Draft 29 June 2015
interface ConstrainBooleanParameters {
exact: boolean;
ideal: boolean;
}
interface NumberRange {
max: number;
min: number;
}
interface ConstrainNumberRange extends NumberRange {
exact: number;
ideal: number;
}
interface ConstrainStringParameters {
exact: string | string[];
ideal: string | string[];
}
interface MediaStreamConstraints {
video?: boolean | MediaTrackConstraints;
audio?: boolean | MediaTrackConstraints;
}
declare module W3C {
type LongRange = NumberRange;
type DoubleRange = NumberRange;
type ConstrainBoolean = boolean | ConstrainBooleanParameters;
type ConstrainNumber = number | ConstrainNumberRange;
type ConstrainLong = ConstrainNumber;
type ConstrainDouble = ConstrainNumber;
type ConstrainString = string | string[] | ConstrainStringParameters;
}
interface MediaTrackConstraints extends MediaTrackConstraintSet {
advanced?: MediaTrackConstraintSet[];
}
interface MediaTrackConstraintSet {
width?: W3C.ConstrainLong;
height?: W3C.ConstrainLong;
aspectRatio?: W3C.ConstrainDouble;
frameRate?: W3C.ConstrainDouble;
facingMode?: W3C.ConstrainString;
volume?: W3C.ConstrainDouble;
sampleRate?: W3C.ConstrainLong;
sampleSize?: W3C.ConstrainLong;
echoCancellation?: W3C.ConstrainBoolean;
latency?: W3C.ConstrainDouble;
deviceId?: W3C.ConstrainString;
groupId?: W3C.ConstrainString;
}
interface MediaTrackSupportedConstraints {
width: boolean;
height: boolean;
aspectRatio: boolean;
frameRate: boolean;
facingMode: boolean;
volume: boolean;
sampleRate: boolean;
sampleSize: boolean;
echoCancellation: boolean;
latency: boolean;
deviceId: boolean;
groupId: boolean;
}
interface MediaStream extends EventTarget {
id: string;
active: boolean;
onactive: EventListener;
oninactive: EventListener;
onaddtrack: (event: MediaStreamTrackEvent) => any;
onremovetrack: (event: MediaStreamTrackEvent) => any;
clone(): MediaStream;
stop(): void;
getAudioTracks(): MediaStreamTrack[];
getVideoTracks(): MediaStreamTrack[];
getTracks(): MediaStreamTrack[];
getTrackById(trackId: string): MediaStreamTrack;
addTrack(track: MediaStreamTrack): void;
removeTrack(track: MediaStreamTrack): void;
}
interface MediaStreamTrackEvent extends Event {
track: MediaStreamTrack;
}
declare enum MediaStreamTrackState {
"live",
"ended"
}
interface MediaStreamTrack extends EventTarget {
id: string;
kind: string;
label: string;
enabled: boolean;
muted: boolean;
remote: boolean;
readyState: MediaStreamTrackState;
onmute: EventListener;
onunmute: EventListener;
onended: EventListener;
onoverconstrained: EventListener;
clone(): MediaStreamTrack;
stop(): void;
getCapabilities(): MediaTrackCapabilities;
getConstraints(): MediaTrackConstraints;
getSettings(): MediaTrackSettings;
applyConstraints(constraints: MediaTrackConstraints): Promise<void>;
}
interface MediaTrackCapabilities {
width: number | W3C.LongRange;
height: number | W3C.LongRange;
aspectRatio: number | W3C.DoubleRange;
frameRate: number | W3C.DoubleRange;
facingMode: string;
volume: number | W3C.DoubleRange;
sampleRate: number | W3C.LongRange;
sampleSize: number | W3C.LongRange;
echoCancellation: boolean[];
latency: number | W3C.DoubleRange;
deviceId: string;
groupId: string;
}
interface MediaTrackSettings {
width: number;
height: number;
aspectRatio: number;
frameRate: number;
facingMode: string;
volume: number;
sampleRate: number;
sampleSize: number;
echoCancellation: boolean;
latency: number;
deviceId: string;
groupId: string;
}
interface MediaStreamError {
name: string;
message: string;
constraintName: string;
}
interface NavigatorGetUserMedia {
(constraints: MediaStreamConstraints,
successCallback: (stream: MediaStream) => void,
errorCallback: (error: MediaStreamError) => void): void;
}
interface Navigator {
getUserMedia: NavigatorGetUserMedia;
webkitGetUserMedia: NavigatorGetUserMedia;
mozGetUserMedia: NavigatorGetUserMedia;
msGetUserMedia: NavigatorGetUserMedia;
mediaDevices: MediaDevices;
}
interface MediaDevices {
getSupportedConstraints(): MediaTrackSupportedConstraints;
getUserMedia(constraints: MediaStreamConstraints): Promise<MediaStream>;
}
| kazuki/video-codec.js | typings/MediaStream.d.ts | TypeScript | gpl-2.0 | 5,074 |
/* $Id$ */
/*
* Copyright (C) 2013 Teluu Inc. (http://www.teluu.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __PJSUA2_TYPES_HPP__
#define __PJSUA2_TYPES_HPP__
#ifdef _MSC_VER
# pragma warning( disable : 4290 ) // exception spec ignored
# pragma warning( disable : 4512 ) // can't generate assignment op
#endif
/**
* @file pjsua2/types.hpp
* @brief PJSUA2 Base Types
*/
#include <pjsua2/config.hpp>
#include <string>
#include <vector>
#include <map>
/** PJSUA2 API is inside pj namespace */
namespace pj
{
/**
* @defgroup PJSUA2_TYPES General Data Structure
* @ingroup PJSUA2_DS
* @{
*/
using std::string;
using std::vector;
/** Array of strings */
typedef std::vector<std::string> StringVector;
/** Array of integers */
typedef std::vector<int> IntVector;
/** Map string to string */
typedef std::map<std::string, std::string> StringToStringMap;
/**
* Type of token, i.e. arbitrary application user data
*/
typedef void *Token;
/**
* Socket address, encoded as string. The socket address contains host
* and port number in "host[:port]" format. The host part may contain
* hostname, domain name, IPv4 or IPv6 address. For IPv6 address, the
* address will be enclosed with square brackets, e.g. "[::1]:5060".
*/
typedef string SocketAddress;
/**
* Transport ID is an integer.
*/
typedef int TransportId;
/**
* Transport handle, corresponds to pjsip_transport instance.
*/
typedef void *TransportHandle;
/**
* Timer entry, corresponds to pj_timer_entry
*/
typedef void *TimerEntry;
/**
* Generic data
*/
typedef void *GenericData;
/*
* Forward declaration of Account and Call to be used
* by Endpoint.
*/
class Account;
class Call;
/**
* Constants
*/
enum
{
/** Invalid ID, equal to PJSUA_INVALID_ID */
INVALID_ID = -1,
/** Success, equal to PJ_SUCCESS */
SUCCESS = 0
};
//////////////////////////////////////////////////////////////////////////////
/**
* This structure contains information about an error that is thrown
* as an exception.
*/
struct Error
{
/** The error code. */
pj_status_t status;
/** The PJSUA API operation that throws the error. */
string title;
/** The error message */
string reason;
/** The PJSUA source file that throws the error */
string srcFile;
/** The line number of PJSUA source file that throws the error */
int srcLine;
/** Build error string. */
string info(bool multi_line=false) const;
/** Default constructor */
Error();
/**
* Construct an Error instance from the specified parameters. If
* \a prm_reason is empty, it will be filled with the error description
* for the status code.
*/
Error(pj_status_t prm_status,
const string &prm_title,
const string &prm_reason,
const string &prm_src_file,
int prm_src_line);
};
/*
* Error utilities.
*/
#if PJSUA2_ERROR_HAS_EXTRA_INFO
# define PJSUA2_RAISE_ERROR(status) \
PJSUA2_RAISE_ERROR2(status, __FUNCTION__)
# define PJSUA2_RAISE_ERROR2(status,op) \
PJSUA2_RAISE_ERROR3(status, op, string())
# define PJSUA2_RAISE_ERROR3(status,op,txt) \
do { \
Error err_ = Error(status, op, txt, __FILE__, __LINE__); \
PJ_LOG(1,(THIS_FILE, "%s", err_.info().c_str())); \
throw err_; \
} while (0)
#else
/** Raise Error exception */
# define PJSUA2_RAISE_ERROR(status) \
PJSUA2_RAISE_ERROR2(status, string())
/** Raise Error exception */
# define PJSUA2_RAISE_ERROR2(status,op) \
PJSUA2_RAISE_ERROR3(status, op, string())
/** Raise Error exception */
# define PJSUA2_RAISE_ERROR3(status,op,txt) \
do { \
Error err_ = Error(status, op, txt, string(), 0); \
PJ_LOG(1,(THIS_FILE, "%s", err_.info().c_str())); \
throw err_; \
} while (0)
#endif
/** Raise Error exception if the expression fails */
#define PJSUA2_CHECK_RAISE_ERROR2(status, op) \
do { \
if (status != PJ_SUCCESS) { \
PJSUA2_RAISE_ERROR2(status, op); \
} \
} while (0)
/** Raise Error exception if the status fails */
#define PJSUA2_CHECK_RAISE_ERROR(status) \
PJSUA2_CHECK_RAISE_ERROR2(status, "")
/** Raise Error exception if the expression fails */
#define PJSUA2_CHECK_EXPR(expr) \
do { \
pj_status_t the_status = expr; \
PJSUA2_CHECK_RAISE_ERROR2(the_status, #expr); \
} while (0)
//////////////////////////////////////////////////////////////////////////////
/**
* Version information.
*/
struct Version
{
/** Major number */
int major;
/** Minor number */
int minor;
/** Additional revision number */
int rev;
/** Version suffix (e.g. "-svn") */
string suffix;
/** The full version info (e.g. "2.1.0-svn") */
string full;
/**
* PJLIB version number as three bytes with the following format:
* 0xMMIIRR00, where MM: major number, II: minor number, RR: revision
* number, 00: always zero for now.
*/
unsigned numeric;
};
//////////////////////////////////////////////////////////////////////////////
/**
* Representation of time value.
*/
struct TimeVal
{
/**
* The seconds part of the time.
*/
long sec;
/**
* The miliseconds fraction of the time.
*/
long msec;
public:
/**
* Convert from pjsip
*/
void fromPj(const pj_time_val &prm);
};
/**
* @} PJSUA2
*/
} // namespace pj
#endif /* __PJSUA2_TYPES_HPP__ */
| pjsip/pjproject | pjsip/include/pjsua2/types.hpp | C++ | gpl-2.0 | 6,093 |
/*
This file is part of Cyclos (www.cyclos.org).
A project of the Social Trade Organisation (www.socialtrade.org).
Cyclos is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Cyclos is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Cyclos; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.puremoneysystems.poc.utils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import java.lang.Process;
import java.lang.Runtime;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.File;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import org.opentransactions.otapi.OTAPI_Basic;
import org.opentransactions.otjavalib.Tools;
/**
* The OT Manager implementation
*
* @author chris
*/
public class OTManagerImpl implements OTManager, InitializingBean, DisposableBean {
private String lastTestResult = new String("nothing yet");
private boolean otapiLoaded = false;
@Override
public void afterPropertiesSet() throws Exception {
this.appendPathToRuntime("/usr/local/lib");
System.loadLibrary("otapi-java");
OTAPI_Basic.AppStartup();
OTAPI_Basic.Init();
otapiLoaded = OTAPI_Basic.LoadWallet();
if(!otapiLoaded){
OTAPI_Basic.AppShutdown();
throw new RuntimeException("Failed to load the current wallet.");
}
}
@Override
public void destroy() throws Exception {
if(otapiLoaded){
OTAPI_Basic.AppShutdown();
otapiLoaded = false;
}
}
@Override
public String getServerState() {
try{
OTAPI_Basic.Output(0, "OTAPI test");
OTAPI_Basic.AppShutdown();
}catch(Exception e){
this.lastTestResult = e.toString();
e.printStackTrace();
}
return this.lastTestResult;
}
@Override
public String getLastTestResult() {
return this.lastTestResult;
}
private Collection<String> appendPathToRuntime(final String strPath) throws IllegalAccessException, NoSuchFieldException {
Set<String> pathSet = new HashSet<String>();
Field field = ClassLoader.class.getDeclaredField("usr_paths");
field.setAccessible(true);
pathSet.addAll(Arrays.asList((String[]) field.get(null)));
pathSet.addAll(Arrays.asList(strPath.split(File.pathSeparator)));
if (pathSet.contains(".")) {
pathSet.remove(".");
}
if (pathSet.contains("")) {
pathSet.remove("");
}
if (pathSet.contains(" ")) {
pathSet.remove(" ");
}
if (pathSet.contains(File.pathSeparator)) {
pathSet.remove(File.pathSeparator);
}
// now we have just a set of all the paths (including the new one).
StringBuilder pathsString = new StringBuilder();
Iterator<String> setIterator = pathSet.iterator();
while (setIterator.hasNext()) {
String next = setIterator.next();
//System.out.println("Path: " + next);
pathsString.append(next);
if (setIterator.hasNext()) {
pathsString.append(File.pathSeparator);
}
}
field.set(null, pathSet.toArray(new String[0]));
System.setProperty("java.library.path", pathsString.toString());
//System.out.println("Utility.addDirToRuntime: Setting java.library.path: " + pathsString.toString());
return pathSet;
}
}
| PUREMoneySystems/open-cyclos | src/com/puremoneysystems/poc/utils/OTManagerImpl.java | Java | gpl-2.0 | 4,188 |
<?php
namespace hypeJunction\Categories;
$entity = elgg_extract('entity', $vars);
if (elgg_instanceof($entity)) {
$container = $entity->getContainerEntity();
} else {
$container = elgg_extract('container', $vars, elgg_get_site_entity());
}
echo elgg_view('input/hidden', array(
'name' => 'categories[hierarchy][]',
'value' => ''
));
echo elgg_view('input/hidden', array(
'name' => 'categories[guid][]',
'value' => $entity->guid
));
echo elgg_view('input/hidden', array(
'name' => 'categories[container_guid][]',
'value' => $container->guid,
'rel' => 'container-guid',
));
echo '<div class="categories-icon-move icon-small"></div>';
$upload = elgg_echo('categories:edit:icon');
if (elgg_instanceof($entity) && $entity->icontime) {
$has_icon = true;
$icon_upload_class = 'categories-has-icon';
}
echo "<div class=\"categories-icon-upload $icon_upload_class\" title=\"$upload\">";
echo elgg_view('input/file', array(
'name' => 'categories[icon][]',
'class' => 'hidden'
));
echo '</div>';
if ($has_icon) {
echo elgg_view('output/img', array(
'src' => $entity->getIconURL('tiny'),
'class' => 'categories-icon-preview',
));
}
echo '<div class="categories-category-title">';
echo elgg_view('input/text', array(
'name' => 'categories[title][]',
'value' => $entity->title,
'placeholder' => elgg_echo('categories:edit:title')
));
echo '</div>';
echo '<div class="categories-icon-info icon-small"></div>';
echo '<div class="categories-icon-plus"></div>';
echo '<div class="categories-icon-minus"></div>';
echo '<div class="categories-category-meta hidden">';
echo '<div class="categories-category-description">';
//echo '<label>' . elgg_echo('categories:edit:description') . '</label>';
echo elgg_view('input/text', array(
'name' => 'categories[description][]',
'value' => $entity->description,
'placeholder' => elgg_echo('categories:edit:description')
));
echo '</div>';
echo '<div class="categories-category-access">';
//echo '<label>' . elgg_echo('categories:edit:access_id') . '</label>';
echo elgg_view('input/access', array(
'name' => 'categories[access_id][]',
'entity' => $entity,
));
echo '</div>';
echo '</div>'; | amcfarlane1251/ongarde | mod/hypeCategories/views/default/forms/categories/edit.php | PHP | gpl-2.0 | 2,153 |
<?php
/**
* Template Name: Full Width Template
* @package Snap
*/
?>
<?php get_header(); ?>
<?php while ( have_posts() ) : the_post(); global $post; ?>
<div id="page-<?php the_ID(); ?>">
<?php get_template_part( '_post-thumbnail' ); ?>
<h1><?php the_title(); ?></h1>
<?php if ( empty( $post->post_content) && current_user_can( 'edit_page', get_the_ID() ) ) : ?>
<div class="placeholder-text">
<p>
<?php
printf(
__( '<strong>Admin:</strong> Oh snap! It looks like you haven\'t added any content. You can add content in the <a href="%1$s" title="Edit %2$s">Edit Page</a> screen.', 'snap' ),
esc_url( get_edit_post_link() ),
the_title_attribute( array( 'echo' => false, ) )
);
?>
</p>
</div>
<?php else : ?>
<?php get_template_part( '_the-content' ); ?>
<?php endif; ?>
<?php comments_template( '', true ); ?>
</div>
<?php endwhile; ?>
<?php get_footer(); | unconstruct/bandwidth | wp-content/themes/snap/full-width.php | PHP | gpl-2.0 | 951 |
<?php
/**
* @file
* Contains \Drupal\field\FieldInfo.
*/
namespace Drupal\field;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Extension\ModuleHandlerInterface;
/**
* Provides field and instance definitions for the current runtime environment.
*
* The preferred way to access definitions is through the getBundleInstances()
* method, which keeps cache entries per bundle, storing both fields and
* instances for a given bundle. Fields used in multiple bundles are duplicated
* in several cache entries, and are merged into a single list in the memory
* cache. Cache entries are loaded for bundles as a whole, optimizing memory
* and CPU usage for the most common pattern of iterating over all instances of
* a bundle rather than accessing a single instance.
*
* The getFields() and getInstances() methods, which return all existing field
* and instance definitions, are kept mainly for backwards compatibility, and
* should be avoided when possible, since they load and persist in memory a
* potentially large array of information. In many cases, the lightweight
* getFieldMap() method should be preferred.
*/
class FieldInfo {
/**
* The cache backend to use.
*
* @var \Drupal\Core\Cache\CacheBackendInterface
*/
protected $cacheBackend;
/**
* Stores a module manager to invoke hooks.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactory
*/
protected $config;
/**
* Lightweight map of fields across entity types and bundles.
*
* @var array
*/
protected $fieldMap;
/**
* List of $field structures keyed by ID. Includes deleted fields.
*
* @var array
*/
protected $fieldsById = array();
/**
* Mapping of field names to the ID of the corresponding non-deleted field.
*
* @var array
*/
protected $fieldIdsByName = array();
/**
* Whether $fieldsById contains all field definitions or a subset.
*
* @var bool
*/
protected $loadedAllFields = FALSE;
/**
* Separately tracks requested field names or IDs that do not exist.
*
* @var array
*/
protected $unknownFields = array();
/**
* Instance definitions by bundle.
*
* @var array
*/
protected $bundleInstances = array();
/**
* Whether $bundleInstances contains all instances definitions or a subset.
*
* @var bool
*/
protected $loadedAllInstances = FALSE;
/**
* Separately tracks requested bundles that are empty (or do not exist).
*
* @var array
*/
protected $emptyBundles = array();
/**
* Extra fields by bundle.
*
* @var array
*/
protected $bundleExtraFields = array();
/**
* Constructs this FieldInfo object.
*
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* The cache backend to use.
* @param \Drupal\Core\Config\ConfigFactory $config
* The configuration factory object to use.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler class to use for invoking hooks.
*/
public function __construct(CacheBackendInterface $cache_backend, ConfigFactory $config, ModuleHandlerInterface $module_handler) {
$this->cacheBackend = $cache_backend;
$this->moduleHandler = $module_handler;
$this->config = $config;
}
/**
* Clears the "static" and persistent caches.
*/
public function flush() {
$this->fieldMap = NULL;
$this->fieldsById = array();
$this->fieldIdsByName = array();
$this->loadedAllFields = FALSE;
$this->unknownFields = array();
$this->bundleInstances = array();
$this->loadedAllInstances = FALSE;
$this->emptyBundles = array();
$this->bundleExtraFields = array();
$this->cacheBackend->deleteTags(array('field_info' => TRUE));
}
/**
* Collects a lightweight map of fields across bundles.
*
* @return
* An array keyed by field name. Each value is an array with two entries:
* - type: The field type.
* - bundles: The bundles in which the field appears, as an array with
* entity types as keys and the array of bundle names as values.
*/
public function getFieldMap() {
// Read from the "static" cache.
if ($this->fieldMap !== NULL) {
return $this->fieldMap;
}
// Read from persistent cache.
if ($cached = $this->cacheBackend->get('field_info:field_map')) {
$map = $cached->data;
// Save in "static" cache.
$this->fieldMap = $map;
return $map;
}
$map = array();
// Get active fields.
foreach (config_get_storage_names_with_prefix('field.field.') as $config_id) {
$field_config = $this->config->get($config_id)->get();
if ($field_config['active'] && $field_config['storage']['active']) {
$fields[$field_config['uuid']] = $field_config;
}
}
// Get field instances.
foreach (config_get_storage_names_with_prefix('field.instance.') as $config_id) {
$instance_config = $this->config->get($config_id)->get();
$field_uuid = $instance_config['field_uuid'];
// Filter out instances of inactive fields, and instances on unknown
// entity types.
if (isset($fields[$field_uuid])) {
$field = $fields[$field_uuid];
$map[$field['id']]['bundles'][$instance_config['entity_type']][] = $instance_config['bundle'];
$map[$field['id']]['type'] = $field['type'];
}
}
// Save in "static" and persistent caches.
$this->fieldMap = $map;
$this->cacheBackend->set('field_info:field_map', $map, CacheBackendInterface::CACHE_PERMANENT, array('field_info' => TRUE));
return $map;
}
/**
* Returns all active fields, including deleted ones.
*
* @return
* An array of field definitions, keyed by field ID.
*/
public function getFields() {
// Read from the "static" cache.
if ($this->loadedAllFields) {
return $this->fieldsById;
}
// Read from persistent cache.
if ($cached = $this->cacheBackend->get('field_info:fields')) {
$this->fieldsById = $cached->data;
}
else {
// Collect and prepare fields.
foreach (field_read_fields(array(), array('include_deleted' => TRUE)) as $field) {
$this->fieldsById[$field['uuid']] = $this->prepareField($field);
}
// Store in persistent cache.
$this->cacheBackend->set('field_info:fields', $this->fieldsById, CacheBackendInterface::CACHE_PERMANENT, array('field_info' => TRUE));
}
// Fill the name/ID map.
foreach ($this->fieldsById as $field) {
if (!$field['deleted']) {
$this->fieldIdsByName[$field['id']] = $field['uuid'];
}
}
$this->loadedAllFields = TRUE;
return $this->fieldsById;
}
/**
* Retrieves all active, non-deleted instances definitions.
*
* @param $entity_type
* (optional) The entity type.
*
* @return
* If $entity_type is not set, all instances keyed by entity type and bundle
* name. If $entity_type is set, all instances for that entity type, keyed
* by bundle name.
*/
public function getInstances($entity_type = NULL) {
// If the full list is not present in "static" cache yet.
if (!$this->loadedAllInstances) {
// Read from persistent cache.
if ($cached = $this->cacheBackend->get('field_info:instances')) {
$this->bundleInstances = $cached->data;
}
else {
// Collect and prepare instances.
// We also need to populate the static field cache, since it will not
// be set by subsequent getBundleInstances() calls.
$this->getFields();
foreach (field_read_instances() as $instance) {
$field = $this->getField($instance['field_name']);
$instance = $this->prepareInstance($instance, $field['type']);
$this->bundleInstances[$instance['entity_type']][$instance['bundle']][$instance['field_name']] = $instance;
}
// Store in persistent cache.
$this->cacheBackend->set('field_info:instances', $this->bundleInstances, CacheBackendInterface::CACHE_PERMANENT, array('field_info' => TRUE));
}
$this->loadedAllInstances = TRUE;
}
if (isset($entity_type)) {
return isset($this->bundleInstances[$entity_type]) ? $this->bundleInstances[$entity_type] : array();
}
else {
return $this->bundleInstances;
}
}
/**
* Returns a field definition from a field name.
*
* This method only retrieves active, non-deleted fields.
*
* @param $field_name
* The field name.
*
* @return
* The field definition, or NULL if no field was found.
*/
public function getField($field_name) {
// Read from the "static" cache.
if (isset($this->fieldIdsByName[$field_name])) {
$field_id = $this->fieldIdsByName[$field_name];
return $this->fieldsById[$field_id];
}
if (isset($this->unknownFields[$field_name])) {
return;
}
// Do not check the (large) persistent cache, but read the definition.
// Cache miss: read from definition.
if ($field = field_read_field($field_name)) {
$field = $this->prepareField($field);
// Save in the "static" cache.
$this->fieldsById[$field['uuid']] = $field;
$this->fieldIdsByName[$field['field_name']] = $field['uuid'];
return $field;
}
else {
$this->unknownFields[$field_name] = TRUE;
}
}
/**
* Returns a field definition from a field ID.
*
* This method only retrieves active fields, deleted or not.
*
* @param $field_id
* The field ID.
*
* @return
* The field definition, or NULL if no field was found.
*/
public function getFieldById($field_id) {
// Read from the "static" cache.
if (isset($this->fieldsById[$field_id])) {
return $this->fieldsById[$field_id];
}
if (isset($this->unknownFields[$field_id])) {
return;
}
// No persistent cache, fields are only persistently cached as part of a
// bundle.
// Cache miss: read from definition.
if ($fields = field_read_fields(array('uuid' => $field_id), array('include_deleted' => TRUE))) {
$field = current($fields);
$field = $this->prepareField($field);
// Store in the static cache.
$this->fieldsById[$field['uuid']] = $field;
if (!$field['deleted']) {
$this->fieldIdsByName[$field['field_name']] = $field['uuid'];
}
return $field;
}
else {
$this->unknownFields[$field_id] = TRUE;
}
}
/**
* Retrieves the instances for a bundle.
*
* The function also populates the corresponding field definitions in the
* "static" cache.
*
* @param $entity_type
* The entity type.
* @param $bundle
* The bundle name.
*
* @return
* The array of instance definitions, keyed by field name.
*/
public function getBundleInstances($entity_type, $bundle) {
// Read from the "static" cache.
if (isset($this->bundleInstances[$entity_type][$bundle])) {
return $this->bundleInstances[$entity_type][$bundle];
}
if (isset($this->emptyBundles[$entity_type][$bundle])) {
return array();
}
// Read from the persistent cache.
if ($cached = $this->cacheBackend->get("field_info:bundle:$entity_type:$bundle")) {
$info = $cached->data;
// Extract the field definitions and save them in the "static" cache.
foreach ($info['fields'] as $field) {
if (!isset($this->fieldsById[$field['uuid']])) {
$this->fieldsById[$field['uuid']] = $field;
if (!$field['deleted']) {
$this->fieldIdsByName[$field['field_name']] = $field['uuid'];
}
}
}
unset($info['fields']);
// Store the instance definitions in the "static" cache'. Empty (or
// non-existent) bundles are stored separately, so that they do not
// pollute the global list returned by getInstances().
if ($info['instances']) {
$this->bundleInstances[$entity_type][$bundle] = $info['instances'];
}
else {
$this->emptyBundles[$entity_type][$bundle] = TRUE;
}
return $info['instances'];
}
// Cache miss: collect from the definitions.
$instances = array();
// Do not return anything for unknown entity types.
if (entity_get_info($entity_type)) {
// Collect names of fields and instances involved in the bundle, using the
// field map. The field map is already filtered to active, non-deleted
// fields and instances, so those are kept out of the persistent caches.
$config_ids = array();
foreach ($this->getFieldMap() as $field_name => $field_data) {
if (isset($field_data['bundles'][$entity_type]) && in_array($bundle, $field_data['bundles'][$entity_type])) {
$config_ids[$field_name] = "$entity_type.$bundle.$field_name";
}
}
// Load and prepare the corresponding fields and instances entities.
if ($config_ids) {
$loaded_fields = entity_load_multiple('field_entity', array_keys($config_ids));
$loaded_instances = entity_load_multiple('field_instance', array_values($config_ids));
foreach ($loaded_instances as $instance) {
$field = $loaded_fields[$instance['field_name']];
$instance = $this->prepareInstance($instance, $field['type']);
$instances[$field['field_name']] = $instance;
// If the field is not in our global "static" list yet, add it.
if (!isset($this->fieldsById[$field['uuid']])) {
$field = $this->prepareField($field);
$this->fieldsById[$field['uuid']] = $field;
$this->fieldIdsByName[$field['field_name']] = $field['uuid'];
}
}
}
}
// Store in the 'static' cache'. Empty (or non-existent) bundles are stored
// separately, so that they do not pollute the global list returned by
// getInstances().
if ($instances) {
$this->bundleInstances[$entity_type][$bundle] = $instances;
}
else {
$this->emptyBundles[$entity_type][$bundle] = TRUE;
}
// The persistent cache additionally contains the definitions of the fields
// involved in the bundle.
$cache = array(
'instances' => $instances,
'fields' => array()
);
foreach ($instances as $instance) {
$cache['fields'][] = $this->fieldsById[$instance['field_id']];
}
$this->cacheBackend->set("field_info:bundle:$entity_type:$bundle", $cache, CacheBackendInterface::CACHE_PERMANENT, array('field_info' => TRUE));
return $instances;
}
/**
* Returns an array of instance data for a specific field and bundle.
*
* @param string $entity_type
* The entity type for the instance.
* @param string $bundle
* The bundle name for the instance.
* @param string $field_name
* The field name for the instance.
*
* @return array
* An associative array of instance data for the specific field and bundle;
* NULL if the instance does not exist.
*/
function getInstance($entity_type, $bundle, $field_name) {
$info = $this->getBundleInstances($entity_type, $bundle);
if (isset($info[$field_name])) {
return $info[$field_name];
}
}
/**
* Retrieves the "extra fields" for a bundle.
*
* @param $entity_type
* The entity type.
* @param $bundle
* The bundle name.
*
* @return
* The array of extra fields.
*/
public function getBundleExtraFields($entity_type, $bundle) {
// Read from the "static" cache.
if (isset($this->bundleExtraFields[$entity_type][$bundle])) {
return $this->bundleExtraFields[$entity_type][$bundle];
}
// Read from the persistent cache.
if ($cached = $this->cacheBackend->get("field_info:bundle_extra:$entity_type:$bundle")) {
$this->bundleExtraFields[$entity_type][$bundle] = $cached->data;
return $this->bundleExtraFields[$entity_type][$bundle];
}
// Cache miss: read from hook_field_extra_fields(). Note: given the current
// shape of the hook, we have no other way than collecting extra fields on
// all bundles.
$info = array();
$extra = $this->moduleHandler->invokeAll('field_extra_fields');
drupal_alter('field_extra_fields', $extra);
// Merge in saved settings.
if (isset($extra[$entity_type][$bundle])) {
$info = $this->prepareExtraFields($extra[$entity_type][$bundle], $entity_type, $bundle);
}
// Store in the 'static' and persistent caches.
$this->bundleExtraFields[$entity_type][$bundle] = $info;
$this->cacheBackend->set("field_info:bundle_extra:$entity_type:$bundle", $info, CacheBackendInterface::CACHE_PERMANENT, array('field_info' => TRUE));
return $this->bundleExtraFields[$entity_type][$bundle];
}
/**
* Prepares a field definition for the current run-time context.
*
* @param $field
* The raw field structure as read from the database.
*
* @return
* The field definition completed for the current runtime context.
*/
public function prepareField($field) {
// Make sure all expected field settings are present.
$field['settings'] += field_info_field_settings($field['type']);
$field['storage']['settings'] += field_info_storage_settings($field['storage']['type']);
return $field;
}
/**
* Prepares an instance definition for the current run-time context.
*
* @param $instance
* The raw instance structure as read from the database.
* @param $field_type
* The field type.
*
* @return
* The field instance array completed for the current runtime context.
*/
public function prepareInstance($instance, $field_type) {
// Make sure all expected instance settings are present.
$instance['settings'] += field_info_instance_settings($field_type);
// Set a default value for the instance.
if (field_behaviors_widget('default value', $instance) == FIELD_BEHAVIOR_DEFAULT && !isset($instance['default_value'])) {
$instance['default_value'] = NULL;
}
return $instance;
}
/**
* Prepares 'extra fields' for the current run-time context.
*
* @param $extra_fields
* The array of extra fields, as collected in hook_field_extra_fields().
* @param $entity_type
* The entity type.
* @param $bundle
* The bundle name.
*
* @return
* The list of extra fields completed for the current runtime context.
*/
public function prepareExtraFields($extra_fields, $entity_type, $bundle) {
$entity_type_info = entity_get_info($entity_type);
$bundle_settings = field_bundle_settings($entity_type, $bundle);
$extra_fields += array('form' => array(), 'display' => array());
$result = array();
// Extra fields in forms.
foreach ($extra_fields['form'] as $name => $field_data) {
$settings = isset($bundle_settings['extra_fields']['form'][$name]) ? $bundle_settings['extra_fields']['form'][$name] : array();
if (isset($settings['weight'])) {
$field_data['weight'] = $settings['weight'];
}
$result['form'][$name] = $field_data;
}
// Extra fields in displayed entities.
$result['display'] = $extra_fields['display'];
return $result;
}
}
| thebruce/d8-test-junk | drupal-8.x-dev/core/modules/field/lib/Drupal/field/FieldInfo.php | PHP | gpl-2.0 | 19,402 |
#include <bits/stdc++.h>
using namespace std;
/**
Find two segments that intersect
-sweep line technique
-binary search tree (std::set)
TIME: O(N*logN)
Memory: O(N)
**/
#define Point pair<int,int>
#define x first
#define y second
const double EPS = 1e-10;
int sign(int a)
{
if (a > 0)
return 1;
else if (a < 0)
return -1;
else
return 0;
}
/**
-1 counter-clockwise
0 collinear
+1 clockwise
**/
int CCW(Point A, Point B, Point C)
{
return sign( (C.x - A.x) * (B.y - A.y) - (C.y - A.y) * (B.x - A.x) );
}
double dist(Point A, Point B)
{
return sqrt((A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y));
}
struct Segment
{
Point A, B;
int id;
explicit Segment() : A(), B(), id(0) {
}
Segment(Point _A, Point _B, int _id) : A(_A), B(_B), id(_id) {
}
bool operator < (const Segment& S) const
{
if (this->A.x < S.A.x) /// *this starts first
{
/// *this comes before S if (A, B, S.a) are counter-clockwise
int ccw = CCW(this->A, this->B, S.A);
return (ccw < 0 || (ccw == 0 && this->A.y < S.A.y));
}
else
{
/// *this comes before S if (A, B, S.a) are clockwise
int ccw = CCW(S.A, S.B, this->A);
return (ccw > 0 || (ccw == 0 && this->A.y < S.A.y));
}
}
};
bool onSegment(const Segment& S, const Point& P)
{
return fabs(dist(S.A, S.B) - dist(S.A, P) - dist(S.B, P)) < EPS;
}
bool intersect(const Segment& S1, const Segment& S2)
{
if (onSegment(S1, S2.A) || onSegment(S1, S2.B) || onSegment(S2, S1.A) || onSegment(S2, S1.B))
return true;
if (CCW(S1.A, S1.B, S2.A) == CCW(S1.A, S1.B, S2.B) || CCW(S2.A, S2.B, S1.A) == CCW(S2.A, S2.B, S1.B))
return false;
return true;
}
/// O(N^2) solution
pair<int,int> bruteForce(vector<Segment>& S)
{
int sol = 0;
for (int i = 0; i < S.size(); ++i)
for (int j = i + 1; j < S.size(); ++j)
if (intersect(S[i], S[j]))
return {S[i].id, S[j].id};
return make_pair(-1, -1);
}
struct Event
{
Point P;
int id;
bool type; /// 0/1 for insert/erase
bool operator < (const Event& E) const
{
if (P.x != E.P.x)
return P.x < E.P.x;
else
{
/// first inserts (on the same sweep line)
if (type != E.type)
return type > E.type;
else
return P.y < E.P.y;
}
}
};
pair<int,int> findIntersection(vector<Segment>& segments)
{
int N = segments.size();
int nrEvents = 0;
set<Segment> BST; /// binary search tree which stores segments (ordered using ccw)
vector<Event> events(2 * N);
for (int i = 0; i < N; ++i)
{
if (segments[i].A > segments[i].B)
swap(segments[i].A, segments[i].B);
events[nrEvents++] = {segments[i].A, i, 1};
events[nrEvents++] = {segments[i].B, i, 0};
}
sort(events.begin(), events.end());
for (int i = 0; i < nrEvents; ++i)
{
if (events[i].type == 1)
{
auto it = BST.lower_bound(segments[ events[i].id ]);
/// try to intersect *it with its neighbours
if (it != BST.end())
{
if (intersect(*it, segments[ events[i].id ]))
return {it->id, segments[ events[i].id ].id};
}
if (it != BST.begin())
{
it--;
if (intersect(*it, segments[ events[i].id ]))
return {it->id, segments[ events[i].id ].id};
}
BST.insert(segments[ events[i].id ]);
}
else
{
auto it = BST.lower_bound(segments[ events[i].id ]);
auto prec = it, urm = it;
/// check if there are segment before and after *it (and test them)
if (it != BST.begin() && it != --BST.end())
{
prec--;
urm++;
if (intersect(*urm, *prec))
return {urm->id, prec->id};
}
BST.erase(segments[ events[i].id ]);
}
}
/// no intersection
return {-1, -1};
}
int main() {
///ifstream cin("data.in");
int N;
cin >> N;
vector<Segment> V;
for (int i = 1; i <= N; ++i)
{
Point a, b;
cin >> a.x >> a.y;
cin >> b.x >> b.y;
V.push_back({a, b, i});
}
pair<int,int> sol = findIntersection(V);
if (sol.first != -1)
{
cout << "YES\n";
cout << sol.first << " " << sol.second << "\n";
}
else
{
cout << "NO\n";
}
return 0;
}
| AlexandruValeanu/Competitive-Programming-Training | Geometry-Algorithms/Finding a pair of intersected segments - O(N * logN).cpp | C++ | gpl-2.0 | 4,750 |
/* Copyright (C) 2006 - 2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Boss_Cthun
SD%Complete: 95
SDComment: Darkglare tracking issue
SDCategory: Temple of Ahn'Qiraj
EndScriptData */
#include "precompiled.h"
#include "temple_of_ahnqiraj.h"
//Text emote
#define EMOTE_WEAKENED -1531011
#define PI 3.14
//****** Out of Combat ******
//Random Wispers - No txt only sound
#define RANDOM_SOUND_WHISPER 8663
//***** Phase 1 ********
//Mobs
#define BOSS_EYE_OF_CTHUN 15589
#define MOB_CLAW_TENTACLE 15725
#define MOB_EYE_TENTACLE 15726
#define MOB_SMALL_PORTAL 15904
//Eye Spells
#define SPELL_GREEN_BEAM 26134
#define SPELL_DARK_GLARE 26029
#define SPELL_RED_COLORATION 22518 //Probably not the right spell but looks similar
//Eye Tentacles Spells
#define SPELL_MIND_FLAY 26143
//Claw Tentacles Spells
#define SPELL_GROUND_RUPTURE 26139
#define SPELL_HAMSTRING 26141
#define MOB_
//*****Phase 2******
//Body spells
//#define SPELL_CARAPACE_CTHUN 26156 //Was removed from client dbcs
#define SPELL_TRANSFORM 26232
//Eye Tentacles Spells
//SAME AS PHASE1
//Giant Claw Tentacles
#define SPELL_MASSIVE_GROUND_RUPTURE 26100
//Also casts Hamstring
#define SPELL_THRASH 3391
//Giant Eye Tentacles
//CHAIN CASTS "SPELL_GREEN_BEAM"
//Stomach Spells
#define SPELL_MOUTH_TENTACLE 26332
#define SPELL_EXIT_STOMACH_KNOCKBACK 25383
#define SPELL_DIGESTIVE_ACID 26476
//Mobs
#define MOB_BODY_OF_CTHUN 15809
#define MOB_GIANT_CLAW_TENTACLE 15728
#define MOB_GIANT_EYE_TENTACLE 15334
#define MOB_FLESH_TENTACLE 15802
#define MOB_GIANT_PORTAL 15910
//Stomach Teleport positions
#define STOMACH_X -8562.0f
#define STOMACH_Y 2037.0f
#define STOMACH_Z -70.0f
#define STOMACH_O 5.05f
//Flesh tentacle positions
#define TENTACLE_POS1_X -8571.0f
#define TENTACLE_POS1_Y 1990.0f
#define TENTACLE_POS1_Z -98.0f
#define TENTACLE_POS1_O 1.22f
#define TENTACLE_POS2_X -8525.0f
#define TENTACLE_POS2_Y 1994.0f
#define TENTACLE_POS2_Z -98.0f
#define TENTACLE_POS2_O 2.12f
//Kick out position
#define KICK_X -8545.0f
#define KICK_Y 1984.0f
#define KICK_Z -96.0f
struct MANGOS_DLL_DECL flesh_tentacleAI : public ScriptedAI
{
flesh_tentacleAI(Creature* pCreature) : ScriptedAI(pCreature), Parent(0)
{
SetCombatMovement(false);
Reset();
}
uint64 Parent;
uint32 CheckTimer;
void SpawnedByCthun(uint64 p)
{
Parent = p;
}
void Reset()
{
CheckTimer = 1000;
}
void UpdateAI(const uint32 diff);
void JustDied(Unit* killer);
};
struct MANGOS_DLL_DECL eye_of_cthunAI : public ScriptedAI
{
eye_of_cthunAI(Creature* pCreature) : ScriptedAI(pCreature)
{
SetCombatMovement(false);
m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
if (!m_pInstance)
error_log("SD2: No Instance eye_of_cthunAI");
Reset();
}
ScriptedInstance* m_pInstance;
//Global variables
uint32 PhaseTimer;
//Eye beam phase
uint32 BeamTimer;
uint32 EyeTentacleTimer;
uint32 ClawTentacleTimer;
//Dark Glare phase
uint32 DarkGlareTick;
uint32 DarkGlareTickTimer;
float DarkGlareAngle;
bool ClockWise;
void Reset()
{
//Phase information
PhaseTimer = 50000; //First dark glare in 50 seconds
//Eye beam phase 50 seconds
BeamTimer = 3000;
EyeTentacleTimer = 45000; //Always spawns 5 seconds before Dark Beam
ClawTentacleTimer = 12500; //4 per Eye beam phase (unsure if they spawn durring Dark beam)
//Dark Beam phase 35 seconds (each tick = 1 second, 35 ticks)
DarkGlareTick = 0;
DarkGlareTickTimer = 1000;
DarkGlareAngle = 0;
ClockWise = false;
//Reset flags
m_creature->RemoveAurasDueToSpell(SPELL_RED_COLORATION);
m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE);
//Reset Phase
if (m_pInstance)
m_pInstance->SetData(TYPE_CTHUN_PHASE, 0);
}
void Aggro(Unit* pWho)
{
m_creature->SetInCombatWithZone();
}
void SpawnEyeTentacle(float x, float y)
{
Creature* Spawned;
Spawned = (Creature*)m_creature->SummonCreature(MOB_EYE_TENTACLE,m_creature->GetPositionX()+x,m_creature->GetPositionY()+y,m_creature->GetPositionZ(),0,TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT,500);
if (Spawned)
{
Unit* target;
target = SelectUnit(SELECT_TARGET_RANDOM,0);
if (target)
Spawned->AI()->AttackStart(target);
}
}
void UpdateAI(const uint32 diff)
{
//Check if we have a target
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
//No instance
if (!m_pInstance)
return;
switch (m_pInstance->GetData(TYPE_CTHUN_PHASE))
{
case 0:
{
//BeamTimer
if (BeamTimer < diff)
{
//SPELL_GREEN_BEAM
Unit* target = NULL;
target = SelectUnit(SELECT_TARGET_RANDOM,0);
if (target)
{
m_creature->InterruptNonMeleeSpells(false);
DoCastSpellIfCan(target,SPELL_GREEN_BEAM);
//Correctly update our target
m_creature->SetUInt64Value(UNIT_FIELD_TARGET, target->GetGUID());
}
//Beam every 3 seconds
BeamTimer = 3000;
}else BeamTimer -= diff;
//ClawTentacleTimer
if (ClawTentacleTimer < diff)
{
Unit* target = NULL;
target = SelectUnit(SELECT_TARGET_RANDOM,0);
if (target)
{
Creature* Spawned = NULL;
//Spawn claw tentacle on the random target
Spawned = (Creature*)m_creature->SummonCreature(MOB_CLAW_TENTACLE,target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(),0,TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT,500);
if (Spawned)
Spawned->AI()->AttackStart(target);
}
//One claw tentacle every 12.5 seconds
ClawTentacleTimer = 12500;
}else ClawTentacleTimer -= diff;
//EyeTentacleTimer
if (EyeTentacleTimer < diff)
{
//Spawn the 8 Eye Tentacles in the corret spots
SpawnEyeTentacle(0, 20); //south
SpawnEyeTentacle(10, 10); //south west
SpawnEyeTentacle(20, 0); //west
SpawnEyeTentacle(10, -10); //north west
SpawnEyeTentacle(0, -20); //north
SpawnEyeTentacle(-10, -10); //north east
SpawnEyeTentacle(-20, 0); // east
SpawnEyeTentacle(-10, 10); // south east
//No point actually putting a timer here since
//These shouldn't trigger agian until after phase shifts
EyeTentacleTimer = 45000;
}else EyeTentacleTimer -= diff;
//PhaseTimer
if (PhaseTimer < diff)
{
//Switch to Dark Beam
m_pInstance->SetData(TYPE_CTHUN_PHASE, 1);
m_creature->InterruptNonMeleeSpells(false);
//Select random target for dark beam to start on
Unit* target = NULL;
target = SelectUnit(SELECT_TARGET_RANDOM,0);
if (target)
{
//Correctly update our target
m_creature->SetUInt64Value(UNIT_FIELD_TARGET, target->GetGUID());
//Face our target
DarkGlareAngle = m_creature->GetAngle(target);
DarkGlareTickTimer = 1000;
DarkGlareTick = 0;
ClockWise = urand(0, 1);
}
//Add red coloration to C'thun
DoCastSpellIfCan(m_creature,SPELL_RED_COLORATION);
//Freeze animation
//Darkbeam for 35 seconds
PhaseTimer = 35000;
}else PhaseTimer -= diff;
}
break;
case 1:
{
//EyeTentacleTimer
if (DarkGlareTick < 35)
if (DarkGlareTickTimer < diff)
{
//Remove any target
m_creature->SetUInt64Value(UNIT_FIELD_TARGET, 0);
//Set angle and cast
if (ClockWise)
m_creature->SetOrientation(DarkGlareAngle + ((float)DarkGlareTick*PI/35));
else m_creature->SetOrientation(DarkGlareAngle - ((float)DarkGlareTick*PI/35));
m_creature->StopMoving();
//Actual dark glare cast, maybe something missing here?
m_creature->CastSpell(NULL, SPELL_DARK_GLARE, false);
//Increase tick
++DarkGlareTick;
//1 second per tick
DarkGlareTickTimer = 1000;
}else DarkGlareTickTimer -= diff;
//PhaseTimer
if (PhaseTimer < diff)
{
//Switch to Eye Beam
m_pInstance->SetData(TYPE_CTHUN_PHASE, 0);
BeamTimer = 3000;
EyeTentacleTimer = 45000; //Always spawns 5 seconds before Dark Beam
ClawTentacleTimer = 12500; //4 per Eye beam phase (unsure if they spawn durring Dark beam)
m_creature->InterruptNonMeleeSpells(false);
//Remove Red coloration from c'thun
m_creature->RemoveAurasDueToSpell(SPELL_RED_COLORATION);
//Freeze animation
m_creature->SetUInt32Value(UNIT_FIELD_FLAGS, 0);
//Eye Beam for 50 seconds
PhaseTimer = 50000;
}else PhaseTimer -= diff;
}break;
//Transition phase
case 2:
{
//Remove any target
m_creature->SetUInt64Value(UNIT_FIELD_TARGET, 0);
m_creature->SetHealth(0);
}
//Dead phase
case 5:
{
m_creature->DealDamage(m_creature, m_creature->GetMaxHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NONE, NULL, false);
}
}
}
void DamageTaken(Unit *done_by, uint32 &damage)
{
//No instance
if (!m_pInstance)
return;
switch (m_pInstance->GetData(TYPE_CTHUN_PHASE))
{
case 0:
case 1:
{
//Only if it will kill
if (damage < m_creature->GetHealth())
return;
//Fake death in phase 0 or 1 (green beam or dark glare phase)
m_creature->InterruptNonMeleeSpells(false);
//Remove Red coloration from c'thun
m_creature->RemoveAurasDueToSpell(SPELL_RED_COLORATION);
//Reset to normal emote state and prevent select and attack
m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE);
//Remove Target field
m_creature->SetUInt64Value(UNIT_FIELD_TARGET, 0);
//Death animation/respawning;
m_pInstance->SetData(TYPE_CTHUN_PHASE, 2);
m_creature->SetHealth(0);
damage = 0;
m_creature->InterruptNonMeleeSpells(true);
m_creature->RemoveAllAuras();
}
break;
case 5:
{
//Allow death here
return;
}
default:
{
//Prevent death in this phase
damage = 0;
return;
}
break;
}
}
};
struct MANGOS_DLL_DECL cthunAI : public ScriptedAI
{
cthunAI(Creature* pCreature) : ScriptedAI(pCreature)
{
SetCombatMovement(false);
m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
if (!m_pInstance)
error_log("SD2: No Instance eye_of_cthunAI");
Reset();
}
ScriptedInstance* m_pInstance;
//Out of combat whisper timer
uint32 WisperTimer;
//Global variables
uint32 PhaseTimer;
//-------------------
//Phase transition
uint64 HoldPlayer;
//Body Phase
uint32 EyeTentacleTimer;
uint8 FleshTentaclesKilled;
uint32 GiantClawTentacleTimer;
uint32 GiantEyeTentacleTimer;
uint32 StomachAcidTimer;
uint32 StomachEnterTimer;
uint32 StomachEnterVisTimer;
uint64 StomachEnterTarget;
//Stomach map, bool = true then in stomach
UNORDERED_MAP<uint64, bool> Stomach_Map;
void Reset()
{
//One random wisper every 90 - 300 seconds
WisperTimer = 90000;
//Phase information
PhaseTimer = 10000; //Emerge in 10 seconds
//No hold player for transition
HoldPlayer = 0;
//Body Phase
EyeTentacleTimer = 30000;
FleshTentaclesKilled = 0;
GiantClawTentacleTimer = 15000; //15 seconds into body phase (1 min repeat)
GiantEyeTentacleTimer = 45000; //15 seconds into body phase (1 min repeat)
StomachAcidTimer = 4000; //Every 4 seconds
StomachEnterTimer = 10000; //Every 10 seconds
StomachEnterVisTimer = 0; //Always 3.5 seconds after Stomach Enter Timer
StomachEnterTarget = 0; //Target to be teleported to stomach
//Clear players in stomach and outside
Stomach_Map.clear();
//Reset flags
m_creature->RemoveAurasDueToSpell(SPELL_TRANSFORM);
m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE);
if (m_pInstance)
m_pInstance->SetData(TYPE_CTHUN_PHASE, 0);
}
void Aggro(Unit* pWho)
{
m_creature->SetInCombatWithZone();
}
void SpawnEyeTentacle(float x, float y)
{
Creature* Spawned;
Spawned = (Creature*)m_creature->SummonCreature(MOB_EYE_TENTACLE,m_creature->GetPositionX()+x,m_creature->GetPositionY()+y,m_creature->GetPositionZ(),0,TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT,500);
if (Spawned)
{
Unit* target;
target = SelectRandomNotStomach();
if (target)
Spawned->AI()->AttackStart(target);
}
}
Unit* SelectRandomNotStomach()
{
if (Stomach_Map.empty())
return NULL;
UNORDERED_MAP<uint64, bool>::iterator i = Stomach_Map.begin();
std::list<Unit*> temp;
std::list<Unit*>::iterator j;
//Get all players in map
while (i != Stomach_Map.end())
{
//Check for valid player
Unit* pUnit = Unit::GetUnit(*m_creature, i->first);
//Only units out of stomach
if (pUnit && i->second == false)
{
temp.push_back(pUnit);
}
++i;
}
if (temp.empty())
return NULL;
j = temp.begin();
//Get random but only if we have more than one unit on threat list
if (temp.size() > 1)
advance (j , rand() % (temp.size() - 1));
return (*j);
}
void UpdateAI(const uint32 diff)
{
//Check if we have a target
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
{
//No target so we'll use this section to do our random wispers instance wide
//WisperTimer
if (WisperTimer < diff)
{
Map *map = m_creature->GetMap();
if (!map->IsDungeon())
return;
//Play random sound to the zone
Map::PlayerList const &PlayerList = map->GetPlayers();
if (!PlayerList.isEmpty())
{
for(Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr)
{
if (Player* pPlr = itr->getSource())
pPlr->PlayDirectSound(RANDOM_SOUND_WHISPER,pPlr);
}
}
//One random wisper every 90 - 300 seconds
WisperTimer = urand(90000, 300000);
}else WisperTimer -= diff;
return;
}
m_creature->SetUInt64Value(UNIT_FIELD_TARGET, 0);
//No instance
if (!m_pInstance)
return;
switch (m_pInstance->GetData(TYPE_CTHUN_PHASE))
{
//Transition phase
case 2:
{
//PhaseTimer
if (PhaseTimer < diff)
{
//Switch
m_pInstance->SetData(TYPE_CTHUN_PHASE, 3);
//Switch to c'thun model
m_creature->InterruptNonMeleeSpells(false);
DoCastSpellIfCan(m_creature, SPELL_TRANSFORM);
m_creature->SetHealth(m_creature->GetMaxHealth());
m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE);
//Emerging phase
//AttackStart(Unit::GetUnit(*m_creature, HoldPlayer));
m_creature->SetInCombatWithZone();
//Place all units in threat list on outside of stomach
Stomach_Map.clear();
ThreatList const& tList = m_creature->getThreatManager().getThreatList();
for (ThreatList::const_iterator i = tList.begin();i != tList.end(); ++i)
{
//Outside stomach
Stomach_Map[(*i)->getUnitGuid()] = false;
}
//Spawn 2 flesh tentacles
FleshTentaclesKilled = 0;
Creature* Spawned;
//Spawn flesh tentacle
Spawned = (Creature*)m_creature->SummonCreature(MOB_FLESH_TENTACLE, TENTACLE_POS1_X, TENTACLE_POS1_Y, TENTACLE_POS1_Z, TENTACLE_POS1_O, TEMPSUMMON_CORPSE_DESPAWN, 0);
if (!Spawned)
++FleshTentaclesKilled;
else
((flesh_tentacleAI*)(Spawned->AI()))->SpawnedByCthun(m_creature->GetGUID());
//Spawn flesh tentacle
Spawned = (Creature*)m_creature->SummonCreature(MOB_FLESH_TENTACLE, TENTACLE_POS2_X, TENTACLE_POS2_Y, TENTACLE_POS2_Z, TENTACLE_POS2_O, TEMPSUMMON_CORPSE_DESPAWN, 0);
if (!Spawned)
++FleshTentaclesKilled;
else
((flesh_tentacleAI*)(Spawned->AI()))->SpawnedByCthun(m_creature->GetGUID());
PhaseTimer = 0;
}else PhaseTimer -= diff;
}break;
//Body Phase
case 3:
{
//Remove Target field
m_creature->SetUInt64Value(UNIT_FIELD_TARGET, 0);
//Weaken
if (FleshTentaclesKilled > 1)
{
m_pInstance->SetData(TYPE_CTHUN_PHASE, 4);
DoScriptText(EMOTE_WEAKENED, m_creature);
PhaseTimer = 45000;
DoCastSpellIfCan(m_creature, SPELL_RED_COLORATION, CAST_TRIGGERED);
UNORDERED_MAP<uint64, bool>::iterator i = Stomach_Map.begin();
//Kick all players out of stomach
while (i != Stomach_Map.end())
{
//Check for valid player
Unit* pUnit = Unit::GetUnit(*m_creature, i->first);
//Only move units in stomach
if (pUnit && i->second == true)
{
//Teleport each player out
DoTeleportPlayer(pUnit, m_creature->GetPositionX(), m_creature->GetPositionY(), m_creature->GetPositionZ()+10, rand()%6);
//Cast knockback on them
DoCastSpellIfCan(pUnit, SPELL_EXIT_STOMACH_KNOCKBACK, CAST_TRIGGERED);
//Remove the acid debuff
pUnit->RemoveAurasDueToSpell(SPELL_DIGESTIVE_ACID);
i->second = false;
}
++i;
}
return;
}
//Stomach acid
if (StomachAcidTimer < diff)
{
//Apply aura to all players in stomach
UNORDERED_MAP<uint64, bool>::iterator i = Stomach_Map.begin();
while (i != Stomach_Map.end())
{
//Check for valid player
Unit* pUnit = Unit::GetUnit(*m_creature, i->first);
//Only apply to units in stomach
if (pUnit && i->second == true)
{
//Cast digestive acid on them
DoCastSpellIfCan(pUnit, SPELL_DIGESTIVE_ACID, CAST_TRIGGERED);
//Check if player should be kicked from stomach
if (pUnit->IsWithinDist3d(KICK_X, KICK_Y, KICK_Z, 15.0f))
{
//Teleport each player out
DoTeleportPlayer(pUnit, m_creature->GetPositionX(), m_creature->GetPositionY(), m_creature->GetPositionZ()+10, rand()%6);
//Cast knockback on them
DoCastSpellIfCan(pUnit, SPELL_EXIT_STOMACH_KNOCKBACK, CAST_TRIGGERED);
//Remove the acid debuff
pUnit->RemoveAurasDueToSpell(SPELL_DIGESTIVE_ACID);
i->second = false;
}
}
++i;
}
StomachAcidTimer = 4000;
}else StomachAcidTimer -= diff;
//Stomach Enter Timer
if (StomachEnterTimer < diff)
{
Unit* target = NULL;
target = SelectRandomNotStomach();
if (target)
{
//Set target in stomach
Stomach_Map[target->GetGUID()] = true;
target->InterruptNonMeleeSpells(false);
target->CastSpell(target, SPELL_MOUTH_TENTACLE, true, NULL, NULL, m_creature->GetGUID());
StomachEnterTarget = target->GetGUID();
StomachEnterVisTimer = 3800;
}
StomachEnterTimer = 13800;
}else StomachEnterTimer -= diff;
if (StomachEnterVisTimer && StomachEnterTarget)
if (StomachEnterVisTimer <= diff)
{
//Check for valid player
Unit* pUnit = Unit::GetUnit(*m_creature, StomachEnterTarget);
if (pUnit)
{
DoTeleportPlayer(pUnit, STOMACH_X, STOMACH_Y, STOMACH_Z, STOMACH_O);
}
StomachEnterTarget = 0;
StomachEnterVisTimer = 0;
}else StomachEnterVisTimer -= diff;
//GientClawTentacleTimer
if (GiantClawTentacleTimer < diff)
{
Unit* target = NULL;
target = SelectRandomNotStomach();
if (target)
{
Creature* Spawned = NULL;
//Spawn claw tentacle on the random target
Spawned = (Creature*)m_creature->SummonCreature(MOB_GIANT_CLAW_TENTACLE,target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(),0,TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT,500);
if (Spawned)
Spawned->AI()->AttackStart(target);
}
//One giant claw tentacle every minute
GiantClawTentacleTimer = 60000;
}else GiantClawTentacleTimer -= diff;
//GiantEyeTentacleTimer
if (GiantEyeTentacleTimer < diff)
{
Unit* target = NULL;
target = SelectRandomNotStomach();
if (target)
{
Creature* Spawned = NULL;
//Spawn claw tentacle on the random target
Spawned = (Creature*)m_creature->SummonCreature(MOB_GIANT_EYE_TENTACLE,target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(),0,TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT,500);
if (Spawned)
Spawned->AI()->AttackStart(target);
}
//One giant eye tentacle every minute
GiantEyeTentacleTimer = 60000;
}else GiantEyeTentacleTimer -= diff;
//EyeTentacleTimer
if (EyeTentacleTimer < diff)
{
//Spawn the 8 Eye Tentacles in the corret spots
SpawnEyeTentacle(0, 25); //south
SpawnEyeTentacle(12, 12); //south west
SpawnEyeTentacle(25, 0); //west
SpawnEyeTentacle(12, -12); //north west
SpawnEyeTentacle(0, -25); //north
SpawnEyeTentacle(-12, -12); //north east
SpawnEyeTentacle(-25, 0); // east
SpawnEyeTentacle(-12, 12); // south east
//These spawn at every 30 seconds
EyeTentacleTimer = 30000;
}else EyeTentacleTimer -= diff;
}break;
//Weakened state
case 4:
{
//PhaseTimer
if (PhaseTimer < diff)
{
//Switch
m_pInstance->SetData(TYPE_CTHUN_PHASE, 3);
//Remove red coloration
m_creature->RemoveAurasDueToSpell(SPELL_RED_COLORATION);
//Spawn 2 flesh tentacles
FleshTentaclesKilled = 0;
Creature* Spawned;
//Spawn flesh tentacle
Spawned = (Creature*)m_creature->SummonCreature(MOB_FLESH_TENTACLE, TENTACLE_POS1_X, TENTACLE_POS1_Y, TENTACLE_POS1_Z, TENTACLE_POS1_O, TEMPSUMMON_CORPSE_DESPAWN, 0);
if (!Spawned)
++FleshTentaclesKilled;
else
((flesh_tentacleAI*)(Spawned->AI()))->SpawnedByCthun(m_creature->GetGUID());
//Spawn flesh tentacle
Spawned = (Creature*)m_creature->SummonCreature(MOB_FLESH_TENTACLE, TENTACLE_POS2_X, TENTACLE_POS2_Y, TENTACLE_POS2_Z, TENTACLE_POS2_O, TEMPSUMMON_CORPSE_DESPAWN, 0);
if (!Spawned)
++FleshTentaclesKilled;
else
((flesh_tentacleAI*)(Spawned->AI()))->SpawnedByCthun(m_creature->GetGUID());
PhaseTimer = 0;
}else PhaseTimer -= diff;
}
}
}
void JustDied(Unit* pKiller)
{
//Switch
if (m_pInstance)
m_pInstance->SetData(TYPE_CTHUN_PHASE, 5);
}
void DamageTaken(Unit *done_by, uint32 &damage)
{
//No instance
if (!m_pInstance)
return;
switch (m_pInstance->GetData(TYPE_CTHUN_PHASE))
{
case 3:
{
//Not weakened so reduce damage by 99%
if (damage / 99 > 0) damage/= 99;
else damage = 1;
//Prevent death in non-weakened state
if (damage >= m_creature->GetHealth())
damage = 0;
return;
}
break;
case 4:
{
//Weakened - takes normal damage
return;
}
default:
damage = 0;
break;
}
}
void FleshTentcleKilled()
{
++FleshTentaclesKilled;
}
};
struct MANGOS_DLL_DECL eye_tentacleAI : public ScriptedAI
{
eye_tentacleAI(Creature* pCreature) : ScriptedAI(pCreature)
{
SetCombatMovement(false);
Reset();
if (Unit* pPortal = m_creature->SummonCreature(MOB_SMALL_PORTAL, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0))
Portal = pPortal->GetGUID();
}
uint32 MindflayTimer;
uint32 KillSelfTimer;
uint64 Portal;
void JustDied(Unit*)
{
Unit* p = Unit::GetUnit(*m_creature, Portal);
if (p)
p->DealDamage(p, p->GetMaxHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NONE, NULL, false);
}
void Reset()
{
//Mind flay half a second after we spawn
MindflayTimer = 500;
//This prevents eyes from overlapping
KillSelfTimer = 35000;
}
void Aggro(Unit* pWho)
{
m_creature->SetInCombatWithZone();
}
void UpdateAI(const uint32 diff)
{
//Check if we have a target
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
//KillSelfTimer
if (KillSelfTimer < diff)
{
m_creature->DealDamage(m_creature, m_creature->GetMaxHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NONE, NULL, false);
return;
}else KillSelfTimer -= diff;
//MindflayTimer
if (MindflayTimer < diff)
{
Unit* target = NULL;
target = SelectUnit(SELECT_TARGET_RANDOM,0);
if (target && !target->HasAura(SPELL_DIGESTIVE_ACID, EFFECT_INDEX_0))
DoCastSpellIfCan(target,SPELL_MIND_FLAY);
//Mindflay every 10 seconds
MindflayTimer = 10100;
}else MindflayTimer -= diff;
}
};
struct MANGOS_DLL_DECL claw_tentacleAI : public ScriptedAI
{
claw_tentacleAI(Creature* pCreature) : ScriptedAI(pCreature)
{
SetCombatMovement(false);
Reset();
if (Unit* pPortal = m_creature->SummonCreature(MOB_SMALL_PORTAL, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0))
Portal = pPortal->GetGUID();
}
uint32 GroundRuptureTimer;
uint32 HamstringTimer;
uint32 EvadeTimer;
uint64 Portal;
void JustDied(Unit*)
{
if (Unit* p = Unit::GetUnit(*m_creature, Portal))
p->DealDamage(p, p->GetMaxHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NONE, NULL, false);
}
void Reset()
{
//First rupture should happen half a second after we spawn
GroundRuptureTimer = 500;
HamstringTimer = 2000;
EvadeTimer = 5000;
}
void Aggro(Unit* pWho)
{
m_creature->SetInCombatWithZone();
}
void UpdateAI(const uint32 diff)
{
//Check if we have a target
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
//EvadeTimer
if (!m_creature->IsWithinDist(m_creature->getVictim(), ATTACK_DISTANCE))
if (EvadeTimer < diff)
{
if (Unit* p = Unit::GetUnit(*m_creature, Portal))
p->DealDamage(p, m_creature->GetMaxHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NONE, NULL, false);
//Dissapear and reappear at new position
m_creature->SetVisibility(VISIBILITY_OFF);
Unit* target = SelectUnit(SELECT_TARGET_RANDOM,0);
if (!target)
{
m_creature->DealDamage(m_creature, m_creature->GetMaxHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NONE, NULL, false);
return;
}
if (!target->HasAura(SPELL_DIGESTIVE_ACID, EFFECT_INDEX_0))
{
m_creature->GetMap()->CreatureRelocation(m_creature, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0);
if (Unit* pPortal = m_creature->SummonCreature(MOB_SMALL_PORTAL, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0))
Portal = pPortal->GetGUID();
GroundRuptureTimer = 500;
HamstringTimer = 2000;
EvadeTimer = 5000;
AttackStart(target);
}
m_creature->SetVisibility(VISIBILITY_ON);
}else EvadeTimer -= diff;
//GroundRuptureTimer
if (GroundRuptureTimer < diff)
{
DoCastSpellIfCan(m_creature->getVictim(),SPELL_GROUND_RUPTURE);
GroundRuptureTimer = 30000;
}else GroundRuptureTimer -= diff;
//HamstringTimer
if (HamstringTimer < diff)
{
DoCastSpellIfCan(m_creature->getVictim(),SPELL_HAMSTRING);
HamstringTimer = 5000;
}else HamstringTimer -= diff;
DoMeleeAttackIfReady();
}
};
struct MANGOS_DLL_DECL giant_claw_tentacleAI : public ScriptedAI
{
giant_claw_tentacleAI(Creature* pCreature) : ScriptedAI(pCreature)
{
SetCombatMovement(false);
Reset();
if (Unit* pPortal = m_creature->SummonCreature(MOB_GIANT_PORTAL, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0))
Portal = pPortal->GetGUID();
}
uint32 GroundRuptureTimer;
uint32 ThrashTimer;
uint32 HamstringTimer;
uint32 EvadeTimer;
uint64 Portal;
void JustDied(Unit*)
{
if (Unit* p = Unit::GetUnit(*m_creature, Portal))
p->DealDamage(p, p->GetMaxHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NONE, NULL, false);
}
void Reset()
{
//First rupture should happen half a second after we spawn
GroundRuptureTimer = 500;
HamstringTimer = 2000;
ThrashTimer = 5000;
EvadeTimer = 5000;
}
void Aggro(Unit* pWho)
{
m_creature->SetInCombatWithZone();
}
void UpdateAI(const uint32 diff)
{
//Check if we have a target
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
//EvadeTimer
if (m_creature->IsWithinDist(m_creature->getVictim(), ATTACK_DISTANCE))
if (EvadeTimer < diff)
{
if (Unit* p = Unit::GetUnit(*m_creature, Portal))
p->DealDamage(p, m_creature->GetMaxHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NONE, NULL, false);
//Dissapear and reappear at new position
m_creature->SetVisibility(VISIBILITY_OFF);
Unit* target = SelectUnit(SELECT_TARGET_RANDOM, 0);
if (!target)
{
m_creature->DealDamage(m_creature, m_creature->GetMaxHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NONE, NULL, false);
return;
}
if (!target->HasAura(SPELL_DIGESTIVE_ACID, EFFECT_INDEX_0))
{
m_creature->GetMap()->CreatureRelocation(m_creature, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0);
if (Unit* pPortal = m_creature->SummonCreature(MOB_GIANT_PORTAL, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0))
Portal = pPortal->GetGUID();
GroundRuptureTimer = 500;
HamstringTimer = 2000;
ThrashTimer = 5000;
EvadeTimer = 5000;
AttackStart(target);
}
m_creature->SetVisibility(VISIBILITY_ON);
}else EvadeTimer -= diff;
//GroundRuptureTimer
if (GroundRuptureTimer < diff)
{
DoCastSpellIfCan(m_creature->getVictim(),SPELL_GROUND_RUPTURE);
GroundRuptureTimer = 30000;
}else GroundRuptureTimer -= diff;
//ThrashTimer
if (ThrashTimer < diff)
{
DoCastSpellIfCan(m_creature->getVictim(),SPELL_THRASH);
ThrashTimer = 10000;
}else ThrashTimer -= diff;
//HamstringTimer
if (HamstringTimer < diff)
{
DoCastSpellIfCan(m_creature->getVictim(),SPELL_HAMSTRING);
HamstringTimer = 10000;
}else HamstringTimer -= diff;
DoMeleeAttackIfReady();
}
};
struct MANGOS_DLL_DECL giant_eye_tentacleAI : public ScriptedAI
{
giant_eye_tentacleAI(Creature* pCreature) : ScriptedAI(pCreature)
{
SetCombatMovement(false);
Reset();
if (Unit* pPortal = m_creature->SummonCreature(MOB_GIANT_PORTAL, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0))
Portal = pPortal->GetGUID();
}
uint32 BeamTimer;
uint64 Portal;
void JustDied(Unit*)
{
if (Unit* p = Unit::GetUnit(*m_creature, Portal))
p->DealDamage(p, p->GetMaxHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NONE, NULL, false);
}
void Reset()
{
//Green Beam half a second after we spawn
BeamTimer = 500;
}
void Aggro(Unit* pWho)
{
m_creature->SetInCombatWithZone();
}
void UpdateAI(const uint32 diff)
{
//Check if we have a target
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
//BeamTimer
if (BeamTimer < diff)
{
Unit* target = SelectUnit(SELECT_TARGET_RANDOM,0);
if (target && !target->HasAura(SPELL_DIGESTIVE_ACID, EFFECT_INDEX_0))
DoCastSpellIfCan(target,SPELL_GREEN_BEAM);
//Beam every 2 seconds
BeamTimer = 2100;
}else BeamTimer -= diff;
}
};
//Flesh tentacle functions
void flesh_tentacleAI::UpdateAI(const uint32 diff)
{
//Check if we have a target
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
if (Parent)
if (CheckTimer < diff)
{
Unit* pUnit = Unit::GetUnit(*m_creature, Parent);
if (!pUnit || !pUnit->isAlive() || !pUnit->isInCombat())
{
Parent = 0;
m_creature->DealDamage(m_creature, m_creature->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NONE, NULL, false);
return;
}
CheckTimer = 1000;
}else CheckTimer -= diff;
DoMeleeAttackIfReady();
}
void flesh_tentacleAI::JustDied(Unit* killer)
{
if (!Parent)
{
error_log("SD2: flesh_tentacle: No Parent variable");
return;
}
Creature* Cthun = (Creature*)Unit::GetUnit(*m_creature, Parent);
if (Cthun)
((cthunAI*)(Cthun->AI()))->FleshTentcleKilled();
else error_log("SD2: flesh_tentacle: No Cthun");
}
//GetAIs
CreatureAI* GetAI_eye_of_cthun(Creature* pCreature)
{
return new eye_of_cthunAI(pCreature);
}
CreatureAI* GetAI_cthun(Creature* pCreature)
{
return new cthunAI(pCreature);
}
CreatureAI* GetAI_eye_tentacle(Creature* pCreature)
{
return new eye_tentacleAI(pCreature);
}
CreatureAI* GetAI_claw_tentacle(Creature* pCreature)
{
return new claw_tentacleAI(pCreature);
}
CreatureAI* GetAI_giant_claw_tentacle(Creature* pCreature)
{
return new giant_claw_tentacleAI(pCreature);
}
CreatureAI* GetAI_giant_eye_tentacle(Creature* pCreature)
{
return new giant_eye_tentacleAI(pCreature);
}
CreatureAI* GetAI_flesh_tentacle(Creature* pCreature)
{
return new flesh_tentacleAI(pCreature);
}
void AddSC_boss_cthun()
{
Script *newscript;
//Eye
newscript = new Script;
newscript->Name = "boss_eye_of_cthun";
newscript->GetAI = &GetAI_eye_of_cthun;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "boss_cthun";
newscript->GetAI = &GetAI_cthun;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "mob_eye_tentacle";
newscript->GetAI = &GetAI_eye_tentacle;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "mob_claw_tentacle";
newscript->GetAI = &GetAI_claw_tentacle;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "mob_giant_claw_tentacle";
newscript->GetAI = &GetAI_giant_claw_tentacle;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "mob_giant_eye_tentacle";
newscript->GetAI = &GetAI_giant_eye_tentacle;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "mob_giant_flesh_tentacle";
newscript->GetAI = &GetAI_flesh_tentacle;
newscript->RegisterSelf();
}
| Apple15/AppleCore | src/bindings/scriptdev2/scripts/kalimdor/temple_of_ahnqiraj/boss_cthun.cpp | C++ | gpl-2.0 | 43,572 |
<?php
/**
* This file is part of http://github.com/LukeBeer/BroadworksOCIP
*
* (c) 2013-2015 Luke Berezynskyj <eat.lemons@gmail.com>
*/
namespace BroadworksOCIP\api\Rel_17_sp4_1_197_OCISchemaAS\OCISchemaSystem;
use BroadworksOCIP\Builder\Types\TableType;
use BroadworksOCIP\Builder\Types\ComplexInterface;
use BroadworksOCIP\Builder\Types\ComplexType;
use BroadworksOCIP\Response\ResponseOutput;
use BroadworksOCIP\Client\Client;
/**
* Response to a SystemTreatmentMappingQ850CauseGetListRequest. Contains a table with one row per mapping.
* The table columns are: "Q850 Cause Value", "Treatment Id".
*/
class SystemTreatmentMappingQ850CauseGetListResponse extends ComplexType implements ComplexInterface
{
public $elementName = 'SystemTreatmentMappingQ850CauseGetListResponse';
protected $treatmentMappingTable;
/**
* @return \BroadworksOCIP\api\Rel_17_sp4_1_197_OCISchemaAS\OCISchemaSystem\SystemTreatmentMappingQ850CauseGetListResponse $response
*/
public function get(Client $client, $responseOutput = ResponseOutput::STD)
{
return $this->send($client, $responseOutput);
}
/**
*
*/
public function setTreatmentMappingTable(TableType $treatmentMappingTable = null)
{
$this->treatmentMappingTable = $treatmentMappingTable;
$this->treatmentMappingTable->setElementName('treatmentMappingTable');
return $this;
}
/**
*
* @return TableType
*/
public function getTreatmentMappingTable()
{
return $this->treatmentMappingTable;
}
}
| paericksen/broadworks-ocip | src/BroadworksOCIP/api/Rel_17_sp4_1_197_OCISchemaAS/OCISchemaSystem/SystemTreatmentMappingQ850CauseGetListResponse.php | PHP | gpl-2.0 | 1,587 |
/*
* Copyright (C) 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of Apple Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "AccessibilityTableColumn.h"
#include "AXObjectCache.h"
#include "AccessibilityTableCell.h"
#include "HTMLCollection.h"
#include "HTMLElement.h"
#include "HTMLNames.h"
#include "RenderTable.h"
#include "RenderTableCell.h"
#include "RenderTableSection.h"
namespace WebCore {
using namespace HTMLNames;
AccessibilityTableColumn::AccessibilityTableColumn()
{
}
AccessibilityTableColumn::~AccessibilityTableColumn()
{
}
Ref<AccessibilityTableColumn> AccessibilityTableColumn::create()
{
return adoptRef(*new AccessibilityTableColumn());
}
void AccessibilityTableColumn::setParent(AccessibilityObject* parent)
{
AccessibilityMockObject::setParent(parent);
clearChildren();
}
LayoutRect AccessibilityTableColumn::elementRect() const
{
// This used to be cached during the call to addChildren(), but calling elementRect()
// can invalidate elements, so its better to ask for this on demand.
LayoutRect columnRect;
AccessibilityChildrenVector childrenCopy = m_children;
for (const auto& cell : childrenCopy)
columnRect.unite(cell->elementRect());
return columnRect;
}
AccessibilityObject* AccessibilityTableColumn::headerObject()
{
if (!m_parent)
return nullptr;
RenderObject* renderer = m_parent->renderer();
if (!renderer)
return nullptr;
if (!is<AccessibilityTable>(*m_parent))
return nullptr;
auto& parentTable = downcast<AccessibilityTable>(*m_parent);
if (!parentTable.isExposableThroughAccessibility())
return nullptr;
if (parentTable.isAriaTable()) {
for (const auto& cell : children()) {
if (cell->ariaRoleAttribute() == ColumnHeaderRole)
return cell.get();
}
return nullptr;
}
if (!is<RenderTable>(*renderer))
return nullptr;
RenderTable& table = downcast<RenderTable>(*renderer);
// try the <thead> section first. this doesn't require th tags
if (auto* headerObject = headerObjectForSection(table.header(), false))
return headerObject;
RenderTableSection* bodySection = table.firstBody();
while (bodySection && bodySection->isAnonymous())
bodySection = table.sectionBelow(bodySection, SkipEmptySections);
// now try for <th> tags in the first body. If the first body is
return headerObjectForSection(bodySection, true);
}
AccessibilityObject* AccessibilityTableColumn::headerObjectForSection(RenderTableSection* section, bool thTagRequired)
{
if (!section)
return nullptr;
unsigned numCols = section->numColumns();
if (m_columnIndex >= numCols)
return nullptr;
if (!section->numRows())
return nullptr;
RenderTableCell* cell = nullptr;
// also account for cells that have a span
for (int testCol = m_columnIndex; testCol >= 0; --testCol) {
// Run down the rows in case initial rows are invalid (like when a <caption> is used).
unsigned rowCount = section->numRows();
for (unsigned testRow = 0; testRow < rowCount; testRow++) {
RenderTableCell* testCell = section->primaryCellAt(testRow, testCol);
// No cell at this index, keep checking more rows and columns.
if (!testCell)
continue;
// If we've reached a cell that doesn't even overlap our column it can't be the header.
if ((testCell->col() + (testCell->colSpan()-1)) < m_columnIndex)
break;
Node* testCellNode = testCell->element();
// If the RenderTableCell doesn't have an element because its anonymous,
// try to see if we can find the original cell element to check if it has a <th> tag.
if (!testCellNode && testCell->isAnonymous()) {
if (Element* parentElement = testCell->parent() ? testCell->parent()->element() : nullptr) {
if (parentElement->hasTagName(trTag) && testCol < static_cast<int>(parentElement->countChildNodes()))
testCellNode = parentElement->traverseToChildAt(testCol);
}
}
if (!testCellNode)
continue;
// If th is required, but we found an element that doesn't have a th tag, we can stop looking.
if (thTagRequired && !testCellNode->hasTagName(thTag))
break;
cell = testCell;
break;
}
}
if (!cell)
return nullptr;
auto* cellObject = axObjectCache()->getOrCreate(cell);
if (!cellObject || cellObject->accessibilityIsIgnored())
return nullptr;
return cellObject;
}
bool AccessibilityTableColumn::computeAccessibilityIsIgnored() const
{
if (!m_parent)
return true;
#if PLATFORM(IOS) || PLATFORM(GTK)
return true;
#endif
return m_parent->accessibilityIsIgnored();
}
void AccessibilityTableColumn::addChildren()
{
ASSERT(!m_haveChildren);
m_haveChildren = true;
if (!is<AccessibilityTable>(m_parent))
return;
auto& parentTable = downcast<AccessibilityTable>(*m_parent);
if (!parentTable.isExposableThroughAccessibility())
return;
int numRows = parentTable.rowCount();
for (int i = 0; i < numRows; ++i) {
AccessibilityTableCell* cell = parentTable.cellForColumnAndRow(m_columnIndex, i);
if (!cell)
continue;
// make sure the last one isn't the same as this one (rowspan cells)
if (m_children.size() > 0 && m_children.last() == cell)
continue;
m_children.append(cell);
}
}
} // namespace WebCore
| Debian/openjfx | modules/web/src/main/native/Source/WebCore/accessibility/AccessibilityTableColumn.cpp | C++ | gpl-2.0 | 7,188 |
#ifndef BLISS_UTILS_HH
#define BLISS_UTILS_HH
/*
Copyright (c) 2003-2021 Tommi Junttila
Released under the GNU Lesser General Public License version 3.
This file is part of bliss.
bliss 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, version 3 of the License.
bliss 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 bliss. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
* \brief Some small utilities.
*/
#include <vector>
namespace bliss {
/**
* Check whether \a perm is a valid permutation on {0,...,N-1}.
* Slow, mainly for debugging and validation purposes.
*/
bool is_permutation(const unsigned int N, const unsigned int* perm);
/**
* Check whether \a perm is a valid permutation on {0,...,N-1}.
* Slow, mainly for debugging and validation purposes.
*/
bool is_permutation(const std::vector<unsigned int>& perm);
} // namespace bliss
#endif // BLISS_UTILS_HH
| szhorvat/igraph | src/isomorphism/bliss/utils.hh | C++ | gpl-2.0 | 1,297 |
<?php
/**
* @package RSP Extension for phpBB3.1
*
* @copyright (c) 2015 Marco Candian (tacitus@strategie-zone.de)
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2
*
*/
namespace tacitus89\rsp\entity;
/**
* Entity for a single ressource
*/
class user_ress extends abstractEntity
{
/**
* All of fields of this objects
*
**/
protected static $fields = array(
'id' => 'integer',
'user_id' => 'integer',
'ress_id' => 'object',
'menge' => 'integer',
);
/**
* All object must be assigned to a class
**/
protected static $subClasses = array(
'ress_id' => 'ressource',
);
/**
* Some fields must be unsigned (>= 0)
**/
protected static $validate_unsigned = array(
'id',
'user_id',
'menge',
);
/**
* Constructor
*
* @param \phpbb\db\driver\driver_interface $db Database object
* @param string $db_prefix The prefix of database table
* @return \tacitus89\rsp_extension\entity\ressource
* @access public
*/
public function __construct(\phpbb\db\driver\driver_interface $db, $db_prefix)
{
$this->db = $db;
$this->db_prefix = $db_prefix;
}
/**
* Generated the beginning SQL-Select Part
* WHERE and Order missing
*
* @param string $db_prefix The prefix of database table
* @return string The beginning sql select
* @access public
*/
public static function get_sql_select($db_prefix)
{
$sql = 'SELECT '. static::get_sql_fields(array('user_ress' => 'ur', 'ressource' => 'r')) .'
FROM ' . $db_prefix.\tacitus89\rsp\tables::$table['user_ress'] . ' ur
LEFT JOIN '. $db_prefix.\tacitus89\rsp\tables::$table['ressourcen'] .' r ON r.id = ur.ress_id';
return $sql;
}
/**
* Load the data from the database for this ressource
*
* @param int $user_id user identifier
* @return ressource_interface $this object for chaining calls; load()->set()->save()
* @access public
* @throws \tacitus89\rsp\exception\out_of_bounds
*/
public function load($id)
{
$sql = static::get_sql_select($this->db_prefix).'
WHERE '. $this->db->sql_in_set('ur.user_id', $user_id);
$result = $this->db->sql_query($sql);
$data = $this->db->sql_fetchrow($result);
$this->db->sql_freeresult($result);
if ($data === false)
{
// A gebaude does not exist
throw new \tacitus89\rsp_extension\exception\out_of_bounds('id');
}
//Import data
$this->import($data);
return $this;
}
/**
* Get user_id
*
* @return int user_id
* @access public
*/
public function get_user_id()
{
return $this->getInteger($this->data['user_id']);
}
/**
* Set user_id
*
* @param int $user_id
* @return game_interface $this object for chaining calls; load()->set()->save()
* @access public
* @throws \tacitus89\rsp\exception\unexpected_value
*/
public function set_user_id($user_id)
{
return $this->setInteger('user_id', $user_id);
}
/**
* Get ress_id
*
* @return object ress
* @access public
*/
public function get_ress()
{
return $this->data['ress_id'];
}
/**
* Set ress
*
* @param int $ress_id
* @return game_interface $this object for chaining calls; load()->set()->save()
* @access public
* @throws \tacitus89\rsp\exception\unexpected_value
*/
public function set_ress($user_id)
{
// Enforce a integer
$user_id = (integer) $user_id;
// If the data is less than 0, it's not unsigned and we'll throw an exception
if ($user_id < 0)
{
throw new \tacitus89\gamesmod\exception\out_of_bounds('user_id');
}
//Generated new games_cat object
$this->data['ress_id'] = new ressource($this->db, $this->ressourcen_table);
//Load the data for new parent
$this->data['ress_id']->load($user_id);
return $this;
}
/**
* Get menge
*
* @return int menge
* @access public
*/
public function get_menge()
{
return $this->getInteger($this->data['menge']);
}
/**
* Set menge
*
* @param int $menge
* @return game_interface $this object for chaining calls; load()->set()->save()
* @access public
* @throws \tacitus89\rsp\exception\unexpected_value
*/
public function set_menge($menge)
{
return $this->setInteger('menge', $menge);
}
}
| Kommodore/rsp_extension | entity/user_ress.php | PHP | gpl-2.0 | 4,208 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Input;
namespace ProjectSneakyGame
{
/// <summary>
/// Container that holds the entered input from an Xbox 360 Controller, Keyboard and Mouse.
/// Input is updated after it's parent 'Input' class has run its update method.
///
/// IMPORTANT: This class should only be used when retrieved from an 'Input' class via the 'RetrieveInputContainer' getter.
/// </summary>
public sealed class InputContainer
{
/// <summary>
/// Enumeration for specifying which Player input to check. Used in Xbox controller checking.
/// </summary>
public enum IndexPlayers { Player1 = 0, Player2 = 1, Player3 = 2, Player4 = 3, None = -1 };
private Input _parentInput; // The parent Input class that this InputContainer was retrieved from.
private List<Dictionary<Buttons, InputTypeComplex>> _gamePadCommandsC; // The List of Dictionaries of Xbox controller InputTypeComplex data that accesses the parent List via pointers.
private Dictionary<Keys, InputTypeComplex> _keyboardCommandsC; // The Dictionary of Keyboard InputTypeComplex data that accesses the parent Dictionary via pointers.
private Dictionary<MouseInput.MouseButtonsXNA, InputTypeComplex> _mouseCommandsC; // The Dictionary of Mouse InputTypeComplex data that accesses the parent Dictionary via pointers.
private MouseInput _mouse; // Data for the Mouse input that accesses the parent MouseInput data.
public MouseInput MouseData { get { return _mouse; } }
public InputContainer(List<Dictionary<Buttons, InputTypeComplex>> gamePadRefC, Dictionary<Keys, InputTypeComplex> keyboardRefC, Dictionary<MouseInput.MouseButtonsXNA, InputTypeComplex> mouseRefC, MouseInput mouse, Input parent)
{
_gamePadCommandsC = gamePadRefC;
_keyboardCommandsC = keyboardRefC;
_mouseCommandsC = mouseRefC;
_mouse = mouse;
_parentInput = parent;
}
~InputContainer()
{
_mouse = null;
_parentInput = null;
}
public bool IsFirstPressed(MouseInput.MouseButtonsXNA button)
{
return _mouseCommandsC [button].FirstPressed;
}
public bool IsFirstPressed(Keys key)
{
return _keyboardCommandsC [key].FirstPressed;
}
public bool IsFirstPressed(Buttons button)
{
return _gamePadCommandsC [0][button].FirstPressed;
}
public bool IsFirstPressed(IndexPlayers player, Buttons button)
{
return _gamePadCommandsC [(int)player] [button].FirstPressed;
}
public bool IsFirstReleased(MouseInput.MouseButtonsXNA button)
{
return _mouseCommandsC [button].FirstReleased;
}
public bool IsFirstReleased(Keys key)
{
return _keyboardCommandsC [key].FirstReleased;
}
public bool IsFirstReleased(Buttons button)
{
return _gamePadCommandsC [0] [button].FirstReleased;
}
public bool IsFirstReleased(IndexPlayers player, Buttons button)
{
return _gamePadCommandsC [(int)player] [button].FirstReleased;
}
public void EmulateInput(MouseInput.MouseButtonsXNA button)
{
_mouseCommandsC [button].Pressed = true;
}
public void EmulateInput(Keys key)
{
_keyboardCommandsC [key].Pressed = true;
}
public void EmulateInput(Buttons button)
{
EmulateInput(IndexPlayers.Player1, button);
}
public void EmulateInput(IndexPlayers player, Buttons button)
{
_gamePadCommandsC [(int)player] [button].Pressed = true;
}
public double TimePressed(MouseInput.MouseButtonsXNA button)
{
return _mouseCommandsC [button].TimePressed;
}
public double TimePressed(Keys key)
{
return _keyboardCommandsC [key].TimePressed;
}
public double TimePressed(Buttons button)
{
return _gamePadCommandsC [0] [button].TimePressed;
}
public double TimePressed(IndexPlayers player, Buttons button)
{
return _gamePadCommandsC [(int)player] [button].TimePressed;
}
/// <summary>
/// Checks the Xbox Controller input from the specified player to see if it has been pressed.
/// </summary>
/// <param name="player">'IndexPlayer' enum type.</param>
/// <param name="button">'Button' enum type of which input to check for.</param>
/// <returns>Returns true if button is pressed on specified player. Returns false if not.</returns>
public bool this[IndexPlayers player, Buttons button]
{
get
{
return _gamePadCommandsC [(int)player] [button].Pressed;
}
}
/// <summary>
/// Checks the Xbox Controller input from Player1 to see if the specified button has been pressed.
/// </summary>
/// <param name="button">'Button' enum type of which input to check for.</param>
/// <returns>Returns true if button is pressed on Player1. Returns false if not.</returns>
public bool this[Buttons button]
{
get
{
return _gamePadCommandsC [0] [button].Pressed;
}
}
/// <summary>
/// Checks the Keyboard to see if the specified key has been pressed.
/// </summary>
/// <param name="key">'Keys' enum type of which input to check for.</param>
/// <returns>Return true if key is pressed. Returns flase if not.</returns>
public bool this[Keys key]
{
get
{
return _keyboardCommandsC [key].Pressed;
}
}
/// <summary>
/// Checks the Mouse to see if the specified mouse button has been pressed.
/// </summary>
/// <param name="button">'MouseButtonsXNA' enum type of which input to check for.</param>
/// <returns>Return true if mouse button is pressed. Return false if not.</returns>
public bool this[MouseInput.MouseButtonsXNA button]
{
get
{
return _mouseCommandsC [button].Pressed;
}
}
}
}
| JoshuaKlaser/ANSKLibrary | AnimationExample/AnimationExample/InputContainer.cs | C# | gpl-2.0 | 6,474 |
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.xml.ws;
import java.util.Map;
import java.util.concurrent.Future;
/** The <code>Response</code> interface provides methods used to obtain the
* payload and context of a message sent in response to an operation
* invocation.
*
* <p>For asynchronous operation invocations it provides additional methods
* to check the status of the request. The <code>get(...)</code> methods may
* throw the standard
* set of exceptions and their cause may be a <code>RemoteException</code> or a
* {@link WebServiceException} that represents the error that occured during the
* asynchronous method invocation.</p>
*
* @since JAX-WS 2.0
**/
public interface Response<T> extends Future<T> {
/** Gets the contained response context.
*
* @return The contained response context. May be <code>null</code> if a
* response is not yet available.
*
**/
Map<String,Object> getContext();
}
| samskivert/ikvm-openjdk | build/linux-amd64/impsrc/javax/xml/ws/Response.java | Java | gpl-2.0 | 2,141 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2007-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.threshd;
import java.io.File;
import org.opennms.core.test.MockLogAppender;
import org.opennms.netmgt.rrd.RrdUtils;
/**
* FIXME: Should this test case go away now that we use ThresholdingVisitor?
*/
public class SnmpThresholderIntegrationTest extends ThresholderTestCase {
@SuppressWarnings("deprecation")
@Override
protected void setUp() throws Exception {
super.setUp();
MockLogAppender.setupLogging();
setupDatabase();
createMockRrd();
setupEventManager();
replayMocks();
String rrdRepository = "target/threshd-test";
String fileName = "cpuUtilization"+RrdUtils.getExtension();
int nodeId = 1;
String ipAddress = "192.168.1.1";
String serviceName = "SNMP";
String groupName = "default-snmp";
setupThresholdConfig(rrdRepository+File.separator+nodeId, fileName, nodeId, ipAddress, serviceName, groupName);
m_thresholder = new SnmpThresholder();
m_thresholder.initialize(m_serviceParameters);
m_thresholder.initialize(m_iface, m_parameters);
verifyMocks();
expectRrdStrategyCalls();
}
@Override
protected void tearDown() throws Exception {
RrdUtils.setStrategy(null);
MockLogAppender.assertNoWarningsOrGreater();
super.tearDown();
}
public void testNormalValue() throws Exception {
setupFetchSequence("cpuUtilization", 69.0, 79.0, 74.0, 74.0);
replayMocks();
ensureNoEventAfterFetches("cpuUtilization", 4);
verifyMocks();
}
public void testBigValue() throws Exception {
setupFetchSequence("cpuUtilization", 99.0, 98.0, 97.0, 96.0, 95.0);
replayMocks();
ensureExceededAfterFetches("cpuUtilization", 3);
ensureNoEventAfterFetches("cpuUtilization", 2);
verifyMocks();
}
public void testRearm() throws Exception {
double values[] = {
99.0,
91.0,
93.0, // expect exceeded
96.0,
15.0, // expect rearm
98.0,
98.0,
98.0 // expect exceeded
};
setupFetchSequence("cpuUtilization", values);
replayMocks();
ensureExceededAfterFetches("cpuUtilization", 3);
ensureRearmedAfterFetches("cpuUtilization", 2);
ensureExceededAfterFetches("cpuUtilization", 3);
verifyMocks();
}
}
| rfdrake/opennms | opennms-services/src/test/java/org/opennms/netmgt/threshd/SnmpThresholderIntegrationTest.java | Java | gpl-2.0 | 3,835 |
import itertools
def split_list_by(l, n):
for i in range(len(l)/n + 1):
p = l[i*n:(i+1)*n]
if p:
yield p
class CountingIterator(object):
def __init__(self, iterator):
self.iterator = iterator
self.count = 0
def __iter__(self):
return self
def next(self):
next = self.iterator.next()
self.count += 1
return next
def isplit_list_by(il, n):
"""
returns iterator of iterator2
each iterator2 will return n element of il
"""
il = iter(il) # to forget about length
while True:
p = CountingIterator(itertools.islice(il, n))
yield p
if p.count < n:
return
if __name__ == '__main__':
for x in isplit_list_by(xrange(400), 30):
print "------------"
for z in x:
print repr(z),
print
| onoga/toolib | toolib/util/split_list.py | Python | gpl-2.0 | 731 |
package net.longfalcon.newsj.ws.rss;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* The purpose of this element is something of a mystery! You can use it to specify a search engine box. Or to allow a reader to provide feedback. Most aggregators ignore it.
*
* <p>Java class for TextInput complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="TextInput">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <all>
* <element name="title" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="description" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="link" type="{http://www.w3.org/2001/XMLSchema}anyURI"/>
* </all>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TextInput", propOrder = {
})
public class TextInput {
@XmlElement(required = true)
protected String title;
@XmlElement(required = true)
protected String description;
@XmlElement(required = true)
protected String name;
@XmlElement(required = true)
@XmlSchemaType(name = "anyURI")
protected String link;
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the link property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLink() {
return link;
}
/**
* Sets the value of the link property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLink(String value) {
this.link = value;
}
}
| stewartcavanaugh/newsj | newsj-util/src/main/java/net/longfalcon/newsj/ws/rss/TextInput.java | Java | gpl-2.0 | 3,435 |
<?
if(!defined('EL11IDEAL_IN'))
exit;
include(EL11IDEAL_PATH.'modules/team.class.php');
class User{
var $logged=false;
var $id;
var $username;
var $c_uname;
var $team;
public function __destruct(){
unset($this->team);
}
public function check_log($return=false){
if($_SESSION['logged']==true){
global $mysql;
$query = $mysql->do_query("select pass,id,c_id from {{table}} where nick='". $_SESSION['nick'] ."'","users");
if(mysql_num_rows($query) > 0){
$resp = mysql_fetch_array($query);
if($_SESSION['pass'] == $resp['pass'])
{
$this->username = $_SESSION['nick'];
$this->id = (int)($resp['id']);
$this->c_id = (int)($resp['c_id']);
$this->logged=true;
$this->team = new Team($this->id, $this->c_id);
if($return)return true;
}else{
$this->logged=false;
if($return)return false;
}
}else{
$this->logged=false;
if($return)return false;
}
}else{
$this->logged=false;
if($return)return false;
}
}
public function register($nick, $pass, $nombre, $apellidos, $email){
global $mysql;
$r = $mysql->do_query("select * from {{table}} where nick='". $nick ."'",'users');
if (mysql_num_rows($r) > 0)
return 2;
if($mysql->do_query('insert into {{table}} (nick,pass,nombre,apellidos,email) values ("'. $nick .'","'. md5($pass) .'","'. $nombre .'","'. $apellidos .'","'. $email .'")', "users",'',false) == false)
return 3;
return 1;
}
public function log_in($uname, $upass){
global $mysql;
$query = $mysql->do_query('select * from {{table}} where nick="'. $uname .'" and pass="'. md5($upass) .'"', "users");
if(mysql_num_rows($query) > 0){
$resp = mysql_fetch_array($query);
$_SESSION['logged'] = true;
$_SESSION['nick'] = $uname;
$_SESSION['pass'] = md5($upass);
return true;
}else
return false;
}
public function log_out(){
$_SESSION['logged'] = false;
unset($_SESSION['nick']);
unset($_SESSION['pass']);
unset($_SESSION['SID']);
return true;
}
}
?> | blipi/El11Ideal | modules/user.php | PHP | gpl-2.0 | 2,098 |
#include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// 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:AssemblyTitleAttribute("CFControls")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("")];
[assembly:AssemblyProductAttribute("CFControls")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) 2008")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
| goose121/context-free | src-net/CFControls/AssemblyInfo.cpp | C++ | gpl-2.0 | 1,250 |
/*
* Copyright 2000-2003 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package java.nio;
/**
* A direct byte buffer whose content is a memory-mapped region of a file.
*
* <p> Mapped byte buffers are created via the {@link
* java.nio.channels.FileChannel#map FileChannel.map} method. This class
* extends the {@link ByteBuffer} class with operations that are specific to
* memory-mapped file regions.
*
* <p> A mapped byte buffer and the file mapping that it represents remain
* valid until the buffer itself is garbage-collected.
*
* <p> The content of a mapped byte buffer can change at any time, for example
* if the content of the corresponding region of the mapped file is changed by
* this program or another. Whether or not such changes occur, and when they
* occur, is operating-system dependent and therefore unspecified.
*
* <a name="inaccess"><p> All or part of a mapped byte buffer may become
* inaccessible at any time, for example if the mapped file is truncated. An
* attempt to access an inaccessible region of a mapped byte buffer will not
* change the buffer's content and will cause an unspecified exception to be
* thrown either at the time of the access or at some later time. It is
* therefore strongly recommended that appropriate precautions be taken to
* avoid the manipulation of a mapped file by this program, or by a
* concurrently running program, except to read or write the file's content.
*
* <p> Mapped byte buffers otherwise behave no differently than ordinary direct
* byte buffers. </p>
*
*
* @author Mark Reinhold
* @author JSR-51 Expert Group
* @since 1.4
*/
public abstract class MappedByteBuffer
extends ByteBuffer
{
// This is a little bit backwards: By rights MappedByteBuffer should be a
// subclass of DirectByteBuffer, but to keep the spec clear and simple, and
// for optimization purposes, it's easier to do it the other way around.
// This works because DirectByteBuffer is a package-private class.
// Volatile to make sure that the finalization thread sees the current
// value of this so that a region is not accidentally unmapped again later.
volatile boolean isAMappedBuffer; // package-private
// This should only be invoked by the DirectByteBuffer constructors
//
MappedByteBuffer(int mark, int pos, int lim, int cap, // package-private
boolean mapped)
{
super(mark, pos, lim, cap);
isAMappedBuffer = mapped;
}
MappedByteBuffer(int mark, int pos, int lim, int cap) { // package-private
super(mark, pos, lim, cap);
isAMappedBuffer = false;
}
private void checkMapped() {
if (!isAMappedBuffer)
// Can only happen if a luser explicitly casts a direct byte buffer
throw new UnsupportedOperationException();
}
/**
* Tells whether or not this buffer's content is resident in physical
* memory.
*
* <p> A return value of <tt>true</tt> implies that it is highly likely
* that all of the data in this buffer is resident in physical memory and
* may therefore be accessed without incurring any virtual-memory page
* faults or I/O operations. A return value of <tt>false</tt> does not
* necessarily imply that the buffer's content is not resident in physical
* memory.
*
* <p> The returned value is a hint, rather than a guarantee, because the
* underlying operating system may have paged out some of the buffer's data
* by the time that an invocation of this method returns. </p>
*
* @return <tt>true</tt> if it is likely that this buffer's content
* is resident in physical memory
*/
public final boolean isLoaded() {
checkMapped();
if ((address == 0) || (capacity() == 0))
return true;
return isLoaded0(((DirectByteBuffer)this).address(), capacity());
}
/**
* Loads this buffer's content into physical memory.
*
* <p> This method makes a best effort to ensure that, when it returns,
* this buffer's content is resident in physical memory. Invoking this
* method may cause some number of page faults and I/O operations to
* occur. </p>
*
* @return This buffer
*/
public final MappedByteBuffer load() {
checkMapped();
if ((address == 0) || (capacity() == 0))
return this;
load0(((DirectByteBuffer)this).address(), capacity(), Bits.pageSize());
return this;
}
/**
* Forces any changes made to this buffer's content to be written to the
* storage device containing the mapped file.
*
* <p> If the file mapped into this buffer resides on a local storage
* device then when this method returns it is guaranteed that all changes
* made to the buffer since it was created, or since this method was last
* invoked, will have been written to that device.
*
* <p> If the file does not reside on a local device then no such guarantee
* is made.
*
* <p> If this buffer was not mapped in read/write mode ({@link
* java.nio.channels.FileChannel.MapMode#READ_WRITE}) then invoking this
* method has no effect. </p>
*
* @return This buffer
*/
public final MappedByteBuffer force() {
checkMapped();
if ((address == 0) || (capacity() == 0))
return this;
force0(((DirectByteBuffer)this).address(), capacity());
return this;
}
private native boolean isLoaded0(long address, long length);
private native int load0(long address, long length, int pageSize);
private native void force0(long address, long length);
}
| TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/java/nio/MappedByteBuffer.java | Java | gpl-2.0 | 6,894 |
/*
* Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* The Original Code is HAT. The Initial Developer of the
* Original Code is Bill Foote, with contributions from others
* at JavaSoft/Sun.
*/
var hatPkg = Packages.com.sun.tools.hat.internal;
/**
* This is JavaScript interface for heap analysis using HAT
* (Heap Analysis Tool). HAT classes are referred from
* this file. In particular, refer to classes in hat.model
* package.
*
* HAT model objects are wrapped as convenient script objects so that
* fields may be accessed in natural syntax. For eg. Java fields can be
* accessed with obj.field_name syntax and array elements can be accessed
* with array[index] syntax.
*/
// returns an enumeration that wraps elements of
// the input enumeration elements.
function wrapperEnumeration(e) {
return new java.util.Enumeration() {
hasMoreElements: function() {
return e.hasMoreElements();
},
nextElement: function() {
return wrapJavaValue(e.nextElement());
}
};
}
// returns an enumeration that filters out elements
// of input enumeration using the filter function.
function filterEnumeration(e, func, wrap) {
var next = undefined;
var index = 0;
function findNext() {
var tmp;
while (e.hasMoreElements()) {
tmp = e.nextElement();
index++;
if (wrap) {
tmp = wrapJavaValue(tmp);
}
if (func(tmp, index, e)) {
next = tmp;
return;
}
}
}
return new java.util.Enumeration() {
hasMoreElements: function() {
findNext();
return next != undefined;
},
nextElement: function() {
if (next == undefined) {
// user may not have called hasMoreElements?
findNext();
}
if (next == undefined) {
throw "NoSuchElementException";
}
var res = next;
next = undefined;
return res;
}
};
}
// enumeration that has no elements ..
var emptyEnumeration = new java.util.Enumeration() {
hasMoreElements: function() {
return false;
},
nextElement: function() {
throw "NoSuchElementException";
}
};
function wrapRoot(root) {
if (root) {
return {
id: root.idString,
description: root.description,
referrer: wrapJavaValue(root.referer),
type: root.typeName
};
} else {
return null;
}
}
function JavaClassProto() {
function jclass(obj) {
return obj['wrapped-object'];
}
// return whether given class is subclass of this class or not
this.isSubclassOf = function(other) {
var tmp = jclass(this);
var otherid = objectid(other);
while (tmp != null) {
if (otherid.equals(tmp.idString)) {
return true;
}
tmp = tmp.superclass;
}
return false;
}
// return whether given class is superclass of this class or not
this.isSuperclassOf = function(other) {
return other.isSubclassOf(this);
}
// includes direct and indirect superclasses
this.superclasses = function() {
var res = new Array();
var tmp = this.superclass;
while (tmp != null) {
res[res.length] = tmp;
tmp = tmp.superclass;
}
return res;
}
/**
* Returns an array containing subclasses of this class.
*
* @param indirect should include indirect subclasses or not.
* default is true.
*/
this.subclasses = function(indirect) {
if (indirect == undefined) indirect = true;
var classes = jclass(this).subclasses;
var res = new Array();
for (var i in classes) {
var subclass = wrapJavaValue(classes[i]);
res[res.length] = subclass;
if (indirect) {
res = res.concat(subclass.subclasses());
}
}
return res;
}
this.toString = function() { return jclass(this).toString(); }
}
var theJavaClassProto = new JavaClassProto();
// Script wrapper for HAT model objects, values.
// wraps a Java value as appropriate for script object
function wrapJavaValue(thing) {
if (thing == null || thing == undefined ||
thing instanceof hatPkg.model.HackJavaValue) {
return null;
}
if (thing instanceof hatPkg.model.JavaValue) {
// map primitive values to closest JavaScript primitives
if (thing instanceof hatPkg.model.JavaBoolean) {
return thing.toString() == "true";
} else if (thing instanceof hatPkg.model.JavaChar) {
return thing.toString() + '';
} else {
return java.lang.Double.parseDouble(thing.toString());
}
} else {
// wrap Java object as script object
return wrapJavaObject(thing);
}
}
// wrap Java object with appropriate script object
function wrapJavaObject(thing) {
// HAT Java model object wrapper. Handles all cases
// (instance, object/primitive array and Class objects)
function javaObject(jobject) {
// FIXME: Do I need this? or can I assume that these would
// have been resolved already?
if (jobject instanceof hatPkg.model.JavaObjectRef) {
jobject = jobject.dereference();
if (jobject instanceof hatPkg.model.HackJavaValue) {
print(jobject);
return null;
}
}
if (jobject instanceof hatPkg.model.JavaObject) {
return new JavaObjectWrapper(jobject);
} else if (jobject instanceof hatPkg.model.JavaClass) {
return new JavaClassWrapper(jobject);
} else if (jobject instanceof hatPkg.model.JavaObjectArray) {
return new JavaObjectArrayWrapper(jobject);
} else if (jobject instanceof hatPkg.model.JavaValueArray) {
return new JavaValueArrayWrapper(jobject);
} else {
print("unknown heap object type: " + jobject.getClass());
return jobject;
}
}
// returns wrapper for Java instances
function JavaObjectWrapper(instance) {
var things = instance.fields;
var fields = instance.clazz.fieldsForInstance;
// instance fields can be accessed in natural syntax
return new JSAdapter() {
__getIds__ : function() {
var res = new Array(fields.length);
for (var i in fields) {
res[i] = fields[i].name;
}
return res;
},
__has__ : function(name) {
for (var i in fields) {
if (name == fields[i].name) return true;
}
return name == 'class' || name == 'toString' ||
name == 'wrapped-object';
},
__get__ : function(name) {
for (var i in fields) {
if(fields[i].name == name) {
return wrapJavaValue(things[i]);
}
}
if (name == 'class') {
return wrapJavaValue(instance.clazz);
} else if (name == 'toString') {
return function() {
return instance.toString();
}
} else if (name == 'wrapped-object') {
return instance;
}
return undefined;
}
}
}
// return wrapper for Java Class objects
function JavaClassWrapper(jclass) {
var fields = jclass.statics;
// to access static fields of given Class cl, use
// cl.statics.<static-field-name> syntax
this.statics = new JSAdapter() {
__getIds__ : function() {
var res = new Array(fields.length);
for (var i in fields) {
res[i] = fields[i].field.name;
}
return res;
},
__has__ : function(name) {
for (var i in fields) {
if (name == fields[i].field.name) {
return true;
}
}
return theJavaClassProto[name] != undefined;
},
__get__ : function(name) {
for (var i in fields) {
if (name == fields[i].field.name) {
return wrapJavaValue(fields[i].value);
}
}
return theJavaClassProto[name];
}
}
if (jclass.superclass != null) {
this.superclass = wrapJavaValue(jclass.superclass);
} else {
this.superclass = null;
}
this.loader = wrapJavaValue(jclass.getLoader());
this.signers = wrapJavaValue(jclass.getSigners());
this.protectionDomain = wrapJavaValue(jclass.getProtectionDomain());
this.instanceSize = jclass.instanceSize;
this.name = jclass.name;
this.fields = jclass.fields;
this['wrapped-object'] = jclass;
this.__proto__ = this.statics;
}
// returns wrapper for Java object arrays
function JavaObjectArrayWrapper(array) {
var elements = array.elements;
// array elements can be accessed in natural syntax
// also, 'length' property is supported.
return new JSAdapter() {
__getIds__ : function() {
var res = new Array(elements.length);
for (var i = 0; i < elements.length; i++) {
res[i] = i;
}
return res;
},
__has__: function(name) {
return (typeof(name) == 'number' &&
name >= 0 && name < elements.length) ||
name == 'length' || name == 'class' ||
name == 'toString' || name == 'wrapped-object';
},
__get__ : function(name) {
if (typeof(name) == 'number' &&
name >= 0 && name < elements.length) {
return wrapJavaValue(elements[name]);
} else if (name == 'length') {
return elements.length;
} else if (name == 'class') {
return wrapJavaValue(array.clazz);
} else if (name == 'toString') {
return function() { return array.toString(); }
} else if (name == 'wrapped-object') {
return array;
} else {
return undefined;
}
}
}
}
// returns wrapper for Java primitive arrays
function JavaValueArrayWrapper(array) {
var type = String(java.lang.Character.toString(array.elementType));
var elements = array.elements;
// array elements can be accessed in natural syntax
// also, 'length' property is supported.
return new JSAdapter() {
__getIds__ : function() {
var r = new Array(array.length);
for (var i = 0; i < array.length; i++) {
r[i] = i;
}
return r;
},
__has__: function(name) {
return (typeof(name) == 'number' &&
name >= 0 && name < array.length) ||
name == 'length' || name == 'class' ||
name == 'toString' || name == 'wrapped-object';
},
__get__: function(name) {
if (typeof(name) == 'number' &&
name >= 0 && name < array.length) {
return elements[name];
}
if (name == 'length') {
return array.length;
} else if (name == 'toString') {
return function() { return array.valueString(true); }
} else if (name == 'wrapped-object') {
return array;
} else if (name == 'class') {
return wrapJavaValue(array.clazz);
} else {
return undefined;
}
}
}
}
return javaObject(thing);
}
// unwrap a script object to corresponding HAT object
function unwrapJavaObject(jobject) {
if (!(jobject instanceof hatPkg.model.JavaHeapObject)) {
try {
jobject = jobject["wrapped-object"];
} catch (e) {
print("unwrapJavaObject: " + jobject + ", " + e);
jobject = undefined;
}
}
return jobject;
}
/**
* readHeapDump parses a heap dump file and returns script wrapper object.
*
* @param file Heap dump file name
* @param stack flag to tell if allocation site traces are available
* @param refs flag to tell if backward references are needed or not
* @param debug debug level for HAT
* @return heap as a JavaScript object
*/
function readHeapDump(file, stack, refs, debug) {
// default value of debug is 0
if (!debug) debug = 0;
// by default, we assume no stack traces
if (!stack) stack = false;
// by default, backward references are resolved
if (!refs) refs = true;
// read the heap dump
var heap = hatPkg.parser.HprofReader.readFile(file, stack, debug);
// resolve it
heap.resolve(refs);
// wrap Snapshot as convenient script object
return wrapHeapSnapshot(heap);
}
/**
* The result object supports the following methods:
*
* forEachClass -- calls a callback for each Java Class
* forEachObject -- calls a callback for each Java object
* findClass -- finds Java Class of given name
* findObject -- finds object from given object id
* objects -- returns all objects of given class as an enumeration
* classes -- returns all classes in the heap as an enumeration
* reachables -- returns all objects reachable from a given object
* livepaths -- returns an array of live paths because of which an
* object alive.
* describeRef -- returns description for a reference from a 'from'
* object to a 'to' object.
*/
function wrapHeapSnapshot(heap) {
function getClazz(clazz) {
if (clazz == undefined) clazz = "java.lang.Object";
var type = typeof(clazz);
if (type == "string") {
clazz = heap.findClass(clazz);
} else if (type == "object") {
clazz = unwrapJavaObject(clazz);
} else {
throw "class expected";;
}
return clazz;
}
// return heap as a script object with useful methods.
return {
snapshot: heap,
/**
* Class iteration: Calls callback function for each
* Java Class in the heap. Default callback function
* is 'print'. If callback returns true, the iteration
* is stopped.
*
* @param callback function to be called.
*/
forEachClass: function(callback) {
if (callback == undefined) callback = print;
var classes = this.snapshot.classes;
while (classes.hasMoreElements()) {
if (callback(wrapJavaValue(classes.nextElement())))
return;
}
},
/**
* Returns an Enumeration of all roots.
*/
roots: function() {
var e = this.snapshot.roots;
return new java.util.Enumeration() {
hasMoreElements: function() {
return e.hasMoreElements();
},
nextElement: function() {
return wrapRoot(e.nextElement());
}
};
},
/**
* Returns an Enumeration for all Java classes.
*/
classes: function() {
return wrapIterator(this.snapshot.classes, true);
},
/**
* Object iteration: Calls callback function for each
* Java Object in the heap. Default callback function
* is 'print'.If callback returns true, the iteration
* is stopped.
*
* @param callback function to be called.
* @param clazz Class whose objects are retrieved.
* Optional, default is 'java.lang.Object'
* @param includeSubtypes flag to tell if objects of subtypes
* are included or not. optional, default is true.
*/
forEachObject: function(callback, clazz, includeSubtypes) {
if (includeSubtypes == undefined) includeSubtypes = true;
if (callback == undefined) callback = print;
clazz = getClazz(clazz);
if (clazz) {
var instances = clazz.getInstances(includeSubtypes);
while (instances.hasNextElements()) {
if (callback(wrapJavaValue(instances.nextElement())))
return;
}
}
},
/**
* Returns an enumeration of Java objects in the heap.
*
* @param clazz Class whose objects are retrieved.
* Optional, default is 'java.lang.Object'
* @param includeSubtypes flag to tell if objects of subtypes
* are included or not. optional, default is true.
* @param where (optional) filter expression or function to
* filter the objects. The expression has to return true
* to include object passed to it in the result array.
* Built-in variable 'it' refers to the current object in
* filter expression.
*/
objects: function(clazz, includeSubtypes, where) {
if (includeSubtypes == undefined) includeSubtypes = true;
if (where) {
if (typeof(where) == 'string') {
where = new Function("it", "return " + where);
}
}
clazz = getClazz(clazz);
if (clazz) {
var instances = clazz.getInstances(includeSubtypes);
if (where) {
return filterEnumeration(instances, where, true);
} else {
return wrapperEnumeration(instances);
}
} else {
return emptyEnumeration;
}
},
/**
* Find Java Class of given name.
*
* @param name class name
*/
findClass: function(name) {
var clazz = this.snapshot.findClass(name + '');
return wrapJavaValue(clazz);
},
/**
* Find Java Object from given object id
*
* @param id object id as string
*/
findObject: function(id) {
return wrapJavaValue(this.snapshot.findThing(id));
},
/**
* Returns an enumeration of objects in the finalizer
* queue waiting to be finalized.
*/
finalizables: function() {
var tmp = this.snapshot.getFinalizerObjects();
return wrapperEnumeration(tmp);
},
/**
* Returns an array that contains objects referred from the
* given Java object directly or indirectly (i.e., all
* transitively referred objects are returned).
*
* @param jobject Java object whose reachables are returned.
*/
reachables: function (jobject) {
return reachables(jobject, this.snapshot.reachableExcludes);
},
/**
* Returns array of paths of references by which the given
* Java object is live. Each path itself is an array of
* objects in the chain of references. Each path supports
* toHtml method that returns html description of the path.
*
* @param jobject Java object whose live paths are returned
* @param weak flag to indicate whether to include paths with
* weak references or not. default is false.
*/
livepaths: function (jobject, weak) {
if (weak == undefined) {
weak = false;
}
function wrapRefChain(refChain) {
var path = new Array();
// compute path array from refChain
var tmp = refChain;
while (tmp != null) {
var obj = tmp.obj;
path[path.length] = wrapJavaValue(obj);
tmp = tmp.next;
}
function computeDescription(html) {
var root = refChain.obj.root;
var desc = root.description;
if (root.referer) {
var ref = root.referer;
desc += " (from " +
(html? toHtml(ref) : ref.toString()) + ')';
}
desc += '->';
var tmp = refChain;
while (tmp != null) {
var next = tmp.next;
var obj = tmp.obj;
desc += html? toHtml(obj) : obj.toString();
if (next != null) {
desc += " (" +
obj.describeReferenceTo(next.obj, heap) +
") ->";
}
tmp = next;
}
return desc;
}
return new JSAdapter() {
__getIds__ : function() {
var res = new Array(path.length);
for (var i = 0; i < path.length; i++) {
res[i] = i;
}
return res;
},
__has__ : function (name) {
return (typeof(name) == 'number' &&
name >= 0 && name < path.length) ||
name == 'length' || name == 'toHtml' ||
name == 'toString';
},
__get__ : function(name) {
if (typeof(name) == 'number' &&
name >= 0 && name < path.length) {
return path[name];
} else if (name == 'length') {
return path.length;
} else if (name == 'toHtml') {
return function() {
return computeDescription(true);
}
} else if (name == 'toString') {
return function() {
return computeDescription(false);
}
} else {
return undefined;
}
},
};
}
jobject = unwrapJavaObject(jobject);
var refChains = this.snapshot.rootsetReferencesTo(jobject, weak);
var paths = new Array(refChains.length);
for (var i in refChains) {
paths[i] = wrapRefChain(refChains[i]);
}
return paths;
},
/**
* Return description string for reference from 'from' object
* to 'to' Java object.
*
* @param from source Java object
* @param to destination Java object
*/
describeRef: function (from, to) {
from = unwrapJavaObject(from);
to = unwrapJavaObject(to);
return from.describeReferenceTo(to, this.snapshot);
},
};
}
// per-object functions
/**
* Returns allocation site trace (if available) of a Java object
*
* @param jobject object whose allocation site trace is returned
*/
function allocTrace(jobject) {
try {
jobject = unwrapJavaObject(jobject);
var trace = jobject.allocatedFrom;
return (trace != null) ? trace.frames : null;
} catch (e) {
print("allocTrace: " + jobject + ", " + e);
return null;
}
}
/**
* Returns Class object for given Java object
*
* @param jobject object whose Class object is returned
*/
function classof(jobject) {
jobject = unwrapJavaObject(jobject);
return wrapJavaValue(jobject.clazz);
}
/**
* Find referers (a.k.a in-coming references). Calls callback
* for each referrer of the given Java object. If the callback
* returns true, the iteration is stopped.
*
* @param callback function to call for each referer
* @param jobject object whose referers are retrieved
*/
function forEachReferrer(callback, jobject) {
jobject = unwrapJavaObject(jobject);
var refs = jobject.referers;
while (refs.hasMoreElements()) {
if (callback(wrapJavaValue(refs.nextElement()))) {
return;
}
}
}
/**
* Compares two Java objects for object identity.
*
* @param o1, o2 objects to compare for identity
*/
function identical(o1, o2) {
return objectid(o1) == objectid(o2);
}
/**
* Returns Java object id as string
*
* @param jobject object whose id is returned
*/
function objectid(jobject) {
try {
jobject = unwrapJavaObject(jobject);
return String(jobject.idString);
} catch (e) {
print("objectid: " + jobject + ", " + e);
return null;
}
}
/**
* Prints allocation site trace of given object
*
* @param jobject object whose allocation site trace is returned
*/
function printAllocTrace(jobject) {
var frames = this.allocTrace(jobject);
if (frames == null || frames.length == 0) {
print("allocation site trace unavailable for " +
objectid(jobject));
return;
}
print(objectid(jobject) + " was allocated at ..");
for (var i in frames) {
var frame = frames[i];
var src = frame.sourceFileName;
if (src == null) src = '<unknown source>';
print('\t' + frame.className + "." +
frame.methodName + '(' + frame.methodSignature + ') [' +
src + ':' + frame.lineNumber + ']');
}
}
/**
* Returns an enumeration of referrers of the given Java object.
*
* @param jobject Java object whose referrers are returned.
*/
function referrers(jobject) {
try {
jobject = unwrapJavaObject(jobject);
return wrapperEnumeration(jobject.referers);
} catch (e) {
print("referrers: " + jobject + ", " + e);
return emptyEnumeration;
}
}
/**
* Returns an array that contains objects referred from the
* given Java object.
*
* @param jobject Java object whose referees are returned.
*/
function referees(jobject) {
var res = new Array();
jobject = unwrapJavaObject(jobject);
if (jobject != undefined) {
try {
jobject.visitReferencedObjects(
new hatPkg.model.JavaHeapObjectVisitor() {
visit: function(other) {
res[res.length] = wrapJavaValue(other);
},
exclude: function(clazz, field) {
return false;
},
mightExclude: function() {
return false;
}
});
} catch (e) {
print("referees: " + jobject + ", " + e);
}
}
return res;
}
/**
* Returns an array that contains objects referred from the
* given Java object directly or indirectly (i.e., all
* transitively referred objects are returned).
*
* @param jobject Java object whose reachables are returned.
* @param excludes optional comma separated list of fields to be
* removed in reachables computation. Fields are
* written as class_name.field_name form.
*/
function reachables(jobject, excludes) {
if (excludes == undefined) {
excludes = null;
} else if (typeof(excludes) == 'string') {
var st = new java.util.StringTokenizer(excludes, ",");
var excludedFields = new Array();
while (st.hasMoreTokens()) {
excludedFields[excludedFields.length] = st.nextToken().trim();
}
if (excludedFields.length > 0) {
excludes = new hatPkg.model.ReachableExcludes() {
isExcluded: function (field) {
for (var index in excludedFields) {
if (field.equals(excludedFields[index])) {
return true;
}
}
return false;
}
};
} else {
// nothing to filter...
excludes = null;
}
} else if (! (excludes instanceof hatPkg.model.ReachableExcludes)) {
excludes = null;
}
jobject = unwrapJavaObject(jobject);
var ro = new hatPkg.model.ReachableObjects(jobject, excludes);
var tmp = ro.reachables;
var res = new Array(tmp.length);
for (var i in tmp) {
res[i] = wrapJavaValue(tmp[i]);
}
return res;
}
/**
* Returns whether 'from' object refers to 'to' object or not.
*
* @param from Java object that is source of the reference.
* @param to Java object that is destination of the reference.
*/
function refers(from, to) {
try {
var tmp = unwrapJavaObject(from);
if (tmp instanceof hatPkg.model.JavaClass) {
from = from.statics;
} else if (tmp instanceof hatPkg.model.JavaValueArray) {
return false;
}
for (var i in from) {
if (identical(from[i], to)) {
return true;
}
}
} catch (e) {
print("refers: " + from + ", " + e);
}
return false;
}
/**
* If rootset includes given jobject, return Root
* object explanining the reason why it is a root.
*
* @param jobject object whose Root is returned
*/
function root(jobject) {
try {
jobject = unwrapJavaObject(jobject);
return wrapRoot(jobject.root);
} catch (e) {
return null;
}
}
/**
* Returns size of the given Java object
*
* @param jobject object whose size is returned
*/
function sizeof(jobject) {
try {
jobject = unwrapJavaObject(jobject);
return jobject.size;
} catch (e) {
print("sizeof: " + jobject + ", " + e);
return null;
}
}
/**
* Returns String by replacing Unicode chars and
* HTML special chars (such as '<') with entities.
*
* @param str string to be encoded
*/
function encodeHtml(str) {
return hatPkg.util.Misc.encodeHtml(str);
}
/**
* Returns HTML string for the given object.
*
* @param obj object for which HTML string is returned.
*/
function toHtml(obj) {
if (obj == null) {
return "null";
}
if (obj == undefined) {
return "undefined";
}
var tmp = unwrapJavaObject(obj);
if (tmp != undefined) {
var id = tmp.idString;
if (tmp instanceof Packages.com.sun.tools.hat.internal.model.JavaClass) {
var name = tmp.name;
return "<a href='/class/" + id + "'>class " + name + "</a>";
} else {
var name = tmp.clazz.name;
return "<a href='/object/" + id + "'>" +
name + "@" + id + "</a>";
}
} else if ((typeof(obj) == 'object') || (obj instanceof JSAdapter)) {
if (obj instanceof java.lang.Object) {
// script wrapped Java object
obj = wrapIterator(obj);
// special case for enumeration
if (obj instanceof java.util.Enumeration) {
var res = "[ ";
while (obj.hasMoreElements()) {
res += toHtml(obj.nextElement()) + ", ";
}
res += "]";
return res;
} else {
return obj;
}
} else if (obj instanceof Array) {
// script array
var res = "[ ";
for (var i in obj) {
res += toHtml(obj[i]);
if (i != obj.length - 1) {
res += ", ";
}
}
res += " ]";
return res;
} else {
// if the object has a toHtml function property
// just use that...
if (typeof(obj.toHtml) == 'function') {
return obj.toHtml();
} else {
// script object
var res = "{ ";
for (var i in obj) {
res += i + ":" + toHtml(obj[i]) + ", ";
}
res += "}";
return res;
}
}
} else {
// JavaScript primitive value
return obj;
}
}
/*
* Generic array/iterator/enumeration [or even object!] manipulation
* functions. These functions accept an array/iteration/enumeration
* and expression String or function. These functions iterate each
* element of array and apply the expression/function on each element.
*/
// private function to wrap an Iterator as an Enumeration
function wrapIterator(itr, wrap) {
if (itr instanceof java.util.Iterator) {
return new java.util.Enumeration() {
hasMoreElements: function() {
return itr.hasNext();
},
nextElement: function() {
return wrap? wrapJavaValue(itr.next()) : itr.next();
}
};
} else {
return itr;
}
}
/**
* Converts an enumeration/iterator/object into an array
*
* @param obj enumeration/iterator/object
* @return array that contains values of enumeration/iterator/object
*/
function toArray(obj) {
obj = wrapIterator(obj);
if (obj instanceof java.util.Enumeration) {
var res = new Array();
while (obj.hasMoreElements()) {
res[res.length] = obj.nextElement();
}
return res;
} else if (obj instanceof Array) {
return obj;
} else {
var res = new Array();
for (var index in obj) {
res[res.length] = obj[index];
}
return res;
}
}
/**
* Returns whether the given array/iterator/enumeration contains
* an element that satisfies the given boolean expression specified
* in code.
*
* @param array input array/iterator/enumeration that is iterated
* @param code expression string or function
* @return boolean result
*
* The code evaluated can refer to the following built-in variables.
*
* 'it' -> currently visited element
* 'index' -> index of the current element
* 'array' -> array that is being iterated
*/
function contains(array, code) {
array = wrapIterator(array);
var func = code;
if (typeof(func) != 'function') {
func = new Function("it", "index", "array", "return " + code);
}
if (array instanceof java.util.Enumeration) {
var index = 0;
while (array.hasMoreElements()) {
var it = array.nextElement();
if (func(it, index, array)) {
return true;
}
index++;
}
} else {
for (var index in array) {
var it = array[index];
if (func(it, index, array)) {
return true;
}
}
}
return false;
}
/**
* concatenates two arrays/iterators/enumerators.
*
* @param array1 array/iterator/enumeration
* @param array2 array/iterator/enumeration
*
* @return concatenated array or composite enumeration
*/
function concat(array1, array2) {
array1 = wrapIterator(array1);
array2 = wrapIterator(array2);
if (array1 instanceof Array && array2 instanceof Array) {
return array1.concat(array2);
} else if (array1 instanceof java.util.Enumeration &&
array2 instanceof java.util.Enumeration) {
return new Packages.com.sun.tools.hat.internal.util.CompositeEnumeration(array1, array2);
} else {
return undefined;
}
}
/**
* Returns the number of array/iterator/enumeration elements
* that satisfy the given boolean expression specified in code.
* The code evaluated can refer to the following built-in variables.
*
* @param array input array/iterator/enumeration that is iterated
* @param code expression string or function
* @return number of elements
*
* 'it' -> currently visited element
* 'index' -> index of the current element
* 'array' -> array that is being iterated
*/
function count(array, code) {
if (code == undefined) {
return length(array);
}
array = wrapIterator(array);
var func = code;
if (typeof(func) != 'function') {
func = new Function("it", "index", "array", "return " + code);
}
var result = 0;
if (array instanceof java.util.Enumeration) {
var index = 0;
while (array.hasMoreElements()) {
var it = array.nextElement();
if (func(it, index, array)) {
result++;
}
index++;
}
} else {
for (var index in array) {
var it = array[index];
if (func(it, index, array)) {
result++;
}
}
}
return result;
}
/**
* filter function returns an array/enumeration that contains
* elements of the input array/iterator/enumeration that satisfy
* the given boolean expression. The boolean expression code can
* refer to the following built-in variables.
*
* @param array input array/iterator/enumeration that is iterated
* @param code expression string or function
* @return array/enumeration that contains the filtered elements
*
* 'it' -> currently visited element
* 'index' -> index of the current element
* 'array' -> array that is being iterated
* 'result' -> result array
*/
function filter(array, code) {
array = wrapIterator(array);
var func = code;
if (typeof(code) != 'function') {
func = new Function("it", "index", "array", "result", "return " + code);
}
if (array instanceof java.util.Enumeration) {
return filterEnumeration(array, func, false);
} else {
var result = new Array();
for (var index in array) {
var it = array[index];
if (func(it, index, array, result)) {
result[result.length] = it;
}
}
return result;
}
}
/**
* Returns the number of elements of array/iterator/enumeration.
*
* @param array input array/iterator/enumeration that is iterated
*/
function length(array) {
array = wrapIterator(array);
if (array instanceof Array) {
return array.length;
} else if (array instanceof java.util.Enumeration) {
var cnt = 0;
while (array.hasMoreElements()) {
array.nextElement();
cnt++;
}
return cnt;
} else {
var cnt = 0;
for (var index in array) {
cnt++;
}
return cnt;
}
}
/**
* Transforms the given object or array by evaluating given code
* on each element of the object or array. The code evaluated
* can refer to the following built-in variables.
*
* @param array input array/iterator/enumeration that is iterated
* @param code expression string or function
* @return array/enumeration that contains mapped values
*
* 'it' -> currently visited element
* 'index' -> index of the current element
* 'array' -> array that is being iterated
* 'result' -> result array
*
* map function returns an array/enumeration of values created
* by repeatedly calling code on each element of the input
* array/iterator/enumeration.
*/
function map(array, code) {
array = wrapIterator(array);
var func = code;
if(typeof(code) != 'function') {
func = new Function("it", "index", "array", "result", "return " + code);
}
if (array instanceof java.util.Enumeration) {
var index = 0;
var result = new java.util.Enumeration() {
hasMoreElements: function() {
return array.hasMoreElements();
},
nextElement: function() {
return func(array.nextElement(), index++, array, result);
}
};
return result;
} else {
var result = new Array();
for (var index in array) {
var it = array[index];
result[result.length] = func(it, index, array, result);
}
return result;
}
}
// private function used by min, max functions
function minmax(array, code) {
if (typeof(code) == 'string') {
code = new Function("lhs", "rhs", "return " + code);
}
array = wrapIterator(array);
if (array instanceof java.util.Enumeration) {
if (! array.hasMoreElements()) {
return undefined;
}
var res = array.nextElement();
while (array.hasMoreElements()) {
var next = array.nextElement();
if (code(next, res)) {
res = next;
}
}
return res;
} else {
if (array.length == 0) {
return undefined;
}
var res = array[0];
for (var index = 1; index < array.length; index++) {
if (code(array[index], res)) {
res = array[index];
}
}
return res;
}
}
/**
* Returns the maximum element of the array/iterator/enumeration
*
* @param array input array/iterator/enumeration that is iterated
* @param code (optional) comparision expression or function
* by default numerical maximum is computed.
*/
function max(array, code) {
if (code == undefined) {
code = function (lhs, rhs) { return lhs > rhs; }
}
return minmax(array, code);
}
/**
* Returns the minimum element of the array/iterator/enumeration
*
* @param array input array/iterator/enumeration that is iterated
* @param code (optional) comparision expression or function
* by default numerical minimum is computed.
*/
function min(array, code) {
if (code == undefined) {
code = function (lhs, rhs) { return lhs < rhs; }
}
return minmax(array, code);
}
/**
* sort function sorts the input array. optionally accepts
* code to compare the elements. If code is not supplied,
* numerical sort is done.
*
* @param array input array/iterator/enumeration that is sorted
* @param code expression string or function
* @return sorted array
*
* The comparison expression can refer to the following
* built-in variables:
*
* 'lhs' -> 'left side' element
* 'rhs' -> 'right side' element
*/
function sort(array, code) {
// we need an array to sort, so convert non-arrays
array = toArray(array);
// by default use numerical comparison
var func = code;
if (code == undefined) {
func = function(lhs, rhs) { return lhs - rhs; };
} else if (typeof(code) == 'string') {
func = new Function("lhs", "rhs", "return " + code);
}
return array.sort(func);
}
/**
* Returns the sum of the elements of the array
*
* @param array input array that is summed.
* @param code optional expression used to map
* input elements before sum.
*/
function sum(array, code) {
array = wrapIterator(array);
if (code != undefined) {
array = map(array, code);
}
var result = 0;
if (array instanceof java.util.Enumeration) {
while (array.hasMoreElements()) {
result += Number(array.nextElement());
}
} else {
for (var index in array) {
result += Number(array[index]);
}
}
return result;
}
/**
* Returns array of unique elements from the given input
* array/iterator/enumeration.
*
* @param array from which unique elements are returned.
* @param code optional expression (or function) giving unique
* attribute/property for each element.
* by default, objectid is used for uniqueness.
*/
function unique(array, code) {
array = wrapIterator(array);
if (code == undefined) {
code = new Function("it", "return objectid(it);");
} else if (typeof(code) == 'string') {
code = new Function("it", "return " + code);
}
var tmp = new Object();
if (array instanceof java.util.Enumeration) {
while (array.hasMoreElements()) {
var it = array.nextElement();
tmp[code(it)] = it;
}
} else {
for (var index in array) {
var it = array[index];
tmp[code(it)] = it;
}
}
var res = new Array();
for (var index in tmp) {
res[res.length] = tmp[index];
}
return res;
}
| openjdk/jdk7u | jdk/src/share/classes/com/sun/tools/hat/resources/hat.js | JavaScript | gpl-2.0 | 46,751 |
<?php
namespace Drupal\Tests\webform\Functional\Cache;
use Drupal\Tests\webform\Functional\WebformBrowserTestBase;
use Drupal\webform\Entity\Webform;
use Drupal\webform\Entity\WebformSubmission;
/**
* Tests for #cache properties.
*
* @group webform
*/
class WebformCacheTest extends WebformBrowserTestBase {
/**
* Test cache.
*/
public function testCache() {
/** @var \Drupal\Core\Entity\EntityFormBuilder $entity_form_builder */
$entity_form_builder = \Drupal::service('entity.form_builder');
$account = $this->createUser();
/** @var \Drupal\webform\WebformInterface $webform */
$webform = Webform::load('contact');
/** @var \Drupal\webform\WebformSubmissionInterface $webform_submission */
$webform_submission = WebformSubmission::create(['webform_id' => 'contact']);
/* ********************************************************************** */
$form = $entity_form_builder->getForm($webform_submission, 'add');
// Check that the form includes 'user.roles:authenticated' because the
// '[current-user:mail]' token.
$this->assertEqualsCanonicalizing($form['#cache'], [
'contexts' => [
'user.roles:authenticated',
],
'tags' => [
'config:core.entity_form_display.webform_submission.contact.add',
'config:webform.settings',
'config:webform.webform.contact',
'webform:contact',
],
'max-age' => -1,
]);
// Check that the name element does not have #cache because the
// '[current-user:mail]' is set via
// \Drupal\webform\WebformSubmissionForm::setEntity.
$this->assertFalse(isset($form['elements']['email']['#cache']));
$this->assertEqual($form['elements']['email']['#default_value'], '');
// Login and check the #cache property.
$this->drupalLogin($account);
$webform_submission->setOwnerId($account);
\Drupal::currentUser()->setAccount($account);
// Must create a new submission with new data which is set via
// WebformSubmissionForm::setEntity.
// @see \Drupal\webform\WebformSubmissionForm::setEntity
$webform_submission = WebformSubmission::create(['webform_id' => 'contact']);
$form = $entity_form_builder->getForm($webform_submission, 'add');
// Check that the form includes 'user.roles:authenticated' because the
// '[current-user:mail]' token.
$this->assertEqualsCanonicalizing($form['#cache'], [
'contexts' => [
'user',
'user.roles:authenticated',
],
'tags' => [
'config:core.entity_form_display.webform_submission.contact.add',
'config:webform.settings',
'config:webform.webform.contact',
'user:2',
'webform:contact',
],
'max-age' => -1,
]);
$this->assertFalse(isset($form['elements']['email']['#cache']));
$this->assertEqual($form['elements']['email']['#default_value'], $account->getEmail());
// Add the '[current-user:mail]' to the name elements' description.
$element = $webform->getElementDecoded('email')
+ ['#description' => '[current-user:mail]']; // phpcs:ignore
$webform
->setElementProperties('email', $element)
->save();
$form = $entity_form_builder->getForm($webform_submission, 'add');
// Check that the 'email' element does have '#cache' property because the
// '#description' is using the '[current-user:mail]' token.
$this->assertEqualsCanonicalizing($form['elements']['email']['#cache'], [
'contexts' => [
'user',
],
'tags' => [
'config:webform.settings',
'config:webform.webform.contact',
'user:2',
'webform:contact',
],
'max-age' => -1,
]);
$this->assertEqual($form['elements']['email']['#default_value'], $account->getEmail());
$this->assertEqual($form['elements']['email']['#description']['#markup'], $account->getEmail());
}
}
| tobiasbuhrer/tobiasb | web/modules/contrib/webform/tests/src/Functional/Cache/WebformCacheTest.php | PHP | gpl-2.0 | 3,909 |
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.bind.v2.runtime.reflect;
import com.sun.xml.internal.bind.api.AccessorException;
import com.sun.xml.internal.bind.v2.runtime.XMLSerializer;
/**
* {@link Lister} for primitive type arrays.
*
* <p>
* B y t e ArrayLister is used as the master to generate the rest of the
* lister classes. Do not modify the generated copies.
*/
final class PrimitiveArrayListerFloat<BeanT> extends Lister<BeanT,float[],Float,PrimitiveArrayListerFloat.FloatArrayPack> {
private PrimitiveArrayListerFloat() {
}
/*package*/ static void register() {
Lister.primitiveArrayListers.put(Float.TYPE,new PrimitiveArrayListerFloat());
}
public ListIterator<Float> iterator(final float[] objects, XMLSerializer context) {
return new ListIterator<Float>() {
int idx=0;
public boolean hasNext() {
return idx<objects.length;
}
public Float next() {
return objects[idx++];
}
};
}
public FloatArrayPack startPacking(BeanT current, Accessor<BeanT, float[]> acc) {
return new FloatArrayPack();
}
public void addToPack(FloatArrayPack objects, Float o) {
objects.add(o);
}
public void endPacking( FloatArrayPack pack, BeanT bean, Accessor<BeanT,float[]> acc ) throws AccessorException {
acc.set(bean,pack.build());
}
public void reset(BeanT o,Accessor<BeanT,float[]> acc) throws AccessorException {
acc.set(o,new float[0]);
}
static final class FloatArrayPack {
float[] buf = new float[16];
int size;
void add(Float b) {
if(buf.length==size) {
// realloc
float[] nb = new float[buf.length*2];
System.arraycopy(buf,0,nb,0,buf.length);
buf = nb;
}
if(b!=null)
buf[size++] = b;
}
float[] build() {
if(buf.length==size)
// if we are lucky enough
return buf;
float[] r = new float[size];
System.arraycopy(buf,0,r,0,size);
return r;
}
}
}
| samskivert/ikvm-openjdk | build/linux-amd64/impsrc/com/sun/xml/internal/bind/v2/runtime/reflect/PrimitiveArrayListerFloat.java | Java | gpl-2.0 | 3,411 |
/*
* Copyright (C) 2005-2008 Team XBMC
* http://www.xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include "ScraperParser.h"
#include "addons/AddonManager.h"
#include "RegExp.h"
#include "HTMLUtil.h"
#include "addons/Scraper.h"
#include "URL.h"
#include "Util.h"
#include "log.h"
#include "CharsetConverter.h"
#include <sstream>
#include <cstring>
using namespace std;
using namespace ADDON;
using namespace XFILE;
CScraperParser::CScraperParser()
{
m_pRootElement = NULL;
m_document = NULL;
m_SearchStringEncoding = "UTF-8";
}
CScraperParser::CScraperParser(const CScraperParser& parser)
{
m_document = NULL;
m_SearchStringEncoding = "UTF-8";
*this = parser;
}
CScraperParser &CScraperParser::operator=(const CScraperParser &parser)
{
if (this != &parser)
{
Clear();
if (parser.m_document)
{
m_scraper = parser.m_scraper;
m_document = new TiXmlDocument(*parser.m_document);
LoadFromXML();
}
}
return *this;
}
CScraperParser::~CScraperParser()
{
Clear();
}
void CScraperParser::Clear()
{
m_pRootElement = NULL;
delete m_document;
m_document = NULL;
m_strFile.Empty();
}
bool CScraperParser::Load(const CStdString& strXMLFile)
{
Clear();
m_document = new TiXmlDocument(strXMLFile);
if (!m_document)
return false;
m_strFile = strXMLFile;
if (m_document->LoadFile())
return LoadFromXML();
delete m_document;
m_document = NULL;
return false;
}
bool CScraperParser::LoadFromXML()
{
if (!m_document)
return false;
m_pRootElement = m_document->RootElement();
CStdString strValue = m_pRootElement->Value();
if (strValue == "scraper")
{
TiXmlElement* pChildElement = m_pRootElement->FirstChildElement("CreateSearchUrl");
if (pChildElement)
{
if (!(m_SearchStringEncoding = pChildElement->Attribute("SearchStringEncoding")))
m_SearchStringEncoding = "UTF-8";
}
pChildElement = m_pRootElement->FirstChildElement("CreateArtistSearchUrl");
if (pChildElement)
{
if (!(m_SearchStringEncoding = pChildElement->Attribute("SearchStringEncoding")))
m_SearchStringEncoding = "UTF-8";
}
pChildElement = m_pRootElement->FirstChildElement("CreateAlbumSearchUrl");
if (pChildElement)
{
if (!(m_SearchStringEncoding = pChildElement->Attribute("SearchStringEncoding")))
m_SearchStringEncoding = "UTF-8";
}
return true;
}
delete m_document;
m_document = NULL;
m_pRootElement = NULL;
return false;
}
void CScraperParser::ReplaceBuffers(CStdString& strDest)
{
// insert buffers
int iIndex;
for (int i=MAX_SCRAPER_BUFFERS-1; i>=0; i--)
{
CStdString temp;
iIndex = 0;
temp.Format("$$%i",i+1);
while ((size_t)(iIndex = strDest.find(temp,iIndex)) != CStdString::npos) // COPIED FROM CStdString WITH THE ADDITION OF $ ESCAPING
{
strDest.replace(strDest.begin()+iIndex,strDest.begin()+iIndex+temp.GetLength(),m_param[i]);
iIndex += m_param[i].length();
}
}
// insert settings
iIndex = 0;
while ((size_t)(iIndex = strDest.find("$INFO[",iIndex)) != CStdString::npos)
{
int iEnd = strDest.Find("]",iIndex);
CStdString strInfo = strDest.Mid(iIndex+6,iEnd-iIndex-6);
CStdString strReplace;
if (m_scraper)
strReplace = m_scraper->GetSetting(strInfo);
strDest.replace(strDest.begin()+iIndex,strDest.begin()+iEnd+1,strReplace);
iIndex += strReplace.length();
}
iIndex = 0;
while ((size_t)(iIndex = strDest.find("\\n",iIndex)) != CStdString::npos)
strDest.replace(strDest.begin()+iIndex,strDest.begin()+iIndex+2,"\n");
}
void CScraperParser::ParseExpression(const CStdString& input, CStdString& dest, TiXmlElement* element, bool bAppend)
{
CStdString strOutput = element->Attribute("output");
TiXmlElement* pExpression = element->FirstChildElement("expression");
if (pExpression)
{
bool bInsensitive=true;
const char* sensitive = pExpression->Attribute("cs");
if (sensitive)
if (stricmp(sensitive,"yes") == 0)
bInsensitive=false; // match case sensitive
CRegExp reg(bInsensitive);
CStdString strExpression;
if (pExpression->FirstChild())
strExpression = pExpression->FirstChild()->Value();
else
strExpression = "(.*)";
ReplaceBuffers(strExpression);
ReplaceBuffers(strOutput);
if (!reg.RegComp(strExpression.c_str()))
{
return;
}
bool bRepeat = false;
const char* szRepeat = pExpression->Attribute("repeat");
if (szRepeat)
if (stricmp(szRepeat,"yes") == 0)
bRepeat = true;
const char* szClear = pExpression->Attribute("clear");
if (szClear)
if (stricmp(szClear,"yes") == 0)
dest=""; // clear no matter if regexp fails
bool bClean[MAX_SCRAPER_BUFFERS];
GetBufferParams(bClean,pExpression->Attribute("noclean"),true);
bool bTrim[MAX_SCRAPER_BUFFERS];
GetBufferParams(bTrim,pExpression->Attribute("trim"),false);
bool bFixChars[MAX_SCRAPER_BUFFERS];
GetBufferParams(bFixChars,pExpression->Attribute("fixchars"),false);
bool bEncode[MAX_SCRAPER_BUFFERS];
GetBufferParams(bEncode,pExpression->Attribute("encode"),false);
int iOptional = -1;
pExpression->QueryIntAttribute("optional",&iOptional);
int iCompare = -1;
pExpression->QueryIntAttribute("compare",&iCompare);
if (iCompare > -1)
m_param[iCompare-1].ToLower();
CStdString curInput = input;
for (int iBuf=0;iBuf<MAX_SCRAPER_BUFFERS;++iBuf)
{
if (bClean[iBuf])
InsertToken(strOutput,iBuf+1,"!!!CLEAN!!!");
if (bTrim[iBuf])
InsertToken(strOutput,iBuf+1,"!!!TRIM!!!");
if (bFixChars[iBuf])
InsertToken(strOutput,iBuf+1,"!!!FIXCHARS!!!");
if (bEncode[iBuf])
InsertToken(strOutput,iBuf+1,"!!!ENCODE!!!");
}
int i = reg.RegFind(curInput.c_str());
while (i > -1 && (i < (int)curInput.size() || curInput.size() == 0))
{
if (!bAppend)
{
dest = "";
bAppend = true;
}
CStdString strCurOutput=strOutput;
if (iOptional > -1) // check that required param is there
{
char temp[4];
sprintf(temp,"\\%i",iOptional);
char* szParam = reg.GetReplaceString(temp);
CRegExp reg2;
reg2.RegComp("(.*)(\\\\\\(.*\\\\2.*)\\\\\\)(.*)");
int i2=reg2.RegFind(strCurOutput.c_str());
while (i2 > -1)
{
char* szRemove = reg2.GetReplaceString("\\2");
int iRemove = strlen(szRemove);
int i3 = strCurOutput.find(szRemove);
if (szParam && strcmp(szParam,""))
{
strCurOutput.erase(i3+iRemove,2);
strCurOutput.erase(i3,2);
}
else
strCurOutput.replace(strCurOutput.begin()+i3,strCurOutput.begin()+i3+iRemove+2,"");
free(szRemove);
i2 = reg2.RegFind(strCurOutput.c_str());
}
free(szParam);
}
int iLen = reg.GetFindLen();
// nasty hack #1 - & means \0 in a replace string
strCurOutput.Replace("&","!!!AMPAMP!!!");
char* result = reg.GetReplaceString(strCurOutput.c_str());
if (result && strlen(result))
{
CStdString strResult(result);
strResult.Replace("!!!AMPAMP!!!","&");
Clean(strResult);
ReplaceBuffers(strResult);
if (iCompare > -1)
{
CStdString strResultNoCase = strResult;
strResultNoCase.ToLower();
if (strResultNoCase.Find(m_param[iCompare-1]) != -1)
dest += strResult;
}
else
dest += strResult;
free(result);
}
if (bRepeat && iLen > 0)
{
curInput.erase(0,i+iLen>(int)curInput.size()?curInput.size():i+iLen);
i = reg.RegFind(curInput.c_str());
}
else
i = -1;
}
}
}
void CScraperParser::ParseNext(TiXmlElement* element)
{
TiXmlElement* pReg = element;
while (pReg)
{
TiXmlElement* pChildReg = pReg->FirstChildElement("RegExp");
if (pChildReg)
ParseNext(pChildReg);
else
{
TiXmlElement* pChildReg = pReg->FirstChildElement("clear");
if (pChildReg)
ParseNext(pChildReg);
}
int iDest = 1;
bool bAppend = false;
const char* szDest = pReg->Attribute("dest");
if (szDest)
if (strlen(szDest))
{
if (szDest[strlen(szDest)-1] == '+')
bAppend = true;
iDest = atoi(szDest);
}
const char *szInput = pReg->Attribute("input");
CStdString strInput;
if (szInput)
{
strInput = szInput;
ReplaceBuffers(strInput);
}
else
strInput = m_param[0];
const char* szConditional = pReg->Attribute("conditional");
bool bExecute = true;
if (szConditional)
{
bool bInverse=false;
if (szConditional[0] == '!')
{
bInverse = true;
szConditional++;
}
CStdString strSetting;
if (m_scraper && m_scraper->HasSettings())
strSetting = m_scraper->GetSetting(szConditional);
bExecute = bInverse != strSetting.Equals("true");
}
if (bExecute)
{
if (iDest-1 < MAX_SCRAPER_BUFFERS && iDest-1 > -1)
ParseExpression(strInput, m_param[iDest-1],pReg,bAppend);
else
CLog::Log(LOGERROR,"CScraperParser::ParseNext: destination buffer "
"out of bounds, skipping expression");
}
pReg = pReg->NextSiblingElement("RegExp");
}
}
const CStdString CScraperParser::Parse(const CStdString& strTag,
CScraper* scraper)
{
TiXmlElement* pChildElement = m_pRootElement->FirstChildElement(strTag.c_str());
if(pChildElement == NULL)
{
CLog::Log(LOGERROR,"%s: Could not find scraper function %s",__FUNCTION__,strTag.c_str());
return "";
}
int iResult = 1; // default to param 1
pChildElement->QueryIntAttribute("dest",&iResult);
TiXmlElement* pChildStart = pChildElement->FirstChildElement("RegExp");
m_scraper = scraper;
ParseNext(pChildStart);
CStdString tmp = m_param[iResult-1];
const char* szClearBuffers = pChildElement->Attribute("clearbuffers");
if (!szClearBuffers || stricmp(szClearBuffers,"no") != 0)
ClearBuffers();
return tmp;
}
void CScraperParser::Clean(CStdString& strDirty)
{
int i=0;
CStdString strBuffer;
while ((i=strDirty.Find("!!!CLEAN!!!",i)) != -1)
{
int i2;
if ((i2=strDirty.Find("!!!CLEAN!!!",i+11)) != -1)
{
strBuffer = strDirty.substr(i+11,i2-i-11);
CStdString strConverted(strBuffer);
HTML::CHTMLUtil::RemoveTags(strConverted);
RemoveWhiteSpace(strConverted);
strDirty.erase(i,i2-i+11);
strDirty.Insert(i,strConverted);
i += strConverted.size();
}
else
break;
}
i=0;
while ((i=strDirty.Find("!!!TRIM!!!",i)) != -1)
{
int i2;
if ((i2=strDirty.Find("!!!TRIM!!!",i+10)) != -1)
{
strBuffer = strDirty.substr(i+10,i2-i-10);
RemoveWhiteSpace(strBuffer);
strDirty.erase(i,i2-i+10);
strDirty.Insert(i,strBuffer);
i += strBuffer.size();
}
else
break;
}
i=0;
while ((i=strDirty.Find("!!!FIXCHARS!!!",i)) != -1)
{
int i2;
if ((i2=strDirty.Find("!!!FIXCHARS!!!",i+14)) != -1)
{
strBuffer = strDirty.substr(i+14,i2-i-14);
CStdStringW wbuffer;
g_charsetConverter.toW(strBuffer,wbuffer,GetSearchStringEncoding());
CStdStringW wConverted;
HTML::CHTMLUtil::ConvertHTMLToW(wbuffer,wConverted);
g_charsetConverter.fromW(wConverted,strBuffer,GetSearchStringEncoding());
RemoveWhiteSpace(strBuffer);
strDirty.erase(i,i2-i+14);
strDirty.Insert(i,strBuffer);
i += strBuffer.size();
}
else
break;
}
i=0;
while ((i=strDirty.Find("!!!ENCODE!!!",i)) != -1)
{
int i2;
if ((i2=strDirty.Find("!!!ENCODE!!!",i+12)) != -1)
{
strBuffer = strDirty.substr(i+12,i2-i-12);
CURL::Encode(strBuffer);
strDirty.erase(i,i2-i+12);
strDirty.Insert(i,strBuffer);
i += strBuffer.size();
}
else
break;
}
}
void CScraperParser::RemoveWhiteSpace(CStdString &string)
{
string.TrimLeft(" \t\r\n");
string.TrimRight(" \t\r\n");
}
void CScraperParser::ClearBuffers()
{
//clear all m_param strings
for (int i=0;i<MAX_SCRAPER_BUFFERS;++i)
m_param[i].clear();
}
void CScraperParser::GetBufferParams(bool* result, const char* attribute, bool defvalue)
{
for (int iBuf=0;iBuf<MAX_SCRAPER_BUFFERS;++iBuf)
result[iBuf] = defvalue;;
if (attribute)
{
vector<CStdString> vecBufs;
CUtil::Tokenize(attribute,vecBufs,",");
for (size_t nToken=0; nToken < vecBufs.size(); nToken++)
{
int index = atoi(vecBufs[nToken].c_str())-1;
if (index < MAX_SCRAPER_BUFFERS)
result[index] = !defvalue;
}
}
}
void CScraperParser::InsertToken(CStdString& strOutput, int buf, const char* token)
{
char temp[4];
sprintf(temp,"\\%i",buf);
int i2=0;
while ((i2 = strOutput.Find(temp,i2)) != -1)
{
strOutput.Insert(i2,token);
i2 += strlen(token);
strOutput.Insert(i2+strlen(temp),token);
i2 += strlen(temp);
}
}
void CScraperParser::AddDocument(const TiXmlDocument* doc)
{
const TiXmlNode* node = doc->RootElement()->FirstChild();
while (node)
{
m_pRootElement->InsertEndChild(*node);
node = node->NextSibling();
}
}
| chris-magic/xbmc_dualaudio_pvr | xbmc/utils/ScraperParser.cpp | C++ | gpl-2.0 | 14,169 |
<?php
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* The ProxyHandler class does the actual proxy'ing work. it deals both with
* GET and POST based input, and peforms a request based on the input, headers and
* httpmethod params.
*
*/
class ProxyHandler extends ProxyBase {
/**
* Fetches the content and returns it as-is using the headers as returned
* by the remote host.
*
* @param string $url the url to retrieve
*/
public function fetch($url) {
// TODO: Check to see if we can just use MakeRequestOptions::fromCurrentRequest
$st = isset($_GET['st']) ? $_GET['st'] : (isset($_POST['st']) ? $_POST['st'] : false);
$body = isset($_GET['postData']) ? $_GET['postData'] : (isset($_POST['postData']) ? $_POST['postData'] : false);
$authz = isset($_GET['authz']) ? $_GET['authz'] : (isset($_POST['authz']) ? $_POST['authz'] : null);
$headers = isset($_GET['headers']) ? $_GET['headers'] : (isset($_POST['headers']) ? $_POST['headers'] : null);
$params = new MakeRequestOptions($url);
$params->setSecurityTokenString($st)
->setAuthz($authz)
->setRequestBody($body)
->setHttpMethod('GET')
->setFormEncodedRequestHeaders($headers)
->setNoCache($this->context->getIgnoreCache());
$result = $this->makeRequest->fetch($this->context, $params);
$httpCode = (int)$result->getHttpCode();
$cleanedResponseHeaders = $this->makeRequest->cleanResponseHeaders($result->getResponseHeaders());
$isShockwaveFlash = false;
foreach ($cleanedResponseHeaders as $key => $val) {
header("$key: $val", true);
if (strtoupper($key) == 'CONTENT-TYPE' && strtolower($val) == 'application/x-shockwave-flash') {
// We're skipping the content disposition header for flash due to an issue with Flash player 10
// This does make some sites a higher value phishing target, but this can be mitigated by
// additional referer checks.
$isShockwaveFlash = true;
}
}
if (! $isShockwaveFlash && !Config::get('debug')) {
header('Content-Disposition: attachment;filename=p.txt');
}
$lastModified = $result->getResponseHeader('Last-Modified') != null ? $result->getResponseHeader('Last-Modified') : gmdate('D, d M Y H:i:s', $result->getCreated()) . ' GMT';
$notModified = false;
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified && ! isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
$if_modified_since = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
// Use the request's Last-Modified, otherwise fall back on our internal time keeping (the time the request was created)
$lastModified = strtotime($lastModified);
if ($lastModified <= $if_modified_since) {
$notModified = true;
}
}
if ($httpCode == 200) {
// only set caching headers if the result was 'OK'
$this->setCachingHeaders($lastModified);
// was the &gadget=<gadget url> specified in the request? if so parse it and check the rewrite settings
if (isset($_GET['gadget'])) {
$this->rewriteContent($_GET['gadget'], $result);
}
}
// If the cached file time is within the refreshInterval params value, return not-modified
if ($notModified) {
header('HTTP/1.0 304 Not Modified', true);
header('Content-Length: 0', true);
} else {
header("HTTP/1.1 $httpCode ".$result->getHttpCodeMsg());
// then echo the content
echo $result->getResponseContent();
}
}
private function rewriteContent($gadgetUrl, RemoteContentRequest &$result) {
try {
// At the moment we're only able to rewrite CSS files, so check the content type and/or the file extension before rewriting
$headers = $result->getResponseHeaders();
$isCss = false;
if (isset($headers['Content-Type']) && strtolower($headers['Content-Type'] == 'text/csss')) {
$isCss = true;
} else {
$ext = substr($_GET['url'], strrpos($_GET['url'], '.') + 1);
$isCss = strtolower($ext) == 'css';
}
if ($isCss) {
$gadget = $this->createGadget($gadgetUrl);
$rewrite = $gadget->gadgetSpec->rewrite;
if (is_array($rewrite)) {
$contentRewriter = new ContentRewriter($this->context, $gadget);
$result->setResponseContent($contentRewriter->rewriteCSS($result->getResponseContent()));
}
}
} catch (Exception $e) {
// ignore, not being able to rewrite anything isn't fatal
}
}
/**
* Uses the GadgetFactory to instrance the specified gadget
*
* @param string $gadgetUrl
*/
private function createGadget($gadgetUrl) {
// Only include these files if appropiate, else it would slow down the entire proxy way to much
require_once 'src/gadgets/GadgetSpecParser.php';
require_once 'src/gadgets/GadgetBlacklist.php';
require_once 'src/gadgets/sample/BasicGadgetBlacklist.php';
require_once 'src/gadgets/GadgetContext.php';
require_once 'src/gadgets/GadgetFactory.php';
require_once 'src/gadgets/GadgetSpec.php';
require_once 'src/gadgets/Gadget.php';
require_once 'src/gadgets/GadgetException.php';
require_once 'src/gadgets/rewrite/GadgetRewriter.php';
require_once 'src/gadgets/rewrite/DomRewriter.php';
require_once 'src/gadgets/rewrite/ContentRewriter.php';
// make sure our context returns the gadget url and not the proxied document url
$this->context->setUrl($gadgetUrl);
// and create & return the gadget
$factoryClass = Config::get('gadget_factory_class');
$gadgetSpecFactory = new $factoryClass($this->context, null);
$gadget = $gadgetSpecFactory->createGadget();
return $gadget;
}
}
| ROLE/widget-store | src/main/drupal/sites/all/libraries/shindig2.5beta/src/gadgets/ProxyHandler.php | PHP | gpl-2.0 | 6,462 |
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2016 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#include "ProfilePasswordDialog.hpp"
#include "TextEntry.hpp"
#include "Message.hpp"
#include "Error.hpp"
#include "Profile/Map.hpp"
#include "Profile/File.hpp"
#include "Profile/ProfileKeys.hpp"
#include "Language/Language.hpp"
#include "OS/Path.hpp"
#include "Util/StringAPI.hxx"
TriState
ProfileFileHasPassword(Path path)
{
ProfileMap map;
try {
Profile::LoadFile(map, path);
} catch (...) {
return TriState::UNKNOWN;
}
return map.Exists(ProfileKeys::Password)
? TriState::TRUE
: TriState::FALSE;
}
ProfilePasswordResult
CheckProfilePassword(const ProfileMap &map)
{
/* oh no, profile passwords are not truly secure! */
BasicStringBuffer<TCHAR, 80> profile_password;
if (!map.Get(ProfileKeys::Password, profile_password))
/* not password protected */
return ProfilePasswordResult::UNPROTECTED;
BasicStringBuffer<TCHAR, 80> user_password;
user_password.clear();
if (!TextEntryDialog(user_password, _("Enter your password")))
return ProfilePasswordResult::CANCEL;
return StringIsEqualIgnoreCase(profile_password, user_password)
? ProfilePasswordResult::MATCH
: ProfilePasswordResult::MISMATCH;
}
ProfilePasswordResult
CheckProfileFilePassword(Path path)
{
ProfileMap map;
Profile::LoadFile(map, path);
return CheckProfilePassword(map);
}
bool
CheckProfilePasswordResult(ProfilePasswordResult result)
{
switch (result) {
case ProfilePasswordResult::UNPROTECTED:
case ProfilePasswordResult::MATCH:
return true;
case ProfilePasswordResult::MISMATCH:
ShowMessageBox(_("Wrong password."), _("Password"), MB_OK);
return false;
case ProfilePasswordResult::CANCEL:
return false;
}
gcc_unreachable();
}
bool
SetProfilePasswordDialog(ProfileMap &map)
{
BasicStringBuffer<TCHAR, 80> new_password;
new_password.clear();
if (!TextEntryDialog(new_password, _("Enter a new password")))
return false;
if (new_password.empty())
map.erase(ProfileKeys::Password);
else
map.Set(ProfileKeys::Password, new_password);
return true;
}
| fb/XCSoar | src/Dialogs/ProfilePasswordDialog.cpp | C++ | gpl-2.0 | 2,951 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.distribution;
import org.apache.commons.math3.exception.NumberIsTooLargeException;
import org.junit.Assert;
import org.junit.Test;
/**
* Test cases for UniformRealDistribution. See class javadoc for
* {@link RealDistributionAbstractTest} for further details.
*/
public class UniformRealDistributionTest extends RealDistributionAbstractTest {
// --- Override tolerance -------------------------------------------------
@Override
public void setUp() throws Exception {
super.setUp();
setTolerance(1e-4);
}
//--- Implementations for abstract methods --------------------------------
/** Creates the default uniform real distribution instance to use in tests. */
@Override
public UniformRealDistribution makeDistribution() {
return new UniformRealDistribution(-0.5, 1.25);
}
/** Creates the default cumulative probability distribution test input values */
@Override
public double[] makeCumulativeTestPoints() {
return new double[] {-0.5001, -0.5, -0.4999, -0.25, -0.0001, 0.0,
0.0001, 0.25, 1.0, 1.2499, 1.25, 1.2501};
}
/** Creates the default cumulative probability density test expected values */
@Override
public double[] makeCumulativeTestValues() {
return new double[] {0.0, 0.0, 0.0001, 0.25/1.75, 0.4999/1.75,
0.5/1.75, 0.5001/1.75, 0.75/1.75, 1.5/1.75,
1.7499/1.75, 1.0, 1.0};
}
/** Creates the default probability density test expected values */
@Override
public double[] makeDensityTestValues() {
double d = 1 / 1.75;
return new double[] {0, d, d, d, d, d, d, d, d, d, d, 0};
}
//--- Additional test cases -----------------------------------------------
/** Test lower bound getter. */
@Test
public void testGetLowerBound() {
UniformRealDistribution distribution = makeDistribution();
Assert.assertEquals(-0.5, distribution.getSupportLowerBound(), 0);
}
/** Test upper bound getter. */
@Test
public void testGetUpperBound() {
UniformRealDistribution distribution = makeDistribution();
Assert.assertEquals(1.25, distribution.getSupportUpperBound(), 0);
}
/** Test pre-condition for equal lower/upper bound. */
@Test(expected=NumberIsTooLargeException.class)
public void testPreconditions1() {
new UniformRealDistribution(0, 0);
}
/** Test pre-condition for lower bound larger than upper bound. */
@Test(expected=NumberIsTooLargeException.class)
public void testPreconditions2() {
new UniformRealDistribution(1, 0);
}
/** Test mean/variance. */
@Test
public void testMeanVariance() {
UniformRealDistribution dist;
dist = new UniformRealDistribution(0, 1);
Assert.assertEquals(dist.getNumericalMean(), 0.5, 0);
Assert.assertEquals(dist.getNumericalVariance(), 1/12.0, 0);
dist = new UniformRealDistribution(-1.5, 0.6);
Assert.assertEquals(dist.getNumericalMean(), -0.45, 0);
Assert.assertEquals(dist.getNumericalVariance(), 0.3675, 0);
dist = new UniformRealDistribution(-0.5, 1.25);
Assert.assertEquals(dist.getNumericalMean(), 0.375, 0);
Assert.assertEquals(dist.getNumericalVariance(), 0.2552083333333333, 0);
}
}
| SpoonLabs/astor | examples/math_32/src/test/java/org/apache/commons/math3/distribution/UniformRealDistributionTest.java | Java | gpl-2.0 | 4,218 |
<?php
/**
* English language file
*
* @author Arno Welzel <himself@arnowelzel.de>
*/
// custom language strings for the plugin
$lang['getflash'] = 'If <a href="http://www.macromedia.com/go/getflashplayer">Flash</a> is installed, you can watch a video inside this web page.';
//Setup VIM: ex: et ts=2 enc=utf-8 : | jfons9/ateneu | rw_html/ewikiform/lib/plugins/flashplayer/lang/en/lang.php | PHP | gpl-2.0 | 323 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package domen;
import java.io.Serializable;
/**
*
* @author student1
*/
public class Adresa implements Serializable{
private String ulica;
private String broj;
private Mesto mesto;
public Adresa(String ulica, String broj, Mesto mesto) {
this.ulica = ulica;
this.broj = broj;
this.mesto = mesto;
}
public Adresa() {
}
public String getUlica() {
return ulica;
}
public void setUlica(String ulica) {
this.ulica = ulica;
}
public String getBroj() {
return broj;
}
public void setBroj(String broj) {
this.broj = broj;
}
public Mesto getMesto() {
return mesto;
}
public void setMesto(Mesto mesto) {
this.mesto = mesto;
}
@Override
public String toString() {
return ulica + " " + broj + ", " + mesto;
}
@Override
public boolean equals(Object obj) {
Adresa a = (Adresa) obj;
if (ulica.equals(a.ulica) && broj.equals(a.broj) && mesto.equals(a.mesto)) {
return true;
}
return false;
}
}
| PSIXO/softverski-proces | Zajednicki/src/domen/Adresa.java | Java | gpl-2.0 | 1,221 |
<?php
/**
*
* Lightbox extension for the phpBB Forum Software package.
* [Japanese] Translation by momo-i.
*
* @copyright (c) 2015 Matt Friedman
* @license GNU General Public License, version 2 (GPL-2.0)
*
*/
/**
* DO NOT CHANGE
*/
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
$lang = array_merge($lang, array(
'LIGHTBOX_SETTINGS' => 'Lightbox 設定',
'LIGHTBOX_MAX_WIDTH' => '最大画像幅(ピクセル)',
'LIGHTBOX_MAX_WIDTH_EXPLAIN' => 'この幅を超える画像はリサイズされLightboxエフェクトを使用して引き伸ばすことが出来ます。この値を0に設定すると画像のリサイズを無効にします。',
'LIGHTBOX_MAX_WIDTH_APPEND' => '添付ファイルの設定に基づいて勧告: %spx',
'LIGHTBOX_MAX_HEIGHT' => 'Maximum image height',
'LIGHTBOX_MAX_HEIGHT_EXPLAIN' => 'Images that exceed this height will be resized and can be enlarged using the Lightbox effect. Set this value to 0 to disable Lightbox image resizing by height.',
'LIGHTBOX_ALL_IMAGES' => 'Include all images in Lightbox effect',
'LIGHTBOX_ALL_IMAGES_EXPLAIN' => 'With this setting enabled, all posted images can be opened in the Lightbox effect even if they are not being resized.',
'LIGHTBOX_GALLERY' => 'ギャラリーモードを許可',
'LIGHTBOX_GALLERY_EXPLAIN' => 'Lightboxエフェクトを使用するページの全てのリサイズされた画像の間で簡単なナビゲーションを許可します。',
'LIGHTBOX_GALLERY_ALL' => 'All resized images on page',
'LIGHTBOX_GALLERY_POSTS' => 'All resized images per post',
'LIGHTBOX_SIGNATURES' => '署名画像のリサイズ',
'LIGHTBOX_SIGNATURES_EXPLAIN' => '署名でリサイズされた画像の使用を許可します。',
'LIGHTBOX_IMG_TITLES' => '画像のファイル名を表示',
'LIGHTBOX_IMG_TITLES_EXPLAIN' => '画像名はLightboxエフェクトの見出しとして表示されます。',
));
| Galixte/lightbox | language/ja/lightbox.php | PHP | gpl-2.0 | 1,996 |
var searchData=
[
['key',['key',['../classJson_1_1ValueIteratorBase.html#aa2ff5e79fc96acd4c3cd288e92614fc7',1,'Json::ValueIteratorBase::key() const '],['../classJson_1_1ValueIteratorBase.html#aa2ff5e79fc96acd4c3cd288e92614fc7',1,'Json::ValueIteratorBase::key() const ']]]
];
| bmob/BmobCocos2d-x | html/search/functions_9.js | JavaScript | gpl-2.0 | 277 |
<?php
/*******************************************************************************
Copyright 2016 Whole Foods Co-op
This file is part of IT CORE.
IT CORE is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
IT CORE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
in the file license.txt along with IT CORE; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*********************************************************************************/
include(dirname(__FILE__).'/../../../config.php');
if (!class_exists('FannieAPI')) {
include_once($FANNIE_ROOT.'classlib2.0/FannieAPI.php');
}
class OsVarianceReport extends FannieReportPage
{
// 10Nov13 EL Added title and header
protected $title = 'Over/Short Variance Report';
protected $header = 'Over/Short Variance Report';
protected $auth_classes = array('overshorts');
public $page_set = 'Plugin :: Over/Shorts';
public $description = '[Variance Report] shows over/short variance info over time';
public $report_set = 'Finance';
protected $report_headers = array('Date', 'Lane', 'POS Total', 'Count Total', 'Variance', 'Emp#', 'Name', 'Share');
protected $report_cache = 'day';
protected $required_fields = array('date1', 'date2');
public function fetch_report_data()
{
try {
$date1 = $this->form->date1;
$date2 = $this->form->date2;
$store = $this->form->store;
$mode = $this->form->mode;
} catch (Exception $ex) {
return array();
}
return $mode == 'Details' ? $this->getDetails($date1, $date2, $store) : $this->getTotals($date1, $date2, $store);
}
private function getTotals($date1, $date2, $store)
{
$settings = $this->config->get('PLUGIN_SETTINGS');
$dbc = $this->connection;
$dbc->selectDB($settings['OverShortDatabase']);
$dlog = DTransactionsModel::selectDlog($date1, $date2);
$osP = $dbc->prepare("
SELECT SUM(amt) AS ttl
FROM dailyCounts
WHERE date BETWEEN ? AND ?
AND tender_type IN ('CA', 'SCA')
AND emp_no=?
AND storeID=?");
$transP = $dbc->prepare("
SELECT YEAR(tdate) AS year,
MONTH(tdate) AS month,
DAY(tdate) AS day,
d.register_no,
d.emp_no,
e.FirstName,
e.LastName,
SUM(-1*total) AS ttl
FROM {$dlog} AS d
LEFT JOIN " . $this->config->get('OP_DB') . $dbc->sep() . "employees AS e
ON d.emp_no=e.emp_no
WHERE d.tdate BETWEEN ? AND ?
AND trans_type='T'
AND trans_subtype='CA'
AND store_id=?
AND total <> 0
GROUP BY YEAR(tdate),
MONTH(tdate),
DAY(tdate),
d.register_no,
d.emp_no,
e.FirstName,
e.LastName");
$raw = array();
$totals = array();
$transR = $dbc->execute($transP, array($date1 . ' 00:00:00', $date2 . ' 23:59:59', $store));
// get date-register-employee data
while ($transW = $dbc->fetchRow($transR)) {
$date = date('Y-m-d', mktime(0,0,0, $transW['month'], $transW['day'], $transW['year']));
$key = $date . '-' . $transW['register_no'];
$raw[] = array(
'date' => $date,
'reg' => $transW['register_no'],
'emp' => $transW['emp_no'],
'name' => $transW['FirstName'] . ' ' . $transW['LastName'],
'key' => $key,
);
if (!isset($totals[$key])) {
$totals[$key] = 0;
}
$totals[$key] += $transW['ttl'];
}
// count how many employees were in a drawer each day
for ($i=0; $i<count($raw); $i++) {
$count = 0;
for ($j=0; $j<count($raw); $j++) {
if ($raw[$i]['key'] == $raw[$j]['key']) {
$count++;
}
}
$raw[$i]['count'] = $count;
}
// find counted amounts for each drawer
// avoid re-querying when possible
for ($i=0; $i<count($raw); $i++) {
$date = $raw[$i]['date'];
$key = $raw[$i]['key'];
if (!isset($raw[$i]['actual'])) {
$actual = $dbc->getValue($osP, array($date, $date, $raw[$i]['reg'], $store));
$raw[$i]['actual'] = $actual;
for ($j=$i+1; $j<count($raw); $j++) {
if ($raw[$i]['key'] == $raw[$j]['key']) {
$raw[$j]['actual'] = $actual;
}
}
}
}
$data = array();
foreach ($raw as $row) {
$emp = $row['emp'];
if (!isset($data[$emp])) {
$data[$emp] = array($emp, $row['name'], 0);
}
$key = $row['key'];
$variance = $totals[$key] - $row['actual'];
if ($row['actual'] == 0) {
$variance = 0;
}
$avg = $variance / $row['count'];
$data[$emp][2] += $avg;
if ($emp == 1) print_r($row);
}
$ret = array();
foreach ($data as $emp => $row) {
$row[2] = sprintf('%.2f', $row[2]);
$ret[] = $row;
}
return $ret;
}
public function calculate_footers($data)
{
if (count($data[0]) == 3) {
$this->report_headers = array('Emp#', 'Name', 'Total Variance Share');
$sum = array_reduce($data, function($c, $i) { return $c + $i[2]; });
return array('Total', '', round($sum, 2));
}
return array();
}
private function getDetails($date1, $date2, $store)
{
$settings = $this->config->get('PLUGIN_SETTINGS');
$dbc = $this->connection;
$dbc->selectDB($settings['OverShortDatabase']);
$osP = $dbc->prepare('
SELECT emp_no,
date,
storeID,
SUM(amt) AS ttl
FROM dailyCounts
WHERE date BETWEEN ? AND ?
AND tender_type IN (\'CA\', \'SCA\')
AND storeID=?
GROUP BY emp_no,
date,
storeID');
$osR = $dbc->execute($osP, array($date1, $date2, $store));
$dlog = DTransactionsModel::selectDlog($date1, $date2);
$transP = $dbc->prepare("
SELECT SUM(-1*d.total) AS ttl,
d.emp_no,
e.LastName,
e.FirstName
FROM {$dlog} AS d
LEFT JOIN " . $this->config->get('OP_DB') . $dbc->sep() . "employees AS e
ON d.emp_no=e.emp_no
WHERE d.tdate BETWEEN ? AND ?
AND d.trans_type='T'
AND d.trans_subtype='CA'
AND d.store_id=?
AND d.register_no=?
AND d.upc='0'
AND total <> 0
GROUP BY d.emp_no,
e.LastName,
e.FirstName");
$data = array();
while ($osW = $dbc->fetchRow($osR)) {
$args = array(
$osW['date'] . ' 00:00:00',
$osW['date'] . ' 23:59:59',
$osW['storeID'],
$osW['emp_no'],
);
$ttl = 0;
$emps = array();
$transR = $dbc->execute($transP, $args);
while ($transW = $dbc->fetchRow($transR)) {
$ttl += $transW['ttl'];
$emps[] = array(
$transW['emp_no'],
$transW['FirstName'] . ' ' . $transW['LastName'],
);
}
$var = $osW['ttl'] - $ttl;
foreach ($emps as $e) {
$data[] = array(
$osW['date'],
$osW['emp_no'],
sprintf('%.2f', $ttl),
sprintf('%.2f', $osW['ttl']),
sprintf('%.2f', $var),
$e[0],
$e[1],
sprintf('%.2f', $var/count($emps)),
);
}
}
return $data;
}
public function form_content()
{
$dates = FormLib::standardDateFields();
$stores = FormLib::storePicker();
return <<<HTML
<form method="get">
<div class="col-sm-5">
<div class="form-group">
<label>Show</label>
<select name="mode" class="form-control">
<option>Cashier Totals</option>
<option>Details</option>
</select>
</div>
<div class="form-group">
<label>Store</label>
{$stores['html']}
</div>
<div class="form-group">
<button class="btn btn-default btn-core">Submit</button>
</div>
</div>
{$dates}
</form>
HTML;
}
}
FannieDispatch::conditionalExec();
| flathat/IS4C | fannie/modules/plugins2.0/OverShortTools/OsVarianceReport.php | PHP | gpl-2.0 | 9,678 |
<?php
/*------------------------------------------------------------------------------
$Id: cc.php 1160 2005-08-16 22:25:01Z hhgag $
XTC-CC - Contribution for XT-Commerce http://www.xt-commerce.com
modified by http://www.netz-designer.de
Copyright (c) 2003 netz-designer
-----------------------------------------------------------------------------
based on:
$Id: cc.php 1160 2005-08-16 22:25:01Z hhgag $
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2003 osCommerce
Released under the GNU General Public License
------------------------------------------------------------------------------*/
// include needed functions
require_once (DIR_FS_INC.'xtc_php_mail.inc.php');
require_once (DIR_FS_INC.'xtc_validate_email.inc.php');
class cc {
var $code, $title, $description, $enabled;
// class constructor
function cc() {
global $order, $xtPrice;
$this->code = 'cc';
$this->title = MODULE_PAYMENT_CC_TEXT_TITLE;
$this->description = MODULE_PAYMENT_CC_TEXT_DESCRIPTION;
$this->sort_order = MODULE_PAYMENT_CC_SORT_ORDER;
$this->enabled = ((MODULE_PAYMENT_CC_STATUS == 'True') ? true : false);
$this->info = MODULE_PAYMENT_CC_TEXT_INFO;
$this->accepted="";
if ((int) MODULE_PAYMENT_CC_ORDER_STATUS_ID > 0) {
$this->order_status = MODULE_PAYMENT_CC_ORDER_STATUS_ID;
}
if (is_object($order))
$this->update_status();
// if ($xtPrice->xtcRemoveCurr($_SESSION['cart']->show_total())>600) $this->enabled=false;
}
// class methods
function update_status() {
global $order;
if (($this->enabled == true) && ((int) MODULE_PAYMENT_CC_ZONE > 0)) {
$check_flag = false;
$check_query = xtc_db_query("select zone_id from ".TABLE_ZONES_TO_GEO_ZONES." where geo_zone_id = '".MODULE_PAYMENT_CC_ZONE."' and zone_country_id = '".$order->billing['country']['id']."' order by zone_id");
while ($check = xtc_db_fetch_array($check_query)) {
if ($check['zone_id'] < 1) {
$check_flag = true;
break;
}
elseif ($check['zone_id'] == $order->billing['zone_id']) {
$check_flag = true;
break;
}
}
if ($check_flag == false) {
$this->enabled = false;
}
}
}
function javascript_validation() {
if (strtolower(USE_CC_CVV) == 'true') {
$js = ' if (payment_value == "'.$this->code.'") {'."\n".' var cc_owner = document.getElementById("checkout_payment").cc_owner.value;'."\n".' var cc_number = document.getElementById("checkout_payment").cc_number.value;'."\n".' var cc_cvv = document.getElementById("checkout_payment").cc_cvv.value;'."\n".' if (cc_owner == "" || cc_owner.length < '.CC_OWNER_MIN_LENGTH.') {'."\n".' error_message = error_message + unescape("'.xtc_js_lang(MODULE_PAYMENT_CC_TEXT_JS_CC_OWNER).'");'."\n".' error = 1;'."\n".' }'."\n".' if (cc_number == "" || cc_number.length < '.CC_NUMBER_MIN_LENGTH.') {'."\n".' error_message = error_message + unescape("'.xtc_js_lang(MODULE_PAYMENT_CC_TEXT_JS_CC_NUMBER).'");'."\n".' error = 1;'."\n".' }'."\n".' if (cc_cvv == "" || cc_cvv.length <= 2) {'."\n".' error_message = error_message + unescape("'.xtc_js_lang(MODULE_PAYMENT_CC_TEXT_JS_CC_CVV).'");'."\n".' error = 1;'."\n".' }'."\n".' }'."\n";
return $js;
} else {
$js = ' if (payment_value == "'.$this->code.'") {'."\n".' var cc_owner = document.getElementById("checkout_payment").cc_owner.value;'."\n".' var cc_number = document.getElementById("checkout_payment").cc_number.value;'."\n".' if (cc_owner == "" || cc_owner.length < '.CC_OWNER_MIN_LENGTH.') {'."\n".' error_message = error_message + unescape("'.xtc_js_lang(MODULE_PAYMENT_CC_TEXT_JS_CC_OWNER).'");'."\n".' error = 1;'."\n".' }'."\n".' if (cc_number == "" || cc_number.length < '.CC_NUMBER_MIN_LENGTH.') {'."\n".' error_message = error_message + unescape("'.xtc_js_lang(MODULE_PAYMENT_CC_TEXT_JS_CC_NUMBER).'");'."\n".' error = 1;'."\n".' }'."\n".' }'."\n";
return $js;
}
}
function selection() {
global $order;
for ($i = 1; $i < 13; $i ++) {
$expires_month[] = array ('id' => sprintf('%02d', $i), 'text' => strftime('%B', mktime(0, 0, 0, $i, 1, 2000)));
}
$today = getdate();
for ($i = $today['year']; $i < $today['year'] + 10; $i ++) {
$expires_year[] = array ('id' => strftime('%y', mktime(0, 0, 0, 1, 1, $i)), 'text' => strftime('%Y', mktime(0, 0, 0, 1, 1, $i)));
}
for ($i = 1; $i < 13; $i ++) {
$start_month[] = array ('id' => sprintf('%02d', $i), 'text' => strftime('%B', mktime(0, 0, 0, $i, 1, 2000)));
}
$today = getdate();
for ($i = $today['year'] - 4; $i <= $today['year']; $i ++) {
$start_year[] = array ('id' => strftime('%y', mktime(0, 0, 0, 1, 1, $i)), 'text' => strftime('%Y', mktime(0, 0, 0, 1, 1, $i)));
}
$form_array = array ();
// Owner
$form_array = array_merge($form_array, array (array ('title' => MODULE_PAYMENT_CC_TEXT_CREDIT_CARD_OWNER, 'field' => xtc_draw_input_field('cc_owner', $order->billing['firstname'].' '.$order->billing['lastname']))));
// CC Number
$form_array = array_merge($form_array, array (array ('title' => MODULE_PAYMENT_CC_TEXT_CREDIT_CARD_NUMBER, 'field' => xtc_draw_input_field('cc_number'))));
// Startdate
if (strtolower(USE_CC_START) == 'true') {
$form_array = array_merge($form_array, array (array ('title' => MODULE_PAYMENT_CC_TEXT_CREDIT_CARD_START, 'field' => xtc_draw_pull_down_menu('cc_start_month', $start_month).' '.xtc_draw_pull_down_menu('cc_start_year', $start_year))));
}
// expire date
$form_array = array_merge($form_array, array (array ('title' => MODULE_PAYMENT_CC_TEXT_CREDIT_CARD_EXPIRES, 'field' => xtc_draw_pull_down_menu('cc_expires_month', $expires_month).' '.xtc_draw_pull_down_menu('cc_expires_year', $expires_year))));
// CVV
if (strtolower(USE_CC_CVV) == 'true') {
$form_array = array_merge($form_array, array (array ('title' => MODULE_PAYMENT_CC_TEXT_CREDIT_CARD_CVV.' '.'<a href="javascript:popupWindow(\''.xtc_href_link(FILENAME_POPUP_CVV, '', 'SSL').'\')">'.MODULE_PAYMENT_CC_TEXT_CVV_LINK.'</a>', 'field' => xtc_draw_input_field('cc_cvv', '', 'size=4 maxlength=4'))));
}
if (strtolower(USE_CC_ISS) == 'true') {
$form_array = array_merge($form_array, array (array ('title' => MODULE_PAYMENT_CC_TEXT_CREDIT_CARD_ISSUE, 'field' => xtc_draw_input_field('cc_issue', '', 'size=2 maxlength=2'))));
}
// cards
if (strtolower(MODULE_PAYMENT_CC_ACCEPT_VISA) == 'true')
$this->accepted .= xtc_image(DIR_WS_ICONS.'cc_visa.jpg');
if (strtolower(MODULE_PAYMENT_CC_ACCEPT_MASTERCARD) == 'true')
$this->accepted .= xtc_image(DIR_WS_ICONS.'cc_mastercard.jpg');
if (strtolower(MODULE_PAYMENT_CC_ACCEPT_AMERICANEXPRESS) == 'true')
$this->accepted .= xtc_image(DIR_WS_ICONS.'cc_amex.jpg');
if (strtolower(MODULE_PAYMENT_CC_ACCEPT_DINERSCLUB) == 'true')
$this->accepted .= xtc_image(DIR_WS_ICONS.'cc_diners.jpg');
if (strtolower(MODULE_PAYMENT_CC_ACCEPT_DISCOVERNOVUS) == 'true')
$this->accepted .= xtc_image(DIR_WS_ICONS.'cc_discover.jpg');
if (strtolower(MODULE_PAYMENT_CC_ACCEPT_JCB) == 'true')
$this->accepted .= xtc_image(DIR_WS_ICONS.'cc_jcb.jpg');
if (strtolower(MODULE_PAYMENT_CC_ACCEPT_OZBANKCARD) == 'true')
$this->accepted .='';
$form_array=array_merge(array(array('title'=>MODULE_PAYMENT_CC_ACCEPTED_CARDS,'field'=>$this->accepted)),$form_array);
$selection = array ('id' => $this->code, 'module' => $this->title, 'fields' => $form_array, 'description' => $this->info);
return $selection;
}
function pre_confirmation_check() {
include (DIR_WS_CLASSES.'cc_validation.php');
$cc_validation = new cc_validation();
$result = $cc_validation->validate($_POST['cc_number'], $_POST['cc_expires_month'], $_POST['cc_expires_year']);
$error = '';
switch ($result) {
case -1 :
$error = sprintf(TEXT_CCVAL_ERROR_UNKNOWN_CARD, substr($cc_validation->cc_number, 0, 4));
break;
case -2 :
case -3 :
case -4 :
$error = TEXT_CCVAL_ERROR_INVALID_DATE;
break;
case -5 :
$error = sprintf(TEXT_CCVAL_ERROR_NOT_ACCEPTED, substr($cc_validation->cc_type, 0, 10), substr($cc_validation->cc_type, 0, 10));
break;
case -6 :
$error = TEXT_CCVAL_ERROR_SHORT;
break;
case -7 :
$error = TEXT_CCVAL_ERROR_BLACKLIST;
break;
case -8 :
$cards = '';
if (strtolower(MODULE_PAYMENT_CC_ACCEPT_VISA) == 'true')
$cards .= ' Visa,';
if (strtolower(MODULE_PAYMENT_CC_ACCEPT_MASTERCARD) == 'true')
$cards .= ' Master Card,';
if (strtolower(MODULE_PAYMENT_CC_ACCEPT_AMERICANEXPRESS) == 'true')
$cards .= ' American Express,';
if (strtolower(MODULE_PAYMENT_CC_ACCEPT_DINERSCLUB) == 'true')
$cards .= ' Diners Club,';
if (strtolower(MODULE_PAYMENT_CC_ACCEPT_DISCOVERNOVUS) == 'true')
$cards .= ' Discover,';
if (strtolower(MODULE_PAYMENT_CC_ACCEPT_JCB) == 'true')
$cards .= ' JCB,';
if (strtolower(MODULE_PAYMENT_CC_ACCEPT_OZBANKCARD) == 'true')
$cards .= ' Australian BankCard,';
$error = sprintf(TEXT_CARD_NOT_ACZEPTED, $cc_validation->cc_type).$cards;
break;
case false :
$error = TEXT_CCVAL_ERROR_INVALID_NUMBER;
break;
}
if (($result == false) || ($result < 1)) {
$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode($error).'&cc_owner='.urlencode($_POST['cc_owner']).'&cc_expires_month='.$_POST['cc_expires_month'].'&cc_expires_year='.$_POST['cc_expires_year'];
xtc_redirect(xtc_href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
}
if (strtolower(USE_CC_CVV) != 'true') {
$this->cc_cvv = '000';
}
$this->cc_card_type = $cc_validation->cc_type;
$this->cc_card_number = $cc_validation->cc_number;
}
function confirmation() {
$_SESSION['ccard'] = array ('cc_owner' => $_POST['cc_owner'], 'cc_type' => $this->cc_card_type, 'cc_number' => $_POST['cc_number'], 'cc_start' => $_POST['cc_start_month'].$_POST['cc_start_year'], 'cc_expires' => $_POST['cc_expires_month'].$_POST['cc_expires_year'], 'cc_cvv' => $_POST['cc_cvv'], 'cc_issue' => $_POST['cc_issue']);
$form_array = array ();
// CC Owner
$form_array = array_merge($form_array, array (array ('title' => MODULE_PAYMENT_CC_TEXT_CREDIT_CARD_OWNER, 'field' => $_POST['cc_owner'])));
// CC Number
echo (strlen($_POST['cc_number']) - 8);
$form_array = array_merge($form_array, array (array ('title' => MODULE_PAYMENT_CC_TEXT_CREDIT_CARD_NUMBER, 'field' => substr($_POST['cc_number'], 0, 4).str_repeat('X', (strlen($_POST['cc_number']) - 8)).substr($_POST['cc_number'], -4))));
// startdate
if (strtolower(USE_CC_START) == 'true') {
$form_array = array_merge($form_array, array (array ('title' => MODULE_PAYMENT_CC_TEXT_CREDIT_CARD_START, 'field' => strftime('%B, %Y', mktime(0, 0, 0, $_POST['cc_start_month'], 1, $_POST['cc_start_year'])))));
}
//expire date
$form_array = array_merge($form_array, array (array ('title' => MODULE_PAYMENT_CC_TEXT_CREDIT_CARD_EXPIRES, 'field' => strftime('%B, %Y', mktime(0, 0, 0, $_POST['cc_expires_month'], 1, '20'.$_POST['cc_expires_year'])))));
// CCV
if (strtolower(USE_CC_CVV) == 'true') {
$form_array = array_merge($form_array, array (array ('title' => MODULE_PAYMENT_CC_TEXT_CREDIT_CARD_CVV, 'field' => $_POST['cc_cvv'])));
}
// ISS
if (strtolower(USE_CC_ISS) == 'true') {
$form_array = array_merge($form_array, array (array ('title' => MODULE_PAYMENT_CC_TEXT_CREDIT_CARD_ISSUE, 'field' => $_POST['cc_issue'])));
}
$confirmation = array ('title' => $this->title.': '.$this->cc_card_type, 'fields' => $form_array);
return $confirmation;
}
function process_button() {
$process_button_string = xtc_draw_hidden_field('cc_owner', $_POST['cc_owner']).xtc_draw_hidden_field('cc_expires', $_POST['cc_expires_month'].$_POST['cc_expires_year']).xtc_draw_hidden_field('cc_start', $_POST['cc_start_month'].$_POST['cc_start_year']).xtc_draw_hidden_field('cc_cvv', $_POST['cc_cvv']).xtc_draw_hidden_field('cc_issue', $_POST['cc_issue']).xtc_draw_hidden_field('cc_type', $this->cc_card_type).xtc_draw_hidden_field('cc_number', $this->cc_card_number);
return $process_button_string;
}
function before_process() {
global $order;
if ((defined('MODULE_PAYMENT_CC_EMAIL')) && (xtc_validate_email(MODULE_PAYMENT_CC_EMAIL))) {
$len = strlen($_POST['cc_number']);
$this->cc_middle = substr($_POST['cc_number'], 4, ($len -8));
$order->info['cc_number'] = substr($_POST['cc_number'], 0, 4).str_repeat('X', (strlen($_POST['cc_number']) - 8)).substr($_POST['cc_number'], -4);
$this->cc_cvv = $_POST['cc_cvv'];
$this->cc_start = $_POST['cc_start'];
$this->cc_issue = $_POST['cc_issue'];
}
}
function after_process() {
global $insert_id;
if ((defined('MODULE_PAYMENT_CC_EMAIL')) && (xtc_validate_email(MODULE_PAYMENT_CC_EMAIL))) {
$message = 'Order #'.$insert_id."\n\n".'Middle: '.$this->cc_middle."\n\n".'CVV:'.$this->cc_cvv."\n\n".'Start:'.$this->cc_start."\n\n".'ISSUE:'.$this->cc_issue."\n\n";
xtc_php_mail(STORE_OWNER_EMAIL_ADDRESS, STORE_OWNER, MODULE_PAYMENT_CC_EMAIL, '', '', STORE_OWNER_EMAIL_ADDRESS, STORE_OWNER, '', '', 'Extra Order Info: #'.$insert_id, nl2br($message), $message);
}
if ($this->order_status)
xtc_db_query("UPDATE ".TABLE_ORDERS." SET orders_status='".$this->order_status."' WHERE orders_id='".$insert_id."'");
}
function get_error() {
$error = array ('title' => MODULE_PAYMENT_CC_TEXT_ERROR, 'error' => stripslashes(urldecode($_GET['error'])));
return $error;
}
function check() {
if (!isset ($this->_check)) {
$check_query = xtc_db_query("select configuration_value from ".TABLE_CONFIGURATION." where configuration_key = 'MODULE_PAYMENT_CC_STATUS'");
$this->_check = xtc_db_num_rows($check_query);
}
return $this->_check;
}
function install() {
// BMC Changes Start
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_STATUS', 'True', '6', '0', 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('', 'MODULE_PAYMENT_CC_ALLOWED', '', '6', '0', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'CC_VAL', 'True', '6', '0', 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'CC_BLACK', 'True', '6', '0', 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'CC_ENC', 'True', '6', '0', 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('', 'MODULE_PAYMENT_CC_SORT_ORDER', '0', '6', '0' , now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, use_function, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_ZONE', '0', '6', '2', 'xtc_get_zone_class_title', 'xtc_cfg_pull_down_zone_classes(', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, use_function, date_added) values ('', 'MODULE_PAYMENT_CC_ORDER_STATUS_ID', '0', '6', '0', 'xtc_cfg_pull_down_order_statuses(', 'xtc_get_order_status_name', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'USE_CC_CVV', 'True', '6', '0', 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'USE_CC_ISS', 'True', '6', '0', 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'USE_CC_START', 'True', '6', '0', 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('', 'CC_CVV_MIN_LENGTH', '3', '6', '0', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('', 'MODULE_PAYMENT_CC_EMAIL', '', '6', '0', now())");
// added new configuration keys
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_ACCEPT_DINERSCLUB','False', 6, 0, 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_ACCEPT_AMERICANEXPRESS','False', 6, 0, 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_ACCEPT_CARTEBLANCHE','False', 6, 0, 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_ACCEPT_OZBANKCARD','False', 6, 0, 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_ACCEPT_DISCOVERNOVUS','False', 6, 0, 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_ACCEPT_DELTA','False', 6, 0, 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_ACCEPT_ELECTRON','False', 6, 0, 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_ACCEPT_MASTERCARD','False', 6, 0, 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_ACCEPT_SWITCH','False', 6, 0, 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_ACCEPT_SOLO','False', 6, 0, 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_ACCEPT_JCB','False', 6, 0, 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_ACCEPT_MAESTRO','False', 6, 0, 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
xtc_db_query("insert into ".TABLE_CONFIGURATION." (configuration_id, configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('', 'MODULE_PAYMENT_CC_ACCEPT_VISA','False', 6, 0, 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
// BMC Changes End
}
function remove() {
xtc_db_query("delete from ".TABLE_CONFIGURATION." where configuration_key in ('".implode("', '", $this->keys())."')");
}
function keys() {
return array ('MODULE_PAYMENT_CC_STATUS', 'MODULE_PAYMENT_CC_ALLOWED', 'USE_CC_CVV', 'USE_CC_ISS', 'USE_CC_START', 'CC_CVV_MIN_LENGTH', 'CC_ENC', 'CC_VAL', 'CC_BLACK', 'MODULE_PAYMENT_CC_EMAIL', 'MODULE_PAYMENT_CC_ZONE', 'MODULE_PAYMENT_CC_ORDER_STATUS_ID', 'MODULE_PAYMENT_CC_SORT_ORDER', 'MODULE_PAYMENT_CC_ACCEPT_DINERSCLUB', 'MODULE_PAYMENT_CC_ACCEPT_AMERICANEXPRESS', 'MODULE_PAYMENT_CC_ACCEPT_CARTEBLANCHE', 'MODULE_PAYMENT_CC_ACCEPT_OZBANKCARD', 'MODULE_PAYMENT_CC_ACCEPT_DISCOVERNOVUS', 'MODULE_PAYMENT_CC_ACCEPT_DELTA', 'MODULE_PAYMENT_CC_ACCEPT_ELECTRON', 'MODULE_PAYMENT_CC_ACCEPT_MASTERCARD', 'MODULE_PAYMENT_CC_ACCEPT_SWITCH', 'MODULE_PAYMENT_CC_ACCEPT_SOLO', 'MODULE_PAYMENT_CC_ACCEPT_JCB', 'MODULE_PAYMENT_CC_ACCEPT_MAESTRO', 'MODULE_PAYMENT_CC_ACCEPT_VISA');
}
}
?> | Soeldner/modified-inkl-bootstrap-by-karl | includes/modules/payment/cc.php | PHP | gpl-2.0 | 22,288 |
/*
* Copyright 2015 Fabrício Godoy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
Package web provides operations to help HTTP server implementation.
Chain
A Chain provides a function to chain HTTP handlers, also know as middlewares,
before a specified HTTP handler. A Chain is basically a slice of middlewares.
Header
A Header provides functions to help handle HTTP headers, both for reading from
client request and write to server response.
HeaderBuilder
A HeaderBuilder provides some pre-defined HTTP headers.
JSON
Provides a JSONRead and JSONWrite functions for easiest JSON communication, and
a JSONError struct which defines a format for JSON errors as defined by best
practices.
SessionStore
A SessionStore provides session tokens to uniquely identify an user session and
links it to specified data. Each token expires automatically if it is not used
after defined time.
*/
package web
| skarllot/magmanager | vendor/gopkg.in/raiqub/web.v0/doc.go | GO | gpl-2.0 | 1,424 |
<?php
defined('TYPO3_MODE') or die();
if (TYPO3_MODE === 'BE') {
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addModule(
'web',
'func',
'',
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($_EXTKEY) . 'mod1/',
array(
'script' => '_DISPATCH',
'access' => 'user,group',
'name' => 'web_func',
'labels' => array(
'tabs_images' => array(
'tab' => '../Resources/Public/Icons/module-func.png',
),
'll_ref' => 'LLL:EXT:lang/locallang_mod_web_func.xlf',
),
)
);
}
| janusnic/Portfolio | typo3_src-7.3.1/typo3/sysext/func/ext_tables.php | PHP | gpl-2.0 | 520 |
const thymeleaf = require('/lib/thymeleaf');
const dataUtils = require('/lib/data');
const portal = require('/lib/xp/portal');
const assetUrlCache = require('/lib/assetUrlCache');
const view = resolve('default.html');
function buildBodyClass(site, siteConfig, content, params, backgroundImage) {
let bodyClass = '';
if (backgroundImage) {
bodyClass += 'custom-background ';
}
if ((content._path == site._path) && dataUtils.isEmpty(params)) {
bodyClass += 'home blog ';
}
if (params.cat || params.tag || params.author) {
bodyClass += ' archive ';
}
if (content.type == app.name + ':post' || content.type == 'portal:page-template') {
bodyClass += 'single single-post single-format-standard ';
}
if (params.author) {
bodyClass += 'author '
}
return bodyClass;
}
function getPageItemClass(targetPath, currentContentPath) {
return targetPath == currentContentPath ? 'current_page_item' : 'page_item';
}
exports.get = function handleGet(request) {
const site = portal.getSite();
const siteConfig = portal.getSiteConfig();
dataUtils.deleteEmptyProperties(siteConfig);
const content = portal.getContent();
const dashedAppName = app.name.replace(/\./g, "-");
const siteCommon = site.x[dashedAppName].siteCommon;
const backgroundImage = siteCommon.backgroundImage;
const assetUrls = assetUrlCache.getAssetUrls(request.mode, request.branch);
const isFragment = content.type === 'portal:fragment';
const model = {
assetUrls: assetUrls,
title: site.displayName,
description: site.data.description,
bodyClass: buildBodyClass(site, siteConfig, content, request.params, backgroundImage),
mainRegion: isFragment ? null : content.page.regions['main'],
isFragment: isFragment,
siteUrl: portal.pageUrl({path: site._path}),
footerText: siteCommon.footerText ?
portal.processHtml({value: siteCommon.footerText}) :
null,
backgroundImageUrl: (backgroundImage) ?
portal.imageUrl({
id: backgroundImage,
scale: '(1,1)',
format: 'jpeg'
}) :
null,
headerStyle: request.mode == 'edit' ? 'position: absolute;' : null
};
return {
body: thymeleaf.render(view, model),
pageContributions: {
// Insert here instead of in the HTML view itself, because some parts add some of these as their own page contribution.
// This is the easiest way to prevent duplicates (which cause errors).
headEnd: [
`<script src="${assetUrls.jqueryJs}"></script>`,
`<script src="${assetUrls.superheroJs}"></script>`,
`<script src="${assetUrls.flexsliderJs}"></script>`,
]
}
}
};
| enonic/app-superhero-blog | src/main/resources/site/pages/default/default.js | JavaScript | gpl-2.0 | 2,889 |
/*
* Copyright (c) 2008--2012, The University of Sheffield. See the file
* COPYRIGHT.txt in the software or at http://gate.ac.uk/gate/COPYRIGHT.txt
*
* This file is part of GATE (see http://gate.ac.uk/), and is free
* software, licenced under the GNU Library General Public License,
* Version 2, June 1991 (in the distribution as file licence.html,
* and also available at http://gate.ac.uk/gate/licence.html).
*
* $Id: PMIDebugger.java 17718 2014-03-20 20:40:06Z adamfunk $
*/
package gate.termraider.gui;
import gate.termraider.bank.AbstractBank;
import gate.termraider.bank.PMIBank;
import gate.termraider.util.Term;
import gate.termraider.util.UnorderedTermPair;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
public class PMIDebugger extends JPanel {
private static final long serialVersionUID = 4515459904186726963L;
private JSplitPane splitPane;
private JTable termTable, pairTable;
private TableModel termTableModel, pairTableModel;
private JScrollPane termPane, pairPane;
public PMIDebugger(AbstractBank bank) {
this.setLayout(new BorderLayout());
if (bank instanceof PMIBank) {
this.populate((PMIBank) bank);
}
}
private void populate(PMIBank bank) {
JTextField countField = new JTextField("Term count = " + bank.getTotalCount()
+ "; Distinct terms = " + bank.getNbrDistinctTerms()
+ "; Pair count = " + bank.getTotalPairCount()
+ "; Distinct pairs = " + bank.getNbrDistinctPairs() );
this.add(countField, BorderLayout.NORTH);
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
termTableModel = new PDTermModel(bank);
pairTableModel = new PDPairModel(bank);
termTable = new JTable(termTableModel);
pairTable = new JTable(pairTableModel);
termTable.setAutoCreateRowSorter(true);
pairTable.setAutoCreateRowSorter(true);
termPane = new JScrollPane(termTable,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pairPane = new JScrollPane(pairTable,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
splitPane.setLeftComponent(termPane);
splitPane.setRightComponent(pairPane);
this.add(splitPane, BorderLayout.CENTER);
this.validate();
this.repaint();
}
}
class PDPairModel extends AbstractTableModel {
private static final long serialVersionUID = 4553799329984692710L;
private List<UnorderedTermPair> pairs;
private Map<UnorderedTermPair, Double> scores;
private PMIBank bank;
public PDPairModel(PMIBank bank) {
this.pairs = new ArrayList<UnorderedTermPair>(bank.getPairs());
this.scores = bank.getScores();
this.bank = bank;
}
public int getColumnCount() {
return 5;
}
public int getRowCount() {
return this.pairs.size();
}
public Object getValueAt(int row, int col) {
UnorderedTermPair pair = this.pairs.get(row);
if (col == 0) {
return pair.getTerm0().toString();
}
// implied else
if (col == 1) {
return pair.getTerm1().toString();
}
// implied else
if (col == 2) {
return bank.getPairCount(pair);
}
if (col == 3) {
return bank.getDocumentCount(pair);
}
// implied else
return this.scores.get(pair);
}
public Class<?> getColumnClass(int col) {
if (col < 2) {
return String.class;
}
// implied else
if (col < 4) {
return Integer.class;
}
// implied else
return Double.class;
}
public String getColumnName(int col) {
if (col < 2) {
return "Term";
}
// implied else
if (col == 2) {
return "Frequency";
}
if (col == 3) {
return "DocFrequency";
}
// implied else
return "Score";
}
}
class PDTermModel extends AbstractTableModel {
private static final long serialVersionUID = 2673610596047342256L;
private List<Term> terms;
private PMIBank bank;
public PDTermModel(PMIBank bank) {
this.terms = new ArrayList<Term>(bank.getTerms());
this.bank = bank;
}
public int getColumnCount() {
return 3;
}
public int getRowCount() {
return this.terms.size();
}
public Object getValueAt(int row, int col) {
Term term = this.terms.get(row);
if (col == 0) {
return term.toString();
}
// implied else
if (col == 1) {
return this.bank.getTermCount(term);
}
// implied else
return this.bank.getDocumentCount(term);
}
public Class<?> getColumnClass(int col) {
if (col == 0) {
return String.class;
}
// implied else
return Integer.class;
}
public String getColumnName(int col) {
if (col == 0) {
return "Term";
}
if (col == 1) {
return "Frequency";
}
return "DocFrequency";
}
}
| SONIAGroup/S.O.N.I.A. | GATE_Developer_8.0/plugins/TermRaider/src/gate/termraider/gui/PMIDebugger.java | Java | gpl-2.0 | 5,149 |
EasyBlog.module('responsive', function($) {
var module = this;
// $(selector).responsive({condition});
// $(selector).responsive([{condition1}, {condition2}]);
$.fn.responsive = function() {
var node = this;
/* conditions = {
at: 0, // threshold value
switchTo: '', // classname to apply to the node
alsoSwitch: {
'selector': 'class'
}
switchStylesheet: '',
targetFunction: '',
reverseFunction: ''
} */
var options = {
elementWidth: function() {
return $(node).outerWidth(true);
},
conditions: $.makeArray(arguments)
};
$.responsive.process.call(node, options);
};
/*
$.responsive({
elementWidth: function() {} // width calculation of the target element
}, {
condition1
});
$.responsive({
elementWidth: function() {} // width calculation of the target element
}, [{
condition1
}, {
condition2
}]);
*/
$.responsive = function(elem, options) {
// make sure that single condition object gets convert into array any how
options.conditions = $.makeArray(options.conditions);
/*var defaultOptions = {
// main element width to calculate
elementWidth: function() {}, // a function that returns pixel value
// array of conditions of ascending thresholdWidth
conditions: [{
// threshold for this condition
at: 0,
// condition specific options
switchTo: '',
alsoSwitch: {}, // objects with element and class
switchStylesheet: '',
targetFunction: '', // function to run
reverseFunction: '' // reverse function that reverses any action in target function
}]
}*/
$.responsive.process.call($(elem), options);
};
$.responsive.process = function(options) {
var node = this;
var totalConditions = options.conditions.length;
$(window).resize(function() {
$.responsive.sortConditions(options);
var elementWidth;
// calculate element width
if ($.isFunction(options.elementWidth)) {
elementWidth = options.elementWidth();
} else {
elementWidth = options.elementWidth;
}
// loop through each condition
$.each(options.conditions, function(i, condition) {
var conditionOptions = $.responsive.properConditions(condition);
var thresholdWidth = condition.at;
// calculate threshold width
if ($.isFunction(condition.at)) {
thresholdWidth = condition.at();
} else {
thresholdWidth = condition.at;
}
// perform resize if element <= threshold
if (elementWidth <= thresholdWidth) {
// remove all other condition first
$.responsive.resetToDefault.call(node, options.conditions, i);
// apply current condition
$.responsive.resize.call(node, conditionOptions);
return false;
} else {
$.responsive.deresize.call(node, conditionOptions);
}
});
}).resize();
};
$.responsive.resize = function(condition) {
var node = this;
if (condition.switchTo) {
$.each(condition.switchTo, function(i, classname) {
node.addClass(classname);
});
}
if (condition.alsoSwitch) {
$.each(condition.alsoSwitch, function(selector, classname) {
$(selector).addClass(classname);
});
}
if (condition.targetFunction) {
condition.targetFunction();
}
if (condition.switchStylesheet) {
$.each(condition.switchStylesheet, function(i, stylesheet) {
var tmp = $('link[href$="' + stylesheet + '"]');
if (tmp.length < 1) {
$('<link/>', {
rel: 'stylesheet',
type: 'text/css',
href: stylesheet
}).appendTo('head');
}
});
}
};
$.responsive.deresize = function(condition) {
var node = this;
if (condition.switchTo) {
$.each(condition.switchTo, function(i, classname) {
node.removeClass(classname);
});
}
if (condition.alsoSwitch) {
$.each(condition.alsoSwitch, function(selector, classname) {
$(selector).removeClass(classname);
});
}
if (condition.reverseFunction) {
condition.reverseFunction();
}
if (condition.switchStylesheet) {
$.each(condition.switchStylesheet, function(i, stylesheet) {
$('link[href$="' + stylesheet + '"]').remove();
});
}
};
$.responsive.resetToDefault = function(options, current) {
var node = this;
$.each(options, function(i, condition) {
if (current && i == current) {
return true;
} else {
$.responsive.deresize.call(node, condition);
}
});
};
$.responsive.properConditions = function(condition) {
var conditionOptions = {
at: condition.at,
alsoSwitch: condition.alsoSwitch,
switchTo: $.makeArray(condition.switchTo),
switchStylesheet: $.makeArray(condition.switchStylesheet),
targetFunction: condition.targetFunction,
reverseFunction: condition.reverseFunction
};
return conditionOptions;
};
$.responsive.sortConditions = function(options) {
var totalConditions = options.conditions.length;
for (var i = 0; i < totalConditions; i++) {
for (var j = i + 1; j < totalConditions; j++) {
var a, b;
if ($.isFunction(options.conditions[i].at)) {
a = options.conditions[i].at();
} else {
a = options.conditions[i].at;
}
if ($.isFunction(options.conditions[j].at)) {
b = options.conditions[j].at();
} else {
b = options.conditions[j].at;
}
if (a > b) {
var tmp = options.conditions[i];
options.conditions[i] = options.conditions[j];
options.conditions[j] = tmp;
}
}
}
};
module.resolve();
});
| cuongnd/banhangonline88_joomla | media/com_easyblog/scripts_/responsive.js | JavaScript | gpl-2.0 | 5,417 |
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2011 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#ifndef TRACE_HISTORY_RENDERER_HPP
#define TRACE_HISTORY_RENDERER_HPP
#include "Screen/Point.hpp"
#include "Math/fixed.hpp"
struct TraceHistoryLook;
struct VarioLook;
struct ChartLook;
class Chart;
class Canvas;
class TraceVariableHistory;
class TraceHistoryRenderer {
const TraceHistoryLook &look;
const VarioLook &vario_look;
const ChartLook &chart_look;
public:
TraceHistoryRenderer(const TraceHistoryLook &_look,
const VarioLook &_vario_look,
const ChartLook &_chart_look)
:look(_look), vario_look(_vario_look), chart_look(_chart_look) {}
void RenderVario(Canvas& canvas,
const PixelRect rc,
const TraceVariableHistory& var,
const bool centered = false,
const fixed mc=fixed_zero) const;
private:
void scale_chart(Chart &chart,
const TraceVariableHistory& var,
const bool centered) const;
void render_axis(Chart &chart,
const TraceVariableHistory& var) const;
void render_line(Chart &chart,
const TraceVariableHistory& var) const;
void render_filled_posneg(Chart &chart,
const TraceVariableHistory& var) const;
};
#endif
| smurry/XCSoar | src/Renderer/TraceHistoryRenderer.hpp | C++ | gpl-2.0 | 2,183 |
<?php
/**
* File containing the eZ\Publish\API\Repository\Exceptions\InvalidArgumentException class.
*
* @copyright Copyright (C) 1999-2014 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
* @version //autogentag//
*/
namespace eZ\Publish\API\Repository\Exceptions;
/**
*
* This exception is thrown if a service method is called with an illegal or non appropriate value
*/
abstract class InvalidArgumentException extends ForbiddenException
{
}
| glye/ezpublish-kernel | eZ/Publish/API/Repository/Exceptions/InvalidArgumentException.php | PHP | gpl-2.0 | 523 |
/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "GameTime.h"
#include "Pet.h"
#include "Player.h"
#include "SpellHistory.h"
#include "SpellInfo.h"
#include "SpellMgr.h"
#include "World.h"
class DuelResetScript : public PlayerScript
{
public:
DuelResetScript() : PlayerScript("DuelResetScript") { }
// Called when a duel starts (after 3s countdown)
void OnDuelStart(Player* player1, Player* player2) override
{
// Cooldowns reset
if (sWorld->getBoolConfig(CONFIG_RESET_DUEL_COOLDOWNS))
{
player1->GetSpellHistory()->SaveCooldownStateBeforeDuel();
player2->GetSpellHistory()->SaveCooldownStateBeforeDuel();
ResetSpellCooldowns(player1, true);
ResetSpellCooldowns(player2, true);
}
// Health and mana reset
if (sWorld->getBoolConfig(CONFIG_RESET_DUEL_HEALTH_MANA))
{
player1->SaveHealthBeforeDuel();
player1->SaveManaBeforeDuel();
player1->ResetAllPowers();
player2->SaveHealthBeforeDuel();
player2->SaveManaBeforeDuel();
player2->ResetAllPowers();
}
}
// Called when a duel ends
void OnDuelEnd(Player* winner, Player* loser, DuelCompleteType type) override
{
// do not reset anything if DUEL_INTERRUPTED or DUEL_FLED
if (type == DUEL_WON)
{
// Cooldown restore
if (sWorld->getBoolConfig(CONFIG_RESET_DUEL_COOLDOWNS))
{
ResetSpellCooldowns(winner, false);
ResetSpellCooldowns(loser, false);
winner->GetSpellHistory()->RestoreCooldownStateAfterDuel();
loser->GetSpellHistory()->RestoreCooldownStateAfterDuel();
}
// Health and mana restore
if (sWorld->getBoolConfig(CONFIG_RESET_DUEL_HEALTH_MANA))
{
winner->RestoreHealthAfterDuel();
loser->RestoreHealthAfterDuel();
// check if player1 class uses mana
if (winner->GetPowerType() == POWER_MANA || winner->GetClass() == CLASS_DRUID)
winner->RestoreManaAfterDuel();
// check if player2 class uses mana
if (loser->GetPowerType() == POWER_MANA || loser->GetClass() == CLASS_DRUID)
loser->RestoreManaAfterDuel();
}
}
}
static void ResetSpellCooldowns(Player* player, bool onStartDuel)
{
// remove cooldowns on spells that have < 10 min CD > 30 sec and has no onHold
player->GetSpellHistory()->ResetCooldowns([player, onStartDuel](SpellHistory::CooldownStorageType::iterator itr) -> bool
{
SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(itr->first, DIFFICULTY_NONE);
Milliseconds remainingCooldown = player->GetSpellHistory()->GetRemainingCooldown(spellInfo);
Milliseconds totalCooldown = Milliseconds(spellInfo->RecoveryTime);
Milliseconds categoryCooldown = Milliseconds(spellInfo->CategoryRecoveryTime);
auto applySpellMod = [&](Milliseconds& value)
{
int32 intValue = value.count();
player->ApplySpellMod(spellInfo, SpellModOp::Cooldown, intValue, nullptr);
value = Milliseconds(intValue);
};
applySpellMod(totalCooldown);
if (int32 cooldownMod = player->GetTotalAuraModifier(SPELL_AURA_MOD_COOLDOWN))
totalCooldown += Milliseconds(cooldownMod);
if (!spellInfo->HasAttribute(SPELL_ATTR6_IGNORE_CATEGORY_COOLDOWN_MODS))
applySpellMod(categoryCooldown);
return remainingCooldown > 0ms
&& !itr->second.OnHold
&& Milliseconds(totalCooldown) < 10min
&& Milliseconds(categoryCooldown) < 10min
&& Milliseconds(remainingCooldown) < 10min
&& (onStartDuel ? totalCooldown - remainingCooldown > 30s : true)
&& (onStartDuel ? categoryCooldown - remainingCooldown > 30s : true);
}, true);
// pet cooldowns
if (Pet* pet = player->GetPet())
pet->GetSpellHistory()->ResetAllCooldowns();
}
};
void AddSC_duel_reset()
{
new DuelResetScript();
}
| Shauren/TrinityCore | src/server/scripts/World/duel_reset.cpp | C++ | gpl-2.0 | 5,397 |
#include "SystemClass.h"
#include "InputClass.h"
#include "GraphicsClass.h"
SystemClass::SystemClass(void)
{
m_Input = nullptr;
m_Graphics = nullptr;
}
SystemClass::SystemClass(const SystemClass&)
{
}
SystemClass::~SystemClass(void)
{
}
//调用窗口初始化函数和其它一些类的初始化函数
bool SystemClass::Initialize()
{
int screenWidth = 0, screenHeight = 0;
// 初始化窗口
InitializeWindows(screenWidth, screenHeight);
//创建input对象处理键盘输入
m_Input = new InputClass;
if(!m_Input)
return false;
// 初始化输入对象
m_Input->Initialize();
// 创建图形对象,这个对象将渲染应用程序中的所有物体
m_Graphics = new GraphicsClass;
if(!m_Graphics)
return false;
// 初始化图形对象
bool result = m_Graphics->Initialize(screenWidth, screenHeight, m_hwnd);
if(!result)
return false;
return true;
}
void SystemClass::ShutDown()
{
if(m_Graphics)
{
m_Graphics->ShutDown();
delete m_Graphics;
m_Graphics = nullptr;
}
if(m_Input)
{
delete m_Input;
m_Input = nullptr;
}
// 执行窗口一些销毁工作
ShutdownWindows();
}
//处理消息
void SystemClass::Run()
{
MSG msg;
bool done = false, result = true;
// 初始化消息结构
ZeroMemory(&msg, sizeof(MSG));
// 循环进行消息处理
while (!done)
{
// 处理windows消息
if(PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// 接收到WM_QUIT消息,退出程序
if(msg.message == WM_QUIT)
done = true;
else
{
//如果按了ESC,也退出程序
result = Frame();
if(!result)
done = true;
}
}
}
bool SystemClass::Frame()
{
//检测用户是否按下ESC键,如果按下,退出程序
if(m_Input->IsKeyDown(VK_ESCAPE))
return false;
// 执行帧渲染函数
bool result = m_Graphics->Frame();
if(!result)
return false;
return true;
}
//初始化窗口类,创建应用程序窗口
void SystemClass::InitializeWindows(int& screenWidth, int& screenHeight)
{
WNDCLASSEX wc;
DEVMODE dmScreenSettings;
int posX, posY;
//获取System class对象
ApplicationHandle = this;
// 得到应用程序实例句柄
m_hinstance = GetModuleHandle(nullptr);
// 应用程序名字
m_applicationName = TEXT("Engine");
// 设置窗口类参数.
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = m_hinstance;
wc.hIcon = LoadIcon(nullptr, IDI_WINLOGO);
wc.hIconSm = wc.hIcon;
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.lpszMenuName = nullptr;
wc.lpszClassName = m_applicationName;
wc.cbSize = sizeof(WNDCLASSEX);
// 注册窗口类
RegisterClassEx(&wc);
// 得到windows桌面分辨率
screenWidth = GetSystemMetrics(SM_CXSCREEN);
screenHeight = GetSystemMetrics(SM_CYSCREEN);
// 根据是否全屏设置不同的分辨率
if(FULL_SCREEN)
{
//全屏模式下,设置窗口大小为windows桌面分辨率
memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));
dmScreenSettings.dmSize = sizeof(dmScreenSettings);
dmScreenSettings.dmPelsWidth = (DWORD)screenWidth;
dmScreenSettings.dmPelsHeight = (DWORD)screenHeight;
dmScreenSettings.dmBitsPerPel = 32;
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
// 临时设置显示设备为全屏模式,注意:应用程序退出时候,将恢复系统默认设置
ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);
// 设置窗口的左上角坐标位置为(0,0)
posX = posY = 0;
}
else
{
// 窗口模式:800*600
screenWidth = 800;
screenHeight = 600;
// 窗口左上角坐标位置,posX, posY
posX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth) / 2;
posY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2;
}
// 全屏和窗口使用不同的参数.
if(FULL_SCREEN)
{
m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName,
WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP, posX, posY,
screenWidth, screenHeight, nullptr, nullptr, m_hinstance, nullptr);
}
else
{
m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName,
WS_OVERLAPPEDWINDOW, posX, posY, screenWidth, screenHeight,
nullptr, nullptr, m_hinstance, nullptr);
}
// 显示窗口并设置其为焦点.
ShowWindow(m_hwnd, SW_SHOW);
SetForegroundWindow(m_hwnd);
SetFocus(m_hwnd);
//隐藏鼠标
ShowCursor(FALSE);
}
void SystemClass::ShutdownWindows()
{
//显示光标
ShowCursor(true);
// 恢复默认显示设置
if(FULL_SCREEN)
ChangeDisplaySettings(nullptr, 0);
//释放窗口句柄
DestroyWindow(m_hwnd);
m_hwnd = nullptr;
// 释放应用程序实例
UnregisterClass(m_applicationName, m_hinstance);
m_hinstance = nullptr;
ApplicationHandle = nullptr;
}
LRESULT CALLBACK SystemClass::MessageHandler(HWND hwnd, UINT umsg, WPARAM wparam, LPARAM lparam)
{
switch (umsg)
{
// 检测按键消息
case WM_KEYDOWN:
m_Input->KeyDown((unsigned int)wparam);
return 0;
case WM_KEYUP:
m_Input->KeyUp((unsigned int)wparam);
return 0;
//任何其它消息发送到windows缺省处理
case WM_SIZE:
{
int screenWidth = 0, screenHeight = 0;
screenWidth = LOWORD(lparam);
screenHeight = HIWORD(lparam);
// 窗口大小改变时,重新初始化图形对象
if(m_Graphics)
{
bool result = m_Graphics->Initialize(screenWidth, screenHeight, m_hwnd);
if(!result)
return 0;
}
return 0;
}
default:
return DefWindowProc(hwnd, umsg, wparam, lparam);
}
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT umessage, WPARAM wparam, LPARAM lparam)
{
switch (umessage)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_CLOSE:
PostQuitMessage(0);
return 0;
default:
return ApplicationHandle->MessageHandler(hwnd, umessage, wparam, lparam);
}
} | Jesna/DirectX | D3D11/myTutorialD3D11/myTutorialD3D11_6/SystemClass.cpp | C++ | gpl-2.0 | 5,919 |
require 'rails_helper'
RSpec.describe Jobs::PublishTopicToCategory do
let(:category) { Fabricate(:category) }
let(:another_category) { Fabricate(:category) }
let(:topic) do
topic = Fabricate(:topic, category: category)
Fabricate(:topic_timer,
status_type: TopicTimer.types[:publish_to_category],
category_id: another_category.id,
topic: topic
)
topic
end
before do
SiteSetting.queue_jobs = true
end
describe 'when topic has been deleted' do
it 'should not publish the topic to the new category' do
freeze_time 1.hour.ago
topic
freeze_time 1.hour.from_now
topic.trash!
described_class.new.execute(topic_timer_id: topic.public_topic_timer.id)
topic.reload
expect(topic.category).to eq(category)
expect(topic.created_at).to be_within(1.second).of(Time.zone.now - 1.hour)
end
end
it 'should publish the topic to the new category' do
freeze_time 1.hour.ago do
topic.update!(visible: false)
end
message = MessageBus.track_publish do
described_class.new.execute(topic_timer_id: topic.public_topic_timer.id)
end.find do |m|
Hash === m.data && m.data.key?(:reload_topic)
end
topic.reload
expect(topic.category).to eq(another_category)
expect(topic.visible).to eq(true)
expect(topic.public_topic_timer).to eq(nil)
%w{created_at bumped_at updated_at last_posted_at}.each do |attribute|
expect(topic.public_send(attribute)).to be_within(1.second).of(Time.zone.now)
end
expect(message.data[:reload_topic]).to be_present
expect(message.data[:refresh_stream]).to be_present
end
describe 'when topic is a private message' do
before do
freeze_time 1.hour.ago do
expect { topic.convert_to_private_message(Discourse.system_user) }
.to change { topic.private_message? }.to(true)
end
end
it 'should publish the topic to the new category' do
message = MessageBus.track_publish do
described_class.new.execute(topic_timer_id: topic.public_topic_timer.id)
end.last
topic.reload
expect(topic.category).to eq(another_category)
expect(topic.visible).to eq(true)
expect(topic.private_message?).to eq(false)
%w{created_at bumped_at updated_at last_posted_at}.each do |attribute|
expect(topic.public_send(attribute)).to be_within(1.second).of(Time.zone.now)
end
expect(message.data[:reload_topic]).to be_present
expect(message.data[:refresh_stream]).to be_present
end
end
end
| gfvcastro/discourse | spec/jobs/publish_topic_to_category_spec.rb | Ruby | gpl-2.0 | 2,580 |
<?php
/**
* @package EasyBlog
* @copyright Copyright (C) 2010 - 2015 Stack Ideas Sdn Bhd. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* EasyBlog is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
defined('_JEXEC') or die('Unauthorized Access');
?>
<div class="eb-composer-pick-item"
data-avatar="<?php echo $associate->avatar;?>"
data-id="<?php echo $associate->source_id;?>"
data-type="<?php echo $associate->source_type;?>"
data-title="<?php echo $associate->title;?>"
data-associates-item
>
<div class="eb-radio">
<input type="radio" name="radio-associates" id="radio-<?php echo $associate->type;?>-<?php echo $associate->source_id;?>" value="<?php echo $associate->source_id;?>" data-associates-checkbox
<?php echo $associate->source_id == $source_id && $associate->source_type == $source_type ? ' checked="checked"' : '';?>
/>
<label for="radio-<?php echo $associate->type;?>-<?php echo $associate->source_id;?>">
<div class="col-cell">
<img src="<?php echo $associate->avatar;?>" class="avatar" width="30" height="30" />
</div>
<div class="col-cell">
<?php echo $associate->title;?>
</div>
</label>
</div>
</div>
| quanghung0404/it2tech | components/com_easyblog/themes/wireframe/composer/form/author/associates.php | PHP | gpl-2.0 | 1,555 |
<?php
namespace SendGrid\Test;
use PHPUnit\Framework\TestCase;
class LicenceYearTest extends TestCase
{
public function testLicenseYear()
{
$rootDir = __DIR__ . '/../..';
$license = explode("\n", file_get_contents("$rootDir/LICENSE"));
$copyright = trim($license[2]);
$year = date('Y');
$expected = "Copyright (C) {$year}, Twilio SendGrid, Inc. <help@twilio.com>";
$this->assertEquals($expected, $copyright);
}
}
| Greg-Boggs/GamingLadder | vendor/sendgrid/php-http-client/test/unit/LicenceYearTest.php | PHP | gpl-2.0 | 480 |
<?php
/*
*
* @author Ken Lalobo
*
*/
namespace Mooti\Service\Account\Controller;
use Mooti\Framework\Rest\BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Mooti\Framework\Framework;
use Mooti\Service\Account\Model\User\UserMapper;
class User extends BaseController
{
use Framework;
public function getUsers(Request $request, Response $response)
{
$userMapper = $this->createNew(UserMapper::class);
$users = $userMapper->findAll();
return $this->render($users, $response);
}
public function getUser($id, Request $request, Response $response)
{
$userMapper = $this->createNew(UserMapper::class);
$user = $userMapper->find($id);
return $this->render($user, $response);
}
}
| mooti/mooti-service-account | src/Controller/User.php | PHP | gpl-2.0 | 821 |
/*
* Digital Media Server, for streaming digital media to UPnP AV or DLNA
* compatible devices based on PS3 Media Server and Universal Media Server.
* Copyright (C) 2016 Digital Media Server developers.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see http://www.gnu.org/licenses/.
*/
package net.pms.dlna;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.drew.metadata.Metadata;
import net.pms.exception.DLNAProfileException;
import net.pms.exception.ParseException;
import net.pms.image.Image;
import net.pms.image.ImageFormat;
import net.pms.image.ImageInfo;
import net.pms.image.ImagesUtil;
import net.pms.image.ImagesUtil.ScaleType;
/**
* This class is simply a byte array for holding an {@link ImageIO} supported
* image with some additional metadata restricted to the DLNA image media
* format profiles {@code JPEG_*} and {@code PNG_*}.
*
* @see DLNAThumbnailInputStream
*
* @author Nadahar
*/
public class DLNABinaryThumbnail extends DLNAImage implements DLNAThumbnail {
private static final Logger LOGGER = LoggerFactory.getLogger(DLNAImage.class);
/*
* Please note: This class is packed and stored in the database. Any changes
* to the data structure (fields) will invalidate any instances already
* stored, and will require a wipe of all rows with a stored instance. The
* serialVersionUID value below should also be bumped.
*/
private static final long serialVersionUID = 1L;
/**
* Creates a new {@link DLNABinaryThumbnail} instance.
*
* @param image the source {@link Image} in either JPEG or PNG format
* adhering to the DLNA restrictions for color space and
* compression.
* @param profile the {@link DLNAImageProfile} this {@link DLNAImage}
* adheres to.
* @param copy whether this instance should be copied or shared.
* @throws DLNAProfileException if the profile compliance check fails.
*/
public DLNABinaryThumbnail(
Image image,
DLNAImageProfile profile,
boolean copy
) throws DLNAProfileException {
super(image, profile, copy);
}
/**
* Creates a new {@link DLNABinaryThumbnail} instance.
*
* @param bytes the source image in either JPEG or PNG format adhering to
* the DLNA restrictions for color space and compression.
* @param imageInfo the {@link ImageInfo} to store with this
* {@link DLNABinaryThumbnail}.
* @param profile the {@link DLNAImageProfile} this {@link DLNAImage}
* adheres to.
* @param copy whether this instance should be copied or shared.
* @throws DLNAProfileException if the profile compliance check fails.
*/
public DLNABinaryThumbnail(
byte[] bytes,
ImageInfo imageInfo,
DLNAImageProfile profile,
boolean copy
) throws DLNAProfileException {
super(bytes, imageInfo, profile, copy);
}
/**
* Creates a new {@link DLNABinaryThumbnail} instance.
*
* @param bytes the source image in either JPEG or PNG format adhering to
* the DLNA restrictions for color space and compression.
* @param width the width of the image.
* @param height the height of the image.
* @param format the {@link ImageFormat} of the image.
* @param colorModel the {@link ColorModel} of the image.
* @param metadata the {@link Metadata} instance describing the image.
* @param profile the {@link DLNAImageProfile} this {@link DLNAImage}
* adheres to.
* @param copy whether this instance should be copied or shared.
* @throws DLNAProfileException if the profile compliance check fails.
* @throws ParseException if {@code format} is {@code null} and parsing the
* format from {@code metadata} fails.
*/
public DLNABinaryThumbnail(
byte[] bytes,
int width,
int height,
ImageFormat format,
ColorModel colorModel,
Metadata metadata,
DLNAImageProfile profile,
boolean copy
) throws DLNAProfileException, ParseException {
super(bytes, width, height, format, colorModel, metadata, profile, copy);
}
/**
* Creates a new {@link DLNABinaryThumbnail} instance.
*
* @param bytes the source image in either JPEG or PNG format adhering to
* the DLNA restrictions for color space and compression.
* @param format the {@link ImageFormat} of the image.
* @param bufferedImage the {@link BufferedImage} to get non-
* {@link Metadata} metadata from.
* @param metadata the {@link Metadata} instance describing the image.
* @param profile the {@link DLNAImageProfile} this {@link DLNAImage}
* adheres to.
* @param copy whether this instance should be copied or shared.
* @throws DLNAProfileException if the profile compliance check fails.
* @throws ParseException if {@code format} is {@code null} and parsing the
* format from {@code metadata} fails.
*/
public DLNABinaryThumbnail(
byte[] bytes,
ImageFormat format,
BufferedImage bufferedImage,
Metadata metadata,
DLNAImageProfile profile,
boolean copy
) throws DLNAProfileException, ParseException {
super(bytes, format, bufferedImage, metadata, profile, copy);
}
/**
* Converts an {@link Image} to a {@link DLNABinaryThumbnail}. Output format will
* be the same as the source if the source is either JPEG or PNG. Further
* restrictions on color space and compression is imposed and conversion
* done if necessary. All other formats will be converted to a DLNA
* compliant JPEG.
*
* @param inputImage the source {@link Image}.
* @return The populated {@link DLNABinaryThumbnail} or {@code null} if the source
* image is {@code null}.
* @throws IOException if the operation fails.
*/
public static DLNABinaryThumbnail toThumbnail(Image inputImage) throws IOException {
return toThumbnail(inputImage, 0, 0, null, ImageFormat.SOURCE, false);
}
/**
* Converts an image to a {@link DLNABinaryThumbnail}. Format support is limited
* to that of {@link ImageIO}. Output format will be the same as source if
* the source is either JPEG or PNG. Further restrictions on color space and
* compression is imposed and conversion done if necessary. All other
* formats will be converted to a DLNA compliant JPEG. Preserves aspect
* ratio and rotates/flips the image according to Exif orientation.
* <p>
* <b> This method consumes and closes {@code inputStream}. </b>
*
* @param inputStream the source image in a supported format.
* @return The populated {@link DLNABinaryThumbnail} or {@code null} if the source
* image is {@code null}.
* @throws IOException if the operation fails.
*/
public static DLNABinaryThumbnail toThumbnail(InputStream inputStream) throws IOException {
return toThumbnail(inputStream, 0, 0, null, ImageFormat.SOURCE, false);
}
/**
* Converts an image to a {@link DLNABinaryThumbnail}. Format support is limited
* to that of {@link ImageIO}. Output format will be the same as source if
* the source is either JPEG or PNG. Further restrictions on color space and
* compression is imposed and conversion done if necessary. All other
* formats will be converted to a DLNA compliant JPEG. Preserves aspect
* ratio and rotates/flips the image according to Exif orientation.
*
* @param inputByteArray the source image in a supported format.
* @return The populated {@link DLNABinaryThumbnail} or {@code null} if the source
* image is {@code null}.
* @throws IOException if the operation fails.
*/
public static DLNABinaryThumbnail toThumbnail(byte[] inputByteArray) throws IOException {
return toThumbnail(inputByteArray, 0, 0, null, ImageFormat.SOURCE, false);
}
/**
* Converts an {@link Image} to a {@link DLNABinaryThumbnail} adhering to
* {@code outputProfile}. {@code outputProfile} is limited to JPEG or PNG
* profiles. If {@code outputProfile} is a GIF profile, the image will be
* converted to {@link DLNAImageProfile#JPEG_LRG}.
*
* @param inputImage the source {@link Image}.
* @param outputProfile the {@link DLNAImageProfile} to adhere to for the
* output.
* @param padToSize whether padding should be used if source aspect doesn't
* match target aspect.
* @return The populated {@link DLNABinaryThumbnail} or {@code null} if the source
* image is {@code null}.
* @throws IOException if the operation fails.
*/
public static DLNABinaryThumbnail toThumbnail(
Image inputImage,
DLNAImageProfile outputProfile,
boolean padToSize
) throws IOException {
if (inputImage == null) {
return null;
}
return (DLNABinaryThumbnail) ImagesUtil.transcodeImage(
inputImage,
outputProfile,
true,
padToSize
);
}
/**
* Converts an image to a {@link DLNABinaryThumbnail} adhering to
* {@code outputProfile}. Format support is limited to that of
* {@link ImageIO}. {@code outputProfile} is limited to JPEG or PNG
* profiles. If {@code outputProfile} is a GIF profile, the image will be
* converted to {@link DLNAImageProfile#JPEG_LRG}. Preserves aspect ratio
* and rotates/flips the image according to Exif orientation.
*
* <p>
* <b> This method consumes and closes {@code inputStream}. </b>
*
* @param inputStream the source image in a supported format.
* @param outputProfile the {@link DLNAImageProfile} to adhere to for the
* output.
* @param padToSize whether padding should be used if source aspect doesn't
* match target aspect.
* @return The populated {@link DLNABinaryThumbnail} or {@code null} if the source
* image is {@code null}.
* @throws IOException if the operation fails.
*/
public static DLNABinaryThumbnail toThumbnail(
InputStream inputStream,
DLNAImageProfile outputProfile,
boolean padToSize
) throws IOException {
if (inputStream == null) {
return null;
}
return (DLNABinaryThumbnail) ImagesUtil.transcodeImage(
inputStream,
outputProfile,
true,
padToSize
);
}
/**
* Converts an image to a {@link DLNABinaryThumbnail} adhering to
* {@code outputProfile}. Format support is limited to that of
* {@link ImageIO}. {@code outputProfile} is limited to JPEG or PNG
* profiles. If {@code outputProfile} is a GIF profile, the image will be
* converted to {@link DLNAImageProfile#JPEG_LRG}. Preserves aspect ratio
* and rotates/flips the image according to Exif orientation.
*
* @param inputByteArray the source image in a supported format.
* @param outputProfile the {@link DLNAImageProfile} to adhere to for the
* output.
* @param padToSize whether padding should be used if source aspect doesn't
* match target aspect.
* @return The populated {@link DLNABinaryThumbnail} or {@code null} if the source
* image is {@code null}.
* @throws IOException if the operation fails.
*/
public static DLNABinaryThumbnail toThumbnail(
byte[] inputByteArray,
DLNAImageProfile outputProfile,
boolean padToSize
) throws IOException {
if (inputByteArray == null) {
return null;
}
return (DLNABinaryThumbnail) ImagesUtil.transcodeImage(
inputByteArray,
outputProfile,
true,
padToSize
);
}
/**
* Converts an {@link Image} to a {@link DLNABinaryThumbnail}. Format support is
* limited to that of {@link ImageIO}. {@code outputFormat} is limited to
* JPEG or PNG format adhering to the DLNA restrictions for color space and
* compression. If {@code outputFormat} doesn't qualify, the image will be
* converted to a DLNA compliant JPEG.
*
* @param inputImage the source {@link Image}.
* @param width the new width or 0 to disable scaling.
* @param height the new height or 0 to disable scaling.
* @param scaleType the {@link ScaleType} to use when scaling.
* @param outputFormat the {@link ImageFormat} to generate or
* {@link ImageFormat#SOURCE} to preserve source format.
* @param padToSize whether padding should be used if source aspect doesn't
* match target aspect.
* @return The populated {@link DLNABinaryThumbnail} or {@code null} if the source
* image is {@code null}.
* @throws IOException if the operation fails.
*/
public static DLNABinaryThumbnail toThumbnail(
Image inputImage,
int width,
int height,
ScaleType scaleType,
ImageFormat outputFormat,
boolean padToSize
) throws IOException {
if (inputImage == null) {
return null;
}
return (DLNABinaryThumbnail) ImagesUtil.transcodeImage(
inputImage,
width,
height,
scaleType,
outputFormat,
true,
true,
padToSize
);
}
/**
* Converts an image to a {@link DLNABinaryThumbnail}. Format support is limited
* to that of {@link ImageIO}. {@code outputFormat} is limited to JPEG or
* PNG format adhering to the DLNA restrictions for color space and
* compression. If {@code outputFormat} doesn't qualify, the image will be
* converted to a DLNA compliant JPEG. Preserves aspect ratio and
* rotates/flips the image according to Exif orientation.
* <p>
* <b> This method consumes and closes {@code inputStream}. </b>
*
* @param inputStream the source image in a supported format.
* @param width the new width or 0 to disable scaling.
* @param height the new height or 0 to disable scaling.
* @param scaleType the {@link ScaleType} to use when scaling.
* @param outputFormat the {@link ImageFormat} to generate or
* {@link ImageFormat#SOURCE} to preserve source format.
* @param padToSize whether padding should be used if source aspect doesn't
* match target aspect.
* @return The populated {@link DLNABinaryThumbnail} or {@code null} if the source
* image is {@code null}.
* @throws IOException if the operation fails.
*/
public static DLNABinaryThumbnail toThumbnail(
InputStream inputStream,
int width,
int height,
ScaleType scaleType,
ImageFormat outputFormat,
boolean padToSize
) throws IOException {
if (inputStream == null) {
return null;
}
return (DLNABinaryThumbnail) ImagesUtil.transcodeImage(
inputStream,
width,
height,
scaleType,
outputFormat,
true,
true,
padToSize
);
}
/**
* Converts an image to a {@link DLNABinaryThumbnail}. Format support is limited
* to that of {@link ImageIO}. {@code outputFormat} is limited to JPEG or
* PNG format adhering to the DLNA restrictions for color space and
* compression. If {@code outputFormat} doesn't qualify, the image will be
* converted to a DLNA compliant JPEG. Preserves aspect ratio and
* rotates/flips the image according to Exif orientation.
*
* @param inputByteArray the source image in a supported format.
* @param width the new width or 0 to disable scaling.
* @param height the new height or 0 to disable scaling.
* @param scaleType the {@link ScaleType} to use when scaling.
* @param outputFormat the {@link ImageFormat} to generate or
* {@link ImageFormat#SOURCE} to preserve source format.
* @param padToSize whether padding should be used if source aspect doesn't
* match target aspect.
* @return The populated {@link DLNABinaryThumbnail} or {@code null} if the source
* image is {@code null}.
* @throws IOException if the operation fails.
*/
public static DLNABinaryThumbnail toThumbnail(
byte[] inputByteArray,
int width,
int height,
ScaleType scaleType,
ImageFormat outputFormat,
boolean padToSize) throws IOException {
return (DLNABinaryThumbnail) ImagesUtil.transcodeImage(
inputByteArray,
width,
height,
scaleType,
outputFormat,
true,
true,
padToSize
);
}
/**
* Converts and scales the thumbnail according to the given
* {@link DLNAImageProfile}. Preserves aspect ratio. Format support is
* limited to that of {@link ImageIO}.
*
* @param outputProfile the {@link DLNAImageProfile} to adhere to for the output.
* @param padToSize Whether padding should be used if source aspect doesn't
* match target aspect.
* @return The scaled and/or converted thumbnail, {@code null} if the
* source is {@code null}.
* @exception IOException if the operation fails.
*/
public DLNABinaryThumbnail transcode(
DLNAImageProfile outputProfile,
boolean padToSize
) throws IOException {
return (DLNABinaryThumbnail) ImagesUtil.transcodeImage(
this,
outputProfile,
true,
padToSize);
}
@Override
public DLNABinaryThumbnail copy() {
try {
return new DLNABinaryThumbnail(bytes, imageInfo, profile, true);
} catch (DLNAProfileException e) {
// Should be impossible
LOGGER.error("Impossible situation in DLNAImage.copy(): {}", e.getMessage());
LOGGER.trace("", e);
return null;
}
}
}
| DigitalMediaServer/DigitalMediaServer | src/main/java/net/pms/dlna/DLNABinaryThumbnail.java | Java | gpl-2.0 | 17,364 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2004,2005,2006 INRIA
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
*/
#include "ns3/log.h"
#include "arf-wifi-manager.h"
#include "wifi-tx-vector.h"
#define Min(a,b) ((a < b) ? a : b)
namespace ns3 {
NS_LOG_COMPONENT_DEFINE ("ArfWifiManager");
/**
* \brief hold per-remote-station state for ARF Wifi manager.
*
* This struct extends from WifiRemoteStation struct to hold additional
* information required by the ARF Wifi manager
*/
struct ArfWifiRemoteStation : public WifiRemoteStation
{
uint32_t m_timer; ///< timer value
uint32_t m_success; ///< success count
uint32_t m_failed; ///< failed count
bool m_recovery; ///< recovery
uint32_t m_retry; ///< retry count
uint32_t m_timerTimeout; ///< timer timeout
uint32_t m_successThreshold; ///< success threshold
uint8_t m_rate; ///< rate
};
NS_OBJECT_ENSURE_REGISTERED (ArfWifiManager);
TypeId
ArfWifiManager::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::ArfWifiManager")
.SetParent<WifiRemoteStationManager> ()
.SetGroupName ("Wifi")
.AddConstructor<ArfWifiManager> ()
.AddAttribute ("TimerThreshold", "The 'timer' threshold in the ARF algorithm.",
UintegerValue (15),
MakeUintegerAccessor (&ArfWifiManager::m_timerThreshold),
MakeUintegerChecker<uint32_t> ())
.AddAttribute ("SuccessThreshold",
"The minimum number of successful transmissions to try a new rate.",
UintegerValue (10),
MakeUintegerAccessor (&ArfWifiManager::m_successThreshold),
MakeUintegerChecker<uint32_t> ())
.AddTraceSource ("Rate",
"Traced value for rate changes (b/s)",
MakeTraceSourceAccessor (&ArfWifiManager::m_currentRate),
"ns3::TracedValueCallback::Uint64")
;
return tid;
}
ArfWifiManager::ArfWifiManager ()
: WifiRemoteStationManager (),
m_currentRate (0)
{
NS_LOG_FUNCTION (this);
}
ArfWifiManager::~ArfWifiManager ()
{
NS_LOG_FUNCTION (this);
}
WifiRemoteStation *
ArfWifiManager::DoCreateStation (void) const
{
NS_LOG_FUNCTION (this);
ArfWifiRemoteStation *station = new ArfWifiRemoteStation ();
station->m_successThreshold = m_successThreshold;
station->m_timerTimeout = m_timerThreshold;
station->m_rate = 0;
station->m_success = 0;
station->m_failed = 0;
station->m_recovery = false;
station->m_retry = 0;
station->m_timer = 0;
return station;
}
void
ArfWifiManager::DoReportRtsFailed (WifiRemoteStation *station)
{
NS_LOG_FUNCTION (this << station);
}
/**
* It is important to realize that "recovery" mode starts after failure of
* the first transmission after a rate increase and ends at the first successful
* transmission. Specifically, recovery mode transcends retransmissions boundaries.
* Fundamentally, ARF handles each data transmission independently, whether it
* is the initial transmission of a packet or the retransmission of a packet.
* The fundamental reason for this is that there is a backoff between each data
* transmission, be it an initial transmission or a retransmission.
*
* \param st the station that we failed to send DATA
*/
void
ArfWifiManager::DoReportDataFailed (WifiRemoteStation *st)
{
NS_LOG_FUNCTION (this << st);
ArfWifiRemoteStation *station = (ArfWifiRemoteStation *)st;
station->m_timer++;
station->m_failed++;
station->m_retry++;
station->m_success = 0;
if (station->m_recovery)
{
NS_ASSERT (station->m_retry >= 1);
if (station->m_retry == 1)
{
//need recovery fallback
if (station->m_rate != 0)
{
station->m_rate--;
}
}
station->m_timer = 0;
}
else
{
NS_ASSERT (station->m_retry >= 1);
if (((station->m_retry - 1) % 2) == 1)
{
//need normal fallback
if (station->m_rate != 0)
{
station->m_rate--;
}
}
if (station->m_retry >= 2)
{
station->m_timer = 0;
}
}
}
void
ArfWifiManager::DoReportRxOk (WifiRemoteStation *station,
double rxSnr, WifiMode txMode)
{
NS_LOG_FUNCTION (this << station << rxSnr << txMode);
}
void ArfWifiManager::DoReportRtsOk (WifiRemoteStation *station,
double ctsSnr, WifiMode ctsMode, double rtsSnr)
{
NS_LOG_FUNCTION (this << station << ctsSnr << ctsMode << rtsSnr);
NS_LOG_DEBUG ("station=" << station << " rts ok");
}
void ArfWifiManager::DoReportDataOk (WifiRemoteStation *st,
double ackSnr, WifiMode ackMode, double dataSnr)
{
NS_LOG_FUNCTION (this << st << ackSnr << ackMode << dataSnr);
ArfWifiRemoteStation *station = (ArfWifiRemoteStation *) st;
station->m_timer++;
station->m_success++;
station->m_failed = 0;
station->m_recovery = false;
station->m_retry = 0;
NS_LOG_DEBUG ("station=" << station << " data ok success=" << station->m_success << ", timer=" << station->m_timer);
if ((station->m_success == m_successThreshold
|| station->m_timer == m_timerThreshold)
&& (station->m_rate < (station->m_state->m_operationalRateSet.size () - 1)))
{
NS_LOG_DEBUG ("station=" << station << " inc rate");
station->m_rate++;
station->m_timer = 0;
station->m_success = 0;
station->m_recovery = true;
}
}
void
ArfWifiManager::DoReportFinalRtsFailed (WifiRemoteStation *station)
{
NS_LOG_FUNCTION (this << station);
}
void
ArfWifiManager::DoReportFinalDataFailed (WifiRemoteStation *station)
{
NS_LOG_FUNCTION (this << station);
}
WifiTxVector
ArfWifiManager::DoGetDataTxVector (WifiRemoteStation *st)
{
NS_LOG_FUNCTION (this << st);
ArfWifiRemoteStation *station = (ArfWifiRemoteStation *) st;
uint16_t channelWidth = GetChannelWidth (station);
if (channelWidth > 20 && channelWidth != 22)
{
//avoid to use legacy rate adaptation algorithms for IEEE 802.11n/ac
channelWidth = 20;
}
WifiMode mode = GetSupported (station, station->m_rate);
if (m_currentRate != mode.GetDataRate (channelWidth))
{
NS_LOG_DEBUG ("New datarate: " << mode.GetDataRate (channelWidth));
m_currentRate = mode.GetDataRate (channelWidth);
}
return WifiTxVector (mode, GetDefaultTxPowerLevel (), GetPreambleForTransmission (mode, GetAddress (station)), 800, 1, 1, 0, channelWidth, GetAggregation (station), false);
}
WifiTxVector
ArfWifiManager::DoGetRtsTxVector (WifiRemoteStation *st)
{
NS_LOG_FUNCTION (this << st);
/// \todo we could/should implement the Arf algorithm for
/// RTS only by picking a single rate within the BasicRateSet.
ArfWifiRemoteStation *station = (ArfWifiRemoteStation *) st;
uint16_t channelWidth = GetChannelWidth (station);
if (channelWidth > 20 && channelWidth != 22)
{
//avoid to use legacy rate adaptation algorithms for IEEE 802.11n/ac
channelWidth = 20;
}
WifiTxVector rtsTxVector;
WifiMode mode;
if (GetUseNonErpProtection () == false)
{
mode = GetSupported (station, 0);
}
else
{
mode = GetNonErpSupported (station, 0);
}
rtsTxVector = WifiTxVector (mode, GetDefaultTxPowerLevel (), GetPreambleForTransmission (mode, GetAddress (station)), 800, 1, 1, 0, channelWidth, GetAggregation (station), false);
return rtsTxVector;
}
bool
ArfWifiManager::IsLowLatency (void) const
{
return true;
}
void
ArfWifiManager::SetHtSupported (bool enable)
{
//HT is not supported by this algorithm.
if (enable)
{
NS_FATAL_ERROR ("WifiRemoteStationManager selected does not support HT rates");
}
}
void
ArfWifiManager::SetVhtSupported (bool enable)
{
//VHT is not supported by this algorithm.
if (enable)
{
NS_FATAL_ERROR ("WifiRemoteStationManager selected does not support VHT rates");
}
}
void
ArfWifiManager::SetHeSupported (bool enable)
{
//HE is not supported by this algorithm.
if (enable)
{
NS_FATAL_ERROR ("WifiRemoteStationManager selected does not support HE rates");
}
}
} //namespace ns3
| tomhenderson/ns-3-dev-git | src/wifi/model/arf-wifi-manager.cc | C++ | gpl-2.0 | 8,873 |
//Copyright (C) 2015 Timothy Watson, Jakub Pachansky
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either version 2
//of the License, or (at your option) any later version.
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
define(['backbone', 'backbone-pageable'], function(Backbone) {
"use strict";
var collection = Backbone.PageableCollection.extend({
url: "heartbeats",
mode: "client"
});
return collection;
});
| R-Suite/ServiceConnect.Monitor | ServiceConnect.Monitor/Scripts/app/collections/heartbeats.js | JavaScript | gpl-2.0 | 987 |
<?php
#-----------------------------------------
# RT-Theme rt_setup_assistant.php
# version: 1.0
#-----------------------------------------
#
# Setup assitant for RT-Themes
#
class RTSetupAssistant{
function __construct(){
//Screenshot URL
$screenshotURL = "http://templatemints.com/theme_screenshots/rt-theme17/index.php";
//Class For Contents
$contents = new stdClass;
$step_count = 0;
$content_count = 0;
#
# Step 1
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Import Dummy Contents';
@$contents->step[$step_count]->single_step = 1;
#
# Sub Titles
#
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Import Dummy Contents';
@$contents->step[$step_count]->contents[$content_count]->content =
'
This step is optional. You can import some of the dummy contents of the demo site if you want. <br /><br />
<div class="sub_title list">Follow these steps to inport the dummy content file</div>
<ol>
<li>Go Tools → Import, click WordPress <a href="admin.php?import=wordpress">show me →</a> </li>
<li>Click browse button and find the XML file in the "Dummy Content" folder that comes with the package you donwloaded from ThemeForest.</li>
<li>Hit "Upload file and import" button and follow the screen instructions.</li>
</ol>
';
#
# Step 2
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Create Pages';
@$contents->step[$step_count]->single_step = 1;
#
# Sub Titles
#
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Create your pages';
@$contents->step[$step_count]->contents[$content_count]->content =
'
Use WordPress "Pages" to create your pages. <a href="post-new.php?post_type=page">show me →</a> <br /><br />
<div class="sub_title list">Things to you should know</div>
<ul>
<li>You can select a template for your page under the <b>"RT-Theme Template Options"</b> box. If you have created custom templates via <b><a href="admin.php?page=rt_template_options">Template Builder</a></b>, you can use it as your page template by selecting it from the tempalte list under the box. <a href="'.$screenshotURL.'?image=template-options.png&preview_iframe=1&TB_iframe=true&" title="RT-Theme Screenshots" class="thickbox">Screenshot</a> </li>
</ul>
';
#
# Step 3
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Create Blog';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Create your posts';
@$contents->step[$step_count]->contents[$content_count]->content =
'
Use WordPress "Posts" to create your blog posts. <a href="post-new.php?post_type=post">show me →</a> <br /><br />
<div class="sub_title list">Things to you should know</div>
<ul>
<li>You can select a template for your post under the <b>"RT-Theme Template Options"</b> box. If you have created custom templates via <b><a href="admin.php?page=rt_template_options">Template Builder</a></b>, you can use it as your page template by selecting it from the tempalte list under the box. <a href="'.$screenshotURL.'?image=template-options.png&preview_iframe=1&TB_iframe=true&" title="RT-Theme Screenshots" class="thickbox">Screenshot</a> </li>
<li>Upload featured image by clicking the "Set featured image" link under the "Featured Image" box.
<a href="'.$screenshotURL.'?image=featured-images.png&preview_iframe=1&TB_iframe=true&" title="RT-Theme Screenshots" class="thickbox">Screenshot</a>
</li>
</ul>
<div class="sub_title list">RT-Theme Post Format Options</div>
<ul>
<li>There are six post format available to select under the "Format" box listed as options.</li>
<li>You can find related options with your post format under the "RT-Theme Post Format Options" box.</li>
</ul>
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Define a page as your Blog page';
@$contents->step[$step_count]->contents[$content_count]->content =
'
Any page can be a blog page! Also you can have multiple blog pages that shows different categories.
Tip: If you do not need a customized layout such as a slider before than the blog posts, you can just use categories as your menu items.
<br /><br />
<div class="sub_title qa">Defining a page as a Blog page</div>
<ol>
<li>Add/Edit a page</li>
<li>Select "Default Blog Template" from the "Templates" list under the <b>"RT-Theme Template Options"</b> box. <a href="'.$screenshotURL.'?image=template-options.png&preview_iframe=1&TB_iframe=true&" title="RT-Theme Screenshots" class="thickbox">Screenshot</a></li>
</ol>
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Customize Default Blog Template or Create one';
@$contents->step[$step_count]->contents[$content_count]->content =
'
<ol>
<li>Open Template Builder and expand "Default Blog Template"</li>
<li>Expand "Blog Posts" by clicking the plus icon on right-top corner of the module.</li>
<li>Change the options, add or remove new modules into the template.</li>
<li>Click save options icon on the right or "Save Options" button at the bottom of the page.</li>
</ol>
<br />
If you would like to learn how create a new template please read "How To Use Template Builder" section of the Setup Assistant.
';
#
# Step 4
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Create Portfolio';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Create your portfolio items';
@$contents->step[$step_count]->contents[$content_count]->content =
'
Use "Porfolio" custom post types to add a new portfolio item. <a href="post-new.php?post_type=portfolio">show me →</a> <br /><br />
<div class="sub_title list">Things to you should know</div>
<ul>
<li>If you want to show your portfolio items in a page, you can use page templates by adding "Portfolio Posts" module.</li>
<li>You can find various options for the portfolio categories on <a href="admin.php?page=rt_portfolio_options">Portfolio Options</a></li>
<li>Make sure that all your portfolio items has been assigned at least a portfolio category. <a href="edit-tags.php?taxonomy=portfolio_categories&post_type=portfolio">manage portfolio categories →</a></li>
</ul>
<div class="sub_title qa">Q : How can I add my Portfolio categories to the main menu?</div>
<div class="answer qa">A : Please read "How Create Navigation Menus?" </div>
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Define a page as your Portfolio page';
@$contents->step[$step_count]->contents[$content_count]->content =
'
Any page can be a portfolio page also you can use the portfolio categories in your menu. You all need to select "Default Portfolio Template" for your page under the <b>"RT-Theme Template Options"</b> box. (<a href="'.$screenshotURL.'?image=template-options.png&preview_iframe=1&TB_iframe=true&" title="RT-Theme Screenshots" class="thickbox">Screenshot</a></li>)
<br />
You are also free to create new portfolio templates that suits your needs or customize the default one via <a href="admin.php?page=rt_template_options">Template Builder</a>
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Customize Default Portfolio Template or Create one';
@$contents->step[$step_count]->contents[$content_count]->content =
'
<ol>
<li>Open Template Builder and expand "Default Portfolio Template"</li>
<li>Expand "Portfolio Posts" by clicking the plus icon on right-top corner of the module.</li>
<li>Change the options, add or remove new modules into the template.</li>
<li>Click save options icon on the right or "Save Options" button at the bottom of the page.</li>
</ol>
<br />
If you would like to learn how create a new template please read "How To Use Template Builder" section of the Setup Assistant.
';
#
# Step 5
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Create Product Showcase';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Create your products';
@$contents->step[$step_count]->contents[$content_count]->content =
'
Use "Product" custom post types to add a new product. <a href="post-new.php?post_type=products">show me →</a> <br /><br />
<div class="sub_title list">Things to you should know</div>
<ul>
<li>Make sure that all your products has been assigned at least a product category. <a href="edit-tags.php?taxonomy=product_categories&post_type=products">Manage Portfolio Categories →</a></li>
</ul>
<div class="sub_title qa">Q : How can I add my Product categories to the main menu?</div>
<div class="answer qa">A : Please read "How Create Navigation Menus?" </div>
<div class="sub_title qa">Q : How can i change the permalinks for products?</div>
<div class="answer qa">A : Go to <a href="admin.php?page=rt_product_options">RT-Theme Product Options</a>, edit "Category Slug" and "Single Product Slug"</div>
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Define a page as your Product page';
@$contents->step[$step_count]->contents[$content_count]->content =
'
Any page can be a product page also you can use the product categories in your menu. You all need to select "Default Product Template" for your page under the <b>"RT-Theme Template Options"</b> box. (<a href="'.$screenshotURL.'?image=template-options.png&preview_iframe=1&TB_iframe=true&" title="RT-Theme Screenshots" class="thickbox">Screenshot</a></li>)
<br />
You are also free to create new templates that suits your needs or customize the default one via <a href="admin.php?page=rt_template_options">Template Builder</a>
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Customize Default Product Template or Create one';
@$contents->step[$step_count]->contents[$content_count]->content =
'
<ol>
<li>Open Template Builder and expand "Default Product Template"</li>
<li>Expand "Product Posts" by clicking the plus icon on right-top corner of the module.</li>
<li>Change the options, add or remove new modules into the template.</li>
<li>Click save options icon on the right or "Save Options" button at the bottom of the page.</li>
</ol>
<br />
If you would like to learn how create a new template please read "How To Use Template Builder" section of the Setup Assistant.
';
#
# Step 5
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Create WooCommerce Shop';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Download WooCommerce';
@$contents->step[$step_count]->contents[$content_count]->content =
'
You can download WooCommerce plugin at <a href="http://wordpress.org/extend/plugins/woocommerce/" target="_new">Download →</a> <br /><br />
also available on <a href="http://www.woothemes.com/woocommerce/" target="_new">WooCommerce Official Website →</a> <br /><br />
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Learn How To Use WooCommerce';
@$contents->step[$step_count]->contents[$content_count]->content =
'
WooCommerce has rich documentation archive about the plugin. Go to <a href="http://wcdocs.woothemes.com/" target="_new">WooCommerce Documentation Website→</a>
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Change WooCommerce Settings';
@$contents->step[$step_count]->contents[$content_count]->content =
'
Find "WooCommerce" on the left hand side menu and click "Settings" from its sub menu.
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Change RT-Theme\'s WooCommerce Options';
@$contents->step[$step_count]->contents[$content_count]->content =
'
This theme offers some options for WooCommerce related contents such as "Layout", "Amount of products per page" etc. Go to <a href="admin.php?page=rt_woocommerce_options" target="">RT-Theme\'s WooCommerce Options →</a>
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Read These Notes!';
@$contents->step[$step_count]->contents[$content_count]->content =
'
<div class="sub_title qa">Q : How can I add WooCommerce Products into my templates?</div>
<div class="answer qa">A :
<ol>
<li>Open Template Builder and expand a template that you want to add the products.</li>
<li>Select "WooCommerce Products" from the module list.</li>
<li>Click save options icon on the right or "Save Options" button at the bottom of the page.</li>
</ol>
<br />
If you would like to learn how create a new template please read "How To Use Template Builder" section of the Setup Assistant.
</div>
<div class="sub_title qa">Q : What is the differencies between Product Showcase and WooCommerce Products?</div>
<div class="answer qa">A : They are completely different systems. You can use default "Product Showcase" to create an orginized product calatog. If you would like to
sell your products online via various payment systems, you should use WooCommerce. </div>
<div class="sub_title qa">Q : Can i move my existing products from Product Showcase to WooCommerce?</div>
<div class="answer qa">A : No, this is not possible. You need to create new products, categegories etc. by using the WooCommerce tools.</div>
';
#
# Step 6
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Create Slider';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Create Slider Contents';
@$contents->step[$step_count]->contents[$content_count]->content =
'
In order to provide more flexibility of slider usage, we created "Slider" custom post types.
You can create slider contents and save them and keep ready to use with any slider of the theme on any page template you want. <a href="post-new.php?post_type=slider">show me →</a> <br /><br />
<ul>
<li>Go to Slider → Add New</li>
<li>Use the fields under the "RT-THEME Slider Options" to create slide content.</li>
<li>Upload slide image by clicking the "Set featured image" link under the "Featured Image" box.
<a href="'.$screenshotURL.'?image=step_1_3_1.png&preview_iframe=1&TB_iframe=true&" title="RT-Theme Screenshots" class="thickbox">Screenshot 1</a>
<a href="'.$screenshotURL.'?image=step_1_3_2.png&preview_iframe=1&TB_iframe=true&" title="RT-Theme Screenshots" class="thickbox">Screenshot 2</a>
<a href="'.$screenshotURL.'?image=step_1_3_3.png&preview_iframe=1&TB_iframe=true&" title="RT-Theme Screenshots" class="thickbox">Screenshot 3</a>
</li>
</ul>
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Add a Slider to a Page';
@$contents->step[$step_count]->contents[$content_count]->content =
'
You can add a slider to any page or post you want via Template Builder by adding a Slider module.
<br /><br />
<div class="sub_title qa">Q : How can I add a slider to my home page?</div>
<div class="answer qa">A : Your home page is using the "Default Home Page Template" and it already contains a slider module if you have not removed. <br />
<ol>
<li>Go to Template Builder → Expand the "Default Home Page Template"</li>
<li>Expand the "Slider" module by clicking its plus icon on the right side</li>
<li>Change the options and follow screen instructions.</li>
<li>Click save options icon on the right or "Save Options" button at the bottom of the page.</li>
</ol>
</div>
<div class="sub_title qa">Q : How can I add a slider to any page or post?</div>
<div class="answer qa">A : Its same way to add on Home Page. You must use the Template Builder and add a slider module to your page template.</div>
';
#
# Step 7
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Build Home Page';
#
# Sub Titles
#
$content_count++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Create Home Page Contents';
@$contents->step[$step_count]->contents[$content_count]->content =
'
There are two ways to add a content on your home page. <br /><br />
<div class="sub_title list">Using Home Page Custom Posts</div>
<ul>
<li>We created "Home Page" custom post type to use a content with any page you want on your web site in a styled box with a featured image including your home page. <a href="edit.php?post_type=home_page">show me →</a></li>
<li>When you create a home page post and if you have not removed the "Home Page Contents" module from the "Default Home Page Template" it will be displayed on your home page automatically.</li>
<li>You can also select one of them and change it\'s order or column sizes by adding "Home Page Content" module into your page templates via the Template Builder.</li>
</ul>
<div class="sub_title list">Using Widgets</div>
<ul>
<li>You can use all widgets in any page you want including your home page.</li>
<li>Go Appearence → Widgets, drag&drop a widget into the "Widgetized Home Page Area" that you want to show on your home page.</li>
<li>Remember, you have too many options to customize their layouts and orders or use another widget area by customizing the "Default Home Page Template" via Template Builder.</li>
</ul>
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Customize Your Home Page';
@$contents->step[$step_count]->contents[$content_count]->content =
'
Your home page uses "Default Home Page Template" as its template, if you have not chaged your Reading settings and not defined another page as your home page! (Settings → Reading → Front page displays)
<br /><br />
<ul>
<li>Open Template Builder and expand "Default Home Page Template"</li>
<li>You will see there are some modules already added such as "Slider", "Home Page Contents" etc.</li>
<li>You can change options of the modules or add new modules as much as you need to create the home page you desired.</li>
<li>Click save options icon on the right or "Save Options" button at the bottom of the page.</li>
</ul>
<br />
If you would like to learn how create a new template please read "How To Use Template Builder" section of the Setup Assistant.
';
#
# Step 8
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Create Contact Page';
@$contents->step[$step_count]->single_step = 1;
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Define a page as your Contact page';
@$contents->step[$step_count]->contents[$content_count]->content =
'
Any page can be a contact page. You all need to select "Default Contact Page Template" for your page under the <b>"RT-Theme Template Options"</b> box. (<a href="'.$screenshotURL.'?image=template-options.png&preview_iframe=1&TB_iframe=true&" title="RT-Theme Screenshots" class="thickbox">Screenshot</a></li>)
<br />
You are also free to create new templates that suits your needs or customize the default one via <a href="admin.php?page=rt_template_options">Template Builder</a>
<br /> <br />
<div class="sub_title qa">Q : How can I customize "Default Contact Page Template" or create new one?</div>
<ol>
<li>Open Template Builder and expand "Default Contact Page Template"</li>
<li>Change the options of the modules or add/remove new modules into the template.</li>
<li>Click save options icon on the right or "Save Options" button at the bottom of the page.</li>
</ol>
<br />
If you would like to learn how create a new template please read "How To Use Template Builder" section of the Setup Assistant.
';
#
# Step 8
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Use Template Builder';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'What is Template Builder?';
@$contents->step[$step_count]->contents[$content_count]->content =
'
<a href="admin.php?page=rt_template_options">Template Builder</a> is a built-in tool that lets you create custom page templates to use with your pages or posts.
You are free to edit the default templates or create a new one as you wish.
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'How to use a template with a page or post?';
@$contents->step[$step_count]->contents[$content_count]->content =
'
<ol>
<li>Add/Edit a page or post.</li>
<li>Select a template name you want to use for your page under the <b>"RT-Theme Template Options"</b> <a href="'.$screenshotURL.'?image=template-options.png&preview_iframe=1&TB_iframe=true&" title="RT-Theme Screenshots" class="thickbox">Screenshot</a></li>
<li>Update your page/post.</li>
</ol>
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'How to create a new template?';
@$contents->step[$step_count]->contents[$content_count]->content =
'
<ol>
<li>Go to <a href="admin.php?page=rt_template_options">Template Builder</a></li>
<li>Expand "Create New Template" box at the bottom of the page.</li>
<li>Type a name for the template</li>
<li>Select a sidebar location or full width page layout</li>
<li>Start adding modules by using the "Module List"</li>
<li>Click "Create Template Button"</li>
</ol>
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Watch Video Tutorials?';
@$contents->step[$step_count]->contents[$content_count]->content =
'
<ol>
<li>You can find video tutorials about template builder inside the documentation file. </li>
<li>The documnetation file can be found in the /Documentation/ folder as index.html file, that comes with the theme package!</li>
</ol>
';
#
# Step 9
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Create Navigation Menus';
@$contents->step[$step_count]->single_step = 1;
@$contents->step[$step_count]->contents[$content_count]->content =
'
WordPress has a great tool to create navigation menus and this theme is using the menus as well.
You must use "RT Theme Main Navigation Menu" for the main navigation and "RT Theme Footer Navigation Menu" for the footer links.
<br /><br />
<div class="sub_title qa">Q : Where is the WordPress Menus??</div>
<div class="answer qa">A : Go to Appearence → <a href="nav-menus.php">Menus</a> </div>
<div class="sub_title qa">Q : How can I build a main navigation menu?</div>
<div class="answer qa">
<ol>
<li>Click "RT Theme Main Navigation Menu" tab. <a href="'.$screenshotURL.'?image=menus.jpg&preview_iframe=1&TB_iframe=true&" title="RT-Theme Screenshots" class="thickbox">Click here for the screenshot</a></li>
<li>Use the boxes on the left such as "Pages", "Posts" to add items to your menu.</li>
<li>Select an item from the boxes and click "Add to Menu" button of the box.</li>
<li>Drag and Move the menu item in the list.</li>
<li>Click "Save Menu" button.</li>
</ol>
</div>
<div class="sub_title qa">Q : How can I add portfolio or product categories to a menu?</div>
<div class="answer qa">
<ol>
<li>Click "Screen Options" tab on the top of the "<a href="nav-menus.php">Menus</a>" page.</li>
<li>Check the boxes of available cotents to make them visible on the left side as others.</li>
<li><a href="'.$screenshotURL.'?image=menus-screen-tab.png&preview_iframe=1&TB_iframe=true&" title="RT-Theme Screenshots" class="thickbox">Click here for the screenshot</a></li>
</ol>
</div>
<div class="sub_title qa">Q : How can I add a "Home Page" link?</div>
<div class="answer qa">
<ol>
<li>Use "Custom Links" box</li>
<li>Type your home page URL in the URL field.</li>
<li>Type "Home Page" or anything else that you want to call your home page in the "Label" field.</li>
<li>Click "Add to Menu" button.</li>
</ol>
</div>
';
#
# Step 9
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Use Widgets';
@$contents->step[$step_count]->single_step = 1;
@$contents->step[$step_count]->contents[$content_count]->content =
'
<ol>
<li>Go to Appearance → <a href="widgets.php">Widgets</a> </li>
<li>Choose a Widget and drag it to the sidebar where you wish it to appear. There are default sidebars for the theme or you can create custom one for a specific content group by using "<a href="admin.php?page=rt_sidebar_options">Sidebar Creator</a>"
<li>To arrange the Widgets within the sidebar or Widget area, click and drag it into place.</li>
<li>To customize the Widget features, click the down arrow in the upper right corner to expand the Widget\'s interface.</li>
<li>To save the Widget\'s customization, click Save.</li>
<li>To remove the Widget, click Remove or Delete.</li>
</ol>
<div class="sub_title qa">Q : How can I add a "Home Page" link?</div>
<div class="answer qa">
<ol>
<li>Use "Custom Links" box</li>
<li>Type your home page URL in the URL field.</li>
<li>Type "Home Page" or anything else that you want to call your home page in the "Label" field.</li>
<li>Click "Add to Menu" button.</li>
</ol>
</div>
';
#
# Step
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Change Backgrouds';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Change background of entire website';
@$contents->step[$step_count]->contents[$content_count]->content =
'
Use "Background Options" from the theme options panel to control background of entire website. <a href="admin.php?page=rt_background_options">show me →</a> <br /><br />
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Change background of an individual page';
@$contents->step[$step_count]->contents[$content_count]->content =
'
You can find individual background options for each page in their "Edit" sections.
For example if you would like to edit your "About Us" page\'s background.
Go to Pages → click "About Us" to edit → and scroll down to find "RT-Theme Background Options"
';
#
# Step
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Change Header Images';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Change header of entire website';
@$contents->step[$step_count]->contents[$content_count]->content =
'
Use "Header Options" from the theme options panel to control header of entire website. <a href="admin.php?page=rt_header_options">show me →</a> <br /><br />
';
$content_count ++;
@$contents->step[$step_count]->contents[$content_count]->content_title = 'Change header of an individual page';
@$contents->step[$step_count]->contents[$content_count]->content =
'
You can find individual header options for each page in their "Edit" sections.
For example if you would like to edit your "About Us" page\'s header.
Go to Pages → click "About Us" to edit → and scroll down to find "RT-Theme Header Options"
';
#
# Step 10
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Use Shortcodes and Quick Styling Buttons';
@$contents->step[$step_count]->single_step = 1;
@$contents->step[$step_count]->contents[$content_count]->content =
'
RT-Theme comes with some great shortcodes that allow you to add photo galleries, contact forms, tabs, etc. In order to use them, you need to edit/add posts, pages or widgets and enter the shorcodes into the content area.
You can find all the shortcodes and quick styling buttons on the the Visual view mode of the editor. <a href="'.$screenshotURL.'?image=shortcodes.png&preview_iframe=1&TB_iframe=true&" title="RT-Theme Screenshots" class="thickbox">Screenshot</a>
';
#
# Step 10
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Add Twitter, Flickr, Recent Pots etc.';
@$contents->step[$step_count]->single_step = 1;
@$contents->step[$step_count]->contents[$content_count]->content =
'
RT-Theme comes with built-in widgets that coded for the theme. You can find them on the <a href="widgets.php">Widgets</a> page.
For example; If you would like to add your recent tweets drag "[RT-Theme] Twitter" widget and drop a widget area that you want to display.
';
#
# Step 11
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Create Footer Navigation';
@$contents->step[$step_count]->single_step = 1;
@$contents->step[$step_count]->contents[$content_count]->content =
'
Please read "How To Create Navigation Menus" section.
';
#
# Step 12
#
$step_count++;
@$contents->step[$step_count]->number = "How To";
@$contents->step[$step_count]->title = 'Use Sidebar Creator';
@$contents->step[$step_count]->single_step = 1;
@$contents->step[$step_count]->contents[$content_count]->content =
'
This tool gives you chance to create custom sidebars (widget areas) for your web site\'s specific contents only.
<br />
For example: If you would like to put a Text Widget (or anyone) only for your About Us and Contact Us pages;<br />
<ul>
<li>Go to <a href="admin.php?page=rt_sidebar_options">Sidebar Creator</a></li>
<li>Expand "Create New Sidebar" box</li>
<li>Type a name for your custom sidebar</li>
<li>Select the pages or other available cotennts you want to diplay widgets of the sidebar</li>
<li>Click "Create Sidebar" button.</li>
</ul>
Once you created your custom sidebar you will see it in the available sidebar list on the Widgets page.
';
echo '<div id="rt_setup_assistant">';
foreach($contents->step as $key=>$value){
#
# step container
#
echo '<div class="rt_step"><div class="rt_s_number">'.$contents->step[$key]->number.'</div>'.$contents->step[$key]->title.'<div class="expand plus"></div></div>';
echo '<div class="step_contents">';
$content_number = 1;
foreach ($contents->step[$key]->contents as $contentID => $theContent) {
if(!isset($contents->step[$key]->single_step)) echo '<div class="step_content">'.($theContent->content_title).' <span class="step_number">Step '.$content_number.' </span> </div>';
echo (!isset($contents->step[$key]->single_step)) ? '<div class="step_content_hidden">' : '<div class="step_content_hidden show">';
echo $theContent->content.'</div>';
$content_number++;
}
echo '</div>';
}
echo '</div>';
}
}
$RTSetupAssistant = new RTSetupAssistant();
?> | cphillipp/flymebusiness | wp-content/themes/rttheme17/rt-framework/classes/rt_setup_assistant.php | PHP | gpl-2.0 | 35,011 |
<?php
/**
* The file that defines the core plugin class
*
* A class definition that includes attributes and functions used across both the
* public-facing side of the site and the dashboard.
*
* @link http://www.flowdee.de
* @since 1.0.0
*
* @package Blueposts
* @subpackage Blueposts/includes
*/
/**
* The core plugin class.
*
* This is used to define internationalization, dashboard-specific hooks, and
* public-facing site hooks.
*
* Also maintains the unique identifier of this plugin as well as the current
* version of the plugin.
*
* @since 1.0.0
* @package Blueposts
* @subpackage Blueposts/includes
* @author flowdee <support@flowdee.de>
*/
class Blueposts {
/**
* The loader that's responsible for maintaining and registering all hooks that power
* the plugin.
*
* @since 1.0.0
* @access protected
* @var Blueposts_Loader $loader Maintains and registers all hooks for the plugin.
*/
protected $loader;
/**
* The unique identifier of this plugin.
*
* @since 1.0.0
* @access protected
* @var string $Blueposts The string used to uniquely identify this plugin.
*/
protected $Blueposts;
/**
* The current version of the plugin.
*
* @since 1.0.0
* @access protected
* @var string $version The current version of the plugin.
*/
protected $version;
/**
* Define the core functionality of the plugin.
*
* Set the plugin name and the plugin version that can be used throughout the plugin.
* Load the dependencies, define the locale, and set the hooks for the Dashboard and
* the public-facing side of the site.
*
* @since 1.0.0
*/
public function __construct() {
$this->Blueposts = 'blueposts';
$this->version = '1.0.0';
$this->load_dependencies();
$this->set_locale();
$this->define_admin_hooks();
$this->define_public_hooks();
$this->register_shortcodes();
}
/**
* Load the required dependencies for this plugin.
*
* Include the following files that make up the plugin:
*
* - Blueposts_Loader. Orchestrates the hooks of the plugin.
* - Blueposts_i18n. Defines internationalization functionality.
* - Blueposts_Admin. Defines all hooks for the dashboard.
* - Blueposts_Public. Defines all hooks for the public side of the site.
*
* Create an instance of the loader which will be used to register the hooks
* with WordPress.
*
* @since 1.0.0
* @access private
*/
private function load_dependencies() {
/**
* The class responsible for orchestrating the actions and filters of the
* core plugin.
*/
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-blueposts-loader.php';
/**
* The class responsible for defining internationalization functionality
* of the plugin.
*/
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-blueposts-i18n.php';
/**
* The class responsible for defining all actions that occur in the Dashboard.
*/
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/class-blueposts-admin.php';
/**
* The class responsible for defining all actions that occur in the public-facing
* side of the site.
*/
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'public/class-blueposts-public.php';
/**
* The class responsible for initializing the plugin shortcodes
*/
require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-blueposts-shortcodes.php';
$this->loader = new Blueposts_Loader();
}
/**
* Define the locale for this plugin for internationalization.
*
* Uses the Blueposts_i18n class in order to set the domain and to register the hook
* with WordPress.
*
* @since 1.0.0
* @access private
*/
private function set_locale() {
$plugin_i18n = new Blueposts_i18n();
$plugin_i18n->set_domain( $this->get_Blueposts() );
$this->loader->add_action( 'plugins_loaded', $plugin_i18n, 'load_plugin_textdomain' );
}
/**
* Register all of the hooks related to the dashboard functionality
* of the plugin.
*
* @since 1.0.0
* @access private
*/
private function define_admin_hooks() {
$plugin_admin = new Blueposts_Admin( $this->get_Blueposts(), $this->get_version() );
$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_styles' );
$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts' );
}
/**
* Register all of the hooks related to the public-facing functionality
* of the plugin.
*
* @since 1.0.0
* @access private
*/
private function define_public_hooks() {
$plugin_public = new Blueposts_Public( $this->get_Blueposts(), $this->get_version() );
$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_styles' );
$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_scripts' );
}
/**
* Register all of the plugin's shortcodes
* of the plugin.
*
* @since 1.0.0
* @access private
*/
private function register_shortcodes() {
$plugin_shortcodes = new Blueposts_Shortcodes( $this->get_Blueposts(), $this->get_version() );
}
/**
* Run the loader to execute all of the hooks with WordPress.
*
* @since 1.0.0
*/
public function run() {
$this->loader->run();
}
/**
* The name of the plugin used to uniquely identify it within the context of
* WordPress and to define internationalization functionality.
*
* @since 1.0.0
* @return string The name of the plugin.
*/
public function get_Blueposts() {
return $this->Blueposts;
}
/**
* The reference to the class that orchestrates the hooks with the plugin.
*
* @since 1.0.0
* @return Blueposts_Loader Orchestrates the hooks of the plugin.
*/
public function get_loader() {
return $this->loader;
}
/**
* Retrieve the version number of the plugin.
*
* @since 1.0.0
* @return string The version number of the plugin.
*/
public function get_version() {
return $this->version;
}
}
| flowdee/blueposts-for-wordpress | includes/class-blueposts.php | PHP | gpl-2.0 | 6,072 |
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package test.robot.test3d;
import javafx.application.ConditionalFeature;
import javafx.application.Platform;
import javafx.scene.AmbientLight;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.SceneAntialiasing;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.CullFace;
import javafx.scene.shape.DrawMode;
import javafx.scene.shape.MeshView;
import javafx.scene.shape.TriangleMesh;
import javafx.stage.Stage;
import org.junit.Test;
import test.robot.testharness.VisualTestBase;
public class AABalanceFlipTest extends VisualTestBase {
private Stage testStage;
private Scene testScene;
private static final double TOLERANCE = 0.07;
WritableImage selfIllumMap;
@Test(timeout = 5000)
public void testAABalanceFlip() {
final int WIDTH = 800;
final int HEIGHT = 800;
selfIllumMap = new WritableImage(64, 64);
PixelWriter pWriter = selfIllumMap.getPixelWriter();
setArgb(pWriter, 0, 32, 0, 32, 0Xff000000);
setArgb(pWriter, 32, 64, 0, 32, 0Xffffffff);
setArgb(pWriter, 0, 32, 32, 64, 0Xffffffff);
setArgb(pWriter, 32, 64, 32, 64, 0Xff000000);
runAndWait(() -> {
testScene = buildScene(WIDTH, HEIGHT, true);
testScene.setFill(Color.rgb(10, 10, 40));
addCamera(testScene);
testStage = getStage();
testStage.setTitle("SceneAntialiasing.BALANCED Flip Test");
testStage.setScene(testScene);
testStage.show();
});
waitFirstFrame();
runAndWait(() -> {
if (!Platform.isSupported(ConditionalFeature.SCENE3D)) {
System.out.println("*************************************************************");
System.out.println("* Platform isn't SCENE3D capable, skipping 3D test. *");
System.out.println("*************************************************************");
return;
}
Color color;
Color blackColor = new Color(0, 0, 0, 1);
Color whiteColor = new Color(1, 1, 1, 1);
color = getColor(testScene, WIDTH / 4, HEIGHT / 4);
assertColorEquals(blackColor, color, TOLERANCE);
color = getColor(testScene, (WIDTH - 100), HEIGHT / 4);
assertColorEquals(whiteColor, color, TOLERANCE);
color = getColor(testScene, WIDTH / 4, HEIGHT - 100);
assertColorEquals(whiteColor, color, TOLERANCE);
color = getColor(testScene, WIDTH - 100, HEIGHT - 100);
assertColorEquals(blackColor, color, TOLERANCE);
});
}
/**
* **** Scene and Mesh Setup ********
*/
Group root;
MeshView meshView;
TriangleMesh triMesh;
PhongMaterial material;
int divX = 8;
int divY = 8;
static final float MESH_SCALE = 20;
static final float MIN_X = -20;
static final float MIN_Y = -20;
static final float MAX_X = 20;
static final float MAX_Y = 20;
private TriangleMesh buildTriangleMesh(int subDivX, int subDivY,
float scale) {
final int pointSize = 3;
final int texCoordSize = 2;
final int faceSize = 6; // 3 point indices and 3 texCoord indices per triangle
int numDivX = subDivX + 1;
int numVerts = (subDivY + 1) * numDivX;
float points[] = new float[numVerts * pointSize];
float texCoords[] = new float[numVerts * texCoordSize];
int faceCount = subDivX * subDivY * 2;
int faces[] = new int[faceCount * faceSize];
// Create points and texCoords
for (int y = 0; y <= subDivY; y++) {
float dy = (float) y / subDivY;
double fy = (1 - dy) * MIN_Y + dy * MAX_Y;
for (int x = 0; x <= subDivX; x++) {
float dx = (float) x / subDivX;
double fx = (1 - dx) * MIN_X + dx * MAX_X;
int index = y * numDivX * pointSize + (x * pointSize);
points[index] = (float) fx * scale;
points[index + 1] = (float) fy * scale;
points[index + 2] = (float) 0.0;
index = y * numDivX * texCoordSize + (x * texCoordSize);
texCoords[index] = dx * subDivX / 8;
texCoords[index + 1] = dy * subDivY / 8;
}
}
// Create faces
for (int y = 0; y < subDivY; y++) {
for (int x = 0; x < subDivX; x++) {
int p00 = y * numDivX + x;
int p01 = p00 + 1;
int p10 = p00 + numDivX;
int p11 = p10 + 1;
int tc00 = y * numDivX + x;
int tc01 = tc00 + 1;
int tc10 = tc00 + numDivX;
int tc11 = tc10 + 1;
int index = (y * subDivX * faceSize + (x * faceSize)) * 2;
faces[index + 0] = p00;
faces[index + 1] = tc00;
faces[index + 2] = p10;
faces[index + 3] = tc10;
faces[index + 4] = p11;
faces[index + 5] = tc11;
index += faceSize;
faces[index + 0] = p11;
faces[index + 1] = tc11;
faces[index + 2] = p01;
faces[index + 3] = tc01;
faces[index + 4] = p00;
faces[index + 5] = tc00;
}
}
TriangleMesh triangleMesh = new TriangleMesh();
triangleMesh.getPoints().setAll(points);
triangleMesh.getTexCoords().setAll(texCoords);
triangleMesh.getFaces().setAll(faces);
return triangleMesh;
}
private Scene buildScene(int width, int height, boolean depthBuffer) {
triMesh = buildTriangleMesh(divX, divY, MESH_SCALE);
material = new PhongMaterial();
material.setSelfIlluminationMap(selfIllumMap);
meshView = new MeshView(triMesh);
meshView.setMaterial(material);
//Set Wireframe mode
meshView.setDrawMode(DrawMode.FILL);
meshView.setCullFace(CullFace.BACK);
final Group grp = new Group(meshView);
grp.setTranslateX(400);
grp.setTranslateY(400);
grp.setTranslateZ(10);
root = new Group(grp, new AmbientLight(Color.BLACK));
Scene scene = new Scene(root, width, height, depthBuffer, SceneAntialiasing.BALANCED);
return scene;
}
private PerspectiveCamera addCamera(Scene scene) {
PerspectiveCamera perspectiveCamera = new PerspectiveCamera();
scene.setCamera(perspectiveCamera);
return perspectiveCamera;
}
private void setArgb(PixelWriter pWriter,
int startX, int endX, int startY, int endY, int value) {
for (int x = startX; x < endX; x++) {
for (int y = startY; y < endY; y++) {
pWriter.setArgb(x, y, value);
}
}
}
}
| teamfx/openjfx-10-dev-rt | tests/system/src/test/java/test/robot/test3d/AABalanceFlipTest.java | Java | gpl-2.0 | 8,301 |
/*
* see license.txt
*/
package seventh.ai.basic.teamstrategy;
import seventh.ai.basic.Brain;
import seventh.ai.basic.DefaultAISystem;
import seventh.ai.basic.actions.Action;
import seventh.ai.basic.actions.WaitAction;
import seventh.game.GameInfo;
import seventh.game.PlayerInfo;
import seventh.game.Team;
import seventh.game.type.ObjectiveGameType;
import seventh.shared.TimeStep;
/**
* Handles the objective based game type.
*
* @author Tony
*
*/
public class ObjectiveTeamStrategy implements TeamStrategy {
private Team team;
private TeamStrategy strategy;
private DefaultAISystem aiSystem;
/**
*
*/
public ObjectiveTeamStrategy(DefaultAISystem aiSystem, Team team) {
this.aiSystem = aiSystem;
this.team = team;
}
/* (non-Javadoc)
* @see seventh.ai.basic.teamstrategy.TeamStrategy#getDesirability(seventh.ai.basic.Brain)
*/
@Override
public double getDesirability(Brain brain) {
if(strategy!=null) {
return strategy.getDesirability(brain);
}
return 0;
}
/* (non-Javadoc)
* @see seventh.ai.basic.teamstrategy.TeamStrategy#getGoal(seventh.ai.basic.Brain)
*/
@Override
public Action getAction(Brain brain) {
if(strategy!=null) {
return strategy.getAction(brain);
}
return new WaitAction(1000);
}
/* (non-Javadoc)
* @see seventh.ai.basic.teamstrategy.TeamStrategy#getTeam()
*/
@Override
public Team getTeam() {
return this.team;
}
/* (non-Javadoc)
* @see seventh.ai.AIGameTypeStrategy#startOfRound(seventh.game.Game)
*/
@Override
public void startOfRound(GameInfo game) {
ObjectiveGameType gameType = (ObjectiveGameType) game.getGameType();
if( gameType.getAttacker().getId() == this.team.getId() ) {
strategy = new OffenseObjectiveTeamStrategy(this.aiSystem, team);
}
else {
strategy = new DefenseObjectiveTeamStrategy(this.aiSystem, team);
}
strategy.startOfRound(game);
}
/* (non-Javadoc)
* @see seventh.ai.AIGameTypeStrategy#endOfRound(seventh.game.Game)
*/
@Override
public void endOfRound(GameInfo game) {
if(strategy!=null) {
strategy.endOfRound(game);
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.AIGameTypeStrategy#playerKilled(seventh.game.PlayerInfo)
*/
@Override
public void playerKilled(PlayerInfo player) {
if(strategy != null) {
strategy.playerKilled(player);
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.AIGameTypeStrategy#playerSpawned(seventh.game.PlayerInfo)
*/
@Override
public void playerSpawned(PlayerInfo player) {
if(strategy != null) {
strategy.playerSpawned(player);
}
}
/* (non-Javadoc)
* @see seventh.ai.AIGameTypeStrategy#update(seventh.shared.TimeStep, seventh.game.Game)
*/
@Override
public void update(TimeStep timeStep, GameInfo game) {
if(strategy!=null) {
strategy.update(timeStep, game);
}
}
/* (non-Javadoc)
* @see seventh.shared.Debugable#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation me = new DebugInformation();
me.add("strategy", this.strategy);
return me;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDebugInformation().toString();
}
}
| skaghzz/seventh | src/seventh/ai/basic/teamstrategy/ObjectiveTeamStrategy.java | Java | gpl-2.0 | 3,692 |
# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from dialogBase import GdalToolsBaseDialog as BaseDialog
import GdalTools_utils as Utils
class GdalToolsBasePluginWidget:
def __init__(self, iface, commandName, helpFileBaseName = None, parent = None):
self.base = BaseDialog(parent, iface, self, self.windowTitle(), commandName)
self.connect(self.base, SIGNAL("processError(QProcess::ProcessError)"), self.onError)
self.connect(self.base, SIGNAL("processFinished(int, QProcess::ExitStatus)"), self.onFinished)
self.connect(self.base, SIGNAL("okClicked()"), self.onRun)
self.connect(self.base, SIGNAL("closeClicked()"), self.onClosing)
self.connect(self.base, SIGNAL("helpClicked()"), self.onHelp)
self.connect(self.base, SIGNAL("finished(bool)"), self.finished)
def someValueChanged(self):
self.emit(SIGNAL("valuesChanged(const QStringList &)"), self.getArguments())
def exec_(self):
self.someValueChanged()
return self.base.exec_()
def show_(self):
self.someValueChanged()
return self.base.show()
def setCommandViewerEnabled(self, enable):
self.base.setCommandViewerEnabled(enable)
self.someValueChanged()
def onRun(self):
self.base.onRun()
def onClosing(self):
self.base.onClosing()
def onHelp(self):
self.base.onHelp()
def onFinished(self, exitCode, status):
self.base.onFinished(exitCode, status)
def onError(self, error):
self.base.onError(error)
def getArguments(self):
pass
def getInputFileName(self):
pass
def getOutputFileName(self):
pass
def addLayerIntoCanvas(self, fileInfo):
pass
def finished(self, load):
outFn = self.getOutputFileName()
if outFn == None:
return
outFn = QString(outFn)
if outFn.isEmpty():
QMessageBox.warning(self, self.tr( "Warning" ), self.tr( "No output file created." ) )
return
fileInfo = QFileInfo(outFn)
if fileInfo.exists():
if load:
self.addLayerIntoCanvas(fileInfo)
QMessageBox.information(self, self.tr( "Finished" ), self.tr( "Elaboration completed." ) )
else:
QMessageBox.warning(self, self.tr( "Warning" ), self.tr( "%1 not created." ).arg( outFn ) )
# This method is useful to set up options for the command. It sets for each passed widget:
# 1. its passed signals to connect to the BasePluginWidget.someValueChanged() slot,
# 2. its enabler checkbox or enabled status,
# 3. its status as visible (hide) if the installed gdal version is greater or equal (lesser) then the passed version
#
# wdgts_sgnls_chk_ver_list: list of wdgts_sgnls_chk_ver
# wdgts_sgnls_chk_ver: tuple containing widgets, signals, enabler checkbox or enabled status, required version
def setParamsStatus(self, wdgts_sgnls_chk_ver_list):
if isinstance(wdgts_sgnls_chk_ver_list, list):
for wdgts_sgnls_chk_ver in wdgts_sgnls_chk_ver_list:
self.setParamsStatus(wdgts_sgnls_chk_ver)
return
wdgts_sgnls_chk_ver = wdgts_sgnls_chk_ver_list
if not isinstance(wdgts_sgnls_chk_ver, tuple):
return
if len(wdgts_sgnls_chk_ver) > 0:
wdgts = wdgts_sgnls_chk_ver[0]
else:
wdgts = None
if len(wdgts_sgnls_chk_ver) > 1:
sgnls = wdgts_sgnls_chk_ver[1]
else:
sgnls = None
if len(wdgts_sgnls_chk_ver) > 2:
chk = wdgts_sgnls_chk_ver[2]
else:
chk = None
if len(wdgts_sgnls_chk_ver) > 3:
ver = wdgts_sgnls_chk_ver[3]
else:
ver = None
if isinstance(wdgts, list):
for wdgt in wdgts:
self.setParamsStatus((wdgt, sgnls, chk, ver))
return
wdgt = wdgts
if not isinstance(wdgt, QWidget):
return
# if check version fails, disable the widget then hide both it and its enabler checkbox
if ver != None:
if not isinstance(ver, Utils.Version):
ver = Utils.Version(ver)
gdalVer = Utils.GdalConfig.version()
if gdalVer != None and ver > gdalVer:
wdgt.setVisible(False)
if isinstance(chk, QWidget):
chk.setVisible(False)
chk.setChecked(False)
sgnls = None
chk = False
# connects the passed signals to the BasePluginWidget.someValueChanged slot
if isinstance(sgnls, list):
for sgnl in sgnls:
self.setParamsStatus((wdgt, sgnl, chk))
return
sgnl = sgnls
if sgnl != None:
self.connect(wdgt, sgnl, self.someValueChanged)
# set the passed checkbox as widget enabler
if isinstance(chk, bool):
wdgt.setEnabled(chk)
if ( isinstance(chk, QAbstractButton) or isinstance(chk, QGroupBox) ) and \
chk.isCheckable():
wdgt.setEnabled(chk.isChecked())
self.connect(chk, SIGNAL("toggled(bool)"), wdgt.setEnabled)
self.connect(chk, SIGNAL("toggled(bool)"), self.someValueChanged)
| sourcepole/qgis | qgis/python/plugins/GdalTools/tools/widgetPluginBase.py | Python | gpl-2.0 | 5,083 |
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/**
* Template Post
*
* Access original fields: $mod_settings
* @author Themify
*/
$fields_default = array(
'mod_title_post' => '',
'layout_post' => '',
'category_post' => '',
'post_per_page_post' => '',
'offset_post' => '',
'order_post' => 'desc',
'orderby_post' => 'date',
'display_post' => 'content',
'hide_feat_img_post' => 'no',
'image_size_post' => '',
'img_width_post' => '',
'img_height_post' => '',
'unlink_feat_img_post' => 'no',
'hide_post_title_post' => 'no',
'unlink_post_title_post' => 'no',
'hide_post_date_post' => 'no',
'hide_post_meta_post' => 'no',
'hide_page_nav_post' => 'yes',
'animation_effect' => '',
'css_post' => ''
);
if ( isset( $mod_settings['category_post'] ) )
$mod_settings['category_post'] = $this->get_param_value( $mod_settings['category_post'] );
$fields_args = wp_parse_args( $mod_settings, $fields_default );
extract( $fields_args, EXTR_SKIP );
$animation_effect = $this->parse_animation_effect( $animation_effect );
$container_class = implode(' ',
apply_filters('themify_builder_module_classes', array(
'module', 'module-' . $mod_name, $module_ID, 'loops-wrapper', 'clearfix', $css_post, $layout_post
) )
);
$this->add_post_class( $animation_effect );
?>
<!-- module post -->
<div id="<?php echo $module_ID; ?>" class="<?php echo esc_attr( $container_class ); ?>">
<?php if ( $mod_title_post != '' ): ?>
<h3 class="module-title"><?php echo $mod_title_post; ?></h3>
<?php endif; ?>
<?php
do_action( 'themify_builder_before_template_content_render' );
// The Query
global $paged, $wp;
$order = $order_post;
$orderby = $orderby_post;
$paged = $this->get_paged_query();
$limit = $post_per_page_post;
$terms = $category_post;
$temp_terms = explode(',', $terms);
$new_terms = array();
$is_string = false;
foreach ( $temp_terms as $t ) {
if ( ! is_numeric( $t ) )
$is_string = true;
if ( '' != $t ) {
array_push( $new_terms, trim( $t ) );
}
}
$tax_field = ( $is_string ) ? 'slug' : 'id';
$args = array(
'post_status' => 'publish',
'posts_per_page' => $limit,
'order' => $order,
'orderby' => $orderby,
'suppress_filters' => false,
'paged' => $paged
);
if ( count($new_terms) > 0 && ! in_array('0', $new_terms) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => $tax_field,
'terms' => $new_terms,
'operator' => ( '-' == substr( $terms, 0, 1 ) ) ? 'NOT IN' : 'IN',
)
);
}
// check if theme loop template exists
$is_theme_template = $this->is_loop_template_exist('loop.php', 'includes');
// add offset posts
if ( $offset_post != '' ) {
if ( empty( $limit ) )
$limit = get_option('posts_per_page');
$args['offset'] = ( ( $paged - 1 ) * $limit ) + $offset_post;
}
$the_query = new WP_Query();
$posts = $the_query->query($args);
// use theme template loop
if ( $is_theme_template ) {
// save a copy
global $themify;
$themify_save = clone $themify;
// override $themify object
$themify->hide_image = $hide_feat_img_post;
$themify->unlink_image = $unlink_feat_img_post;
$themify->hide_title = $hide_post_title_post;
$themify->width = $img_width_post;
$themify->height = $img_height_post;
$themify->image_setting = 'ignore=true&';
if ( $this->is_img_php_disabled() )
$themify->image_setting .= $image_size_post != '' ? 'image_size=' . $image_size_post . '&' : '';
$themify->unlink_title = $unlink_post_title_post;
$themify->display_content = $display_post;
$themify->hide_date = $hide_post_date_post;
$themify->hide_meta = $hide_post_meta_post;
$themify->post_layout = $layout_post;
// hooks action
do_action_ref_array('themify_builder_override_loop_themify_vars', array( $themify, $mod_name ) );
$out = '';
if ($posts) {
$out .= themify_get_shortcode_template($posts);
}
// revert to original $themify state
$themify = clone $themify_save;
echo $out;
} else {
// use builder template
global $post;
foreach($posts as $post): setup_postdata( $post ); ?>
<?php themify_post_before(); // hook ?>
<article id="post-<?php the_ID(); ?>" <?php post_class("post clearfix"); ?>>
<?php themify_post_start(); // hook ?>
<?php
if ( $hide_feat_img_post != 'yes' ) {
$width = $img_width_post;
$height = $img_height_post;
$param_image = 'w='.$width .'&h='.$height.'&ignore=true';
if ( $this->is_img_php_disabled() )
$param_image .= $image_size_post != '' ? '&image_size=' . $image_size_post : '';
//check if there is a video url in the custom field
if( themify_get('video_url') != '' ){
global $wp_embed;
themify_before_post_image(); // Hook
echo $wp_embed->run_shortcode('[embed]' . themify_get('video_url') . '[/embed]');
themify_after_post_image(); // Hook
} elseif ( $post_image = themify_get_image( $param_image ) ) {
themify_before_post_image(); // Hook ?>
<figure class="post-image">
<?php if ( $unlink_feat_img_post == 'yes' ): ?>
<?php echo $post_image; ?>
<?php else: ?>
<a href="<?php echo themify_get_featured_image_link(); ?>"><?php echo $post_image; ?></a>
<?php endif; ?>
</figure>
<?php themify_after_post_image(); // Hook
}
}
?>
<div class="post-content">
<?php if ( $hide_post_date_post != 'yes' ): ?>
<time datetime="<?php the_time('o-m-d') ?>" class="post-date" pubdate><?php the_time(apply_filters('themify_loop_date', 'M j, Y')) ?></time>
<?php endif; //post date ?>
<?php if ( $hide_post_title_post != 'yes' ): ?>
<?php themify_before_post_title(); // Hook ?>
<?php if ( $unlink_post_title_post == 'yes' ): ?>
<h1 class="post-title"><?php the_title(); ?></h1>
<?php else: ?>
<h1 class="post-title"><a href="<?php echo themify_get_featured_image_link(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h1>
<?php endif; //unlink post title ?>
<?php themify_after_post_title(); // Hook ?>
<?php endif; //post title ?>
<?php if ( $hide_post_meta_post != 'yes' ): ?>
<p class="post-meta">
<span class="post-author"><?php the_author_posts_link() ?></span>
<span class="post-category"><?php the_category(', ') ?></span>
<?php the_tags(' <span class="post-tag">', ', ', '</span>'); ?>
<?php if( !themify_get('setting-comments_posts') && comments_open() ) : ?>
<span class="post-comment"><?php comments_popup_link( __( '0 Comments', 'themify' ), __( '1 Comment', 'themify' ), __( '% Comments', 'themify' ) ); ?></span>
<?php endif; //post comment ?>
</p>
<?php endif; //post meta ?>
<?php
// fix the issue more link doesn't output
global $more;
$more = 0;
?>
<?php if ( $display_post == 'excerpt' ): ?>
<?php the_excerpt(); ?>
<?php elseif ( $display_post == 'none' ): ?>
<?php else: ?>
<?php the_content(themify_check('setting-default_more_text')? themify_get('setting-default_more_text') : __('More →', 'themify')); ?>
<?php endif; //display content ?>
<?php edit_post_link(__('Edit', 'themify'), '[', ']'); ?>
</div>
<!-- /.post-content -->
<?php themify_post_end(); // hook ?>
</article>
<?php themify_post_after(); // hook ?>
<?php endforeach; wp_reset_postdata(); ?>
<?php
} // end $is_theme_template
if ( $hide_page_nav_post != 'yes' ) {
echo $this->get_pagenav('', '', $the_query);
}
?>
<?php do_action( 'themify_builder_after_template_content_render' ); $this->remove_post_class( $animation_effect ); ?>
</div>
<!-- /module post --> | TakenCdosG/ella-live | wp-content/themes/simfo-revision-2/themify/themify-builder/templates/template-post.php | PHP | gpl-2.0 | 7,728 |
<?php
/*
+---------------------------------------------------------------------------+
| OpenX v2.8 |
| ========== |
| |
| Copyright (c) 2003-2009 OpenX Limited |
| For contact details, see: http://www.openx.org/ |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by |
| the Free Software Foundation; either version 2 of the License, or |
| (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
| |
| You should have received a copy of the GNU General Public License |
| along with this program; if not, write to the Free Software |
| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
+---------------------------------------------------------------------------+
$Id: agency-user.php 81772 2012-09-11 00:07:29Z chris.nutting $
*/
// Require the initialisation file
require_once '../../init.php';
// Required files
require_once MAX_PATH . '/www/admin/config.php';
require_once MAX_PATH . '/www/admin/lib-statistics.inc.php';
require_once MAX_PATH . '/lib/OA/Session.php';
require_once MAX_PATH . '/lib/OA/Admin/UI/UserAccess.php';
require_once MAX_PATH . '/lib/max/other/html.php';
OA_Permission::enforceAccount(OA_ACCOUNT_ADMIN, OA_ACCOUNT_MANAGER);
OA_Permission::enforceAccountPermission(OA_ACCOUNT_MANAGER, OA_PERM_SUPER_ACCOUNT);
OA_Permission::enforceAccessToObject('agency', $agencyid);
$userAccess = new OA_Admin_UI_UserAccess();
$userAccess->init();
function OA_HeaderNavigation()
{
global $agencyid;
if (OA_Permission::isAccount(OA_ACCOUNT_ADMIN)) {
phpAds_PageHeader("agency-access");
$doAgency = OA_Dal::staticGetDO('agency', $agencyid);
MAX_displayInventoryBreadcrumbs(array(array("name" => $doAgency->name)), "agency");
} else {
phpAds_PageHeader("agency-user");
}
}
$userAccess->setNavigationHeaderCallback('OA_HeaderNavigation');
$accountId = OA_Permission::getAccountIdForEntity('agency', $agencyid);
$userAccess->setAccountId($accountId);
$userAccess->setPagePrefix('agency');
$aAllowedPermissions = array();
if (OA_Permission::hasPermission(OA_PERM_SUPER_ACCOUNT, $accountId)) {
$aAllowedPermissions[OA_PERM_SUPER_ACCOUNT] = array($strAllowCreateAccounts, false);
}
$userAccess->setAllowedPermissions($aAllowedPermissions);
$userAccess->setHiddenFields(array('agencyid' => $agencyid));
$userAccess->setRedirectUrl('agency-access.php?agencyid='.$agencyid);
$userAccess->setBackUrl('agency-user-start.php?agencyid='.$agencyid);
$userAccess->process();
?>
| webonise/openx | www/admin/agency-user.php | PHP | gpl-2.0 | 3,420 |
/*
* Copyright (c) 2008, Willow Garage, Inc.
* 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 Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <OgreSceneNode.h>
#include <OgreSceneManager.h>
#include <urdf/model.h>
#include <tf/transform_listener.h>
#include "rviz/display_context.h"
#include "rviz/robot/robot.h"
#include "rviz/robot/tf_link_updater.h"
#include "rviz/properties/float_property.h"
#include "rviz/properties/property.h"
#include "rviz/properties/string_property.h"
#include "robot_model_display.h"
namespace rviz
{
void linkUpdaterStatusFunction( StatusProperty::Level level,
const std::string& link_name,
const std::string& text,
RobotModelDisplay* display )
{
display->setStatus( level, QString::fromStdString( link_name ), QString::fromStdString( text ));
}
RobotModelDisplay::RobotModelDisplay()
: Display()
, has_new_transforms_( false )
, time_since_last_transform_( 0.0f )
{
visual_enabled_property_ = new Property( "Visual Enabled", true,
"Whether to display the visual representation of the robot.",
this, SLOT( updateVisualVisible() ));
collision_enabled_property_ = new Property( "Collision Enabled", false,
"Whether to display the collision representation of the robot.",
this, SLOT( updateCollisionVisible() ));
update_rate_property_ = new FloatProperty( "Update Interval", 0,
"Interval at which to update the links, in seconds. "
" 0 means to update every update cycle.",
this );
update_rate_property_->setMin( 0 );
alpha_property_ = new FloatProperty( "Alpha", 1,
"Amount of transparency to apply to the links.",
this, SLOT( updateAlpha() ));
alpha_property_->setMin( 0.0 );
alpha_property_->setMax( 1.0 );
robot_description_property_ = new StringProperty( "Robot Description", "robot_description",
"Name of the parameter to search for to load the robot description.",
this, SLOT( updateRobotDescription() ));
tf_prefix_property_ = new StringProperty( "TF Prefix", "",
"Robot Model normally assumes the link name is the same as the tf frame name. "
" This option allows you to set a prefix. Mainly useful for multi-robot situations.",
this, SLOT( updateTfPrefix() ));
}
RobotModelDisplay::~RobotModelDisplay()
{
if ( initialized() )
{
delete robot_;
}
}
void RobotModelDisplay::onInitialize()
{
robot_ = new Robot( scene_node_, context_, "Robot: " + getName().toStdString(), this );
updateVisualVisible();
updateCollisionVisible();
updateAlpha();
}
void RobotModelDisplay::updateAlpha()
{
robot_->setAlpha( alpha_property_->getFloat() );
context_->queueRender();
}
void RobotModelDisplay::updateRobotDescription()
{
if( isEnabled() )
{
load();
context_->queueRender();
}
}
void RobotModelDisplay::updateVisualVisible()
{
robot_->setVisualVisible( visual_enabled_property_->getValue().toBool() );
context_->queueRender();
}
void RobotModelDisplay::updateCollisionVisible()
{
robot_->setCollisionVisible( collision_enabled_property_->getValue().toBool() );
context_->queueRender();
}
void RobotModelDisplay::updateTfPrefix()
{
clearStatuses();
context_->queueRender();
}
void RobotModelDisplay::load()
{
std::string content;
if( !update_nh_.getParam( robot_description_property_->getStdString(), content ))
{
std::string loc;
if( update_nh_.searchParam( robot_description_property_->getStdString(), loc ))
{
update_nh_.getParam( loc, content );
}
else
{
clear();
setStatus( StatusProperty::Error, "URDF",
"Parameter [" + robot_description_property_->getString()
+ "] does not exist, and was not found by searchParam()" );
return;
}
}
if( content.empty() )
{
clear();
setStatus( StatusProperty::Error, "URDF", "URDF is empty" );
return;
}
if( content == robot_description_ )
{
return;
}
robot_description_ = content;
TiXmlDocument doc;
doc.Parse( robot_description_.c_str() );
if( !doc.RootElement() )
{
clear();
setStatus( StatusProperty::Error, "URDF", "URDF failed XML parse" );
return;
}
urdf::Model descr;
if( !descr.initXml( doc.RootElement() ))
{
clear();
setStatus( StatusProperty::Error, "URDF", "URDF failed Model parse" );
return;
}
setStatus( StatusProperty::Ok, "URDF", "URDF parsed OK" );
robot_->load( descr );
robot_->update( TFLinkUpdater( context_->getFrameManager(),
boost::bind( linkUpdaterStatusFunction, _1, _2, _3, this ),
tf_prefix_property_->getStdString() ));
}
void RobotModelDisplay::onEnable()
{
load();
robot_->setVisible( true );
}
void RobotModelDisplay::onDisable()
{
robot_->setVisible( false );
clear();
}
void RobotModelDisplay::update( float wall_dt, float ros_dt )
{
time_since_last_transform_ += wall_dt;
float rate = update_rate_property_->getFloat();
bool update = rate < 0.0001f || time_since_last_transform_ >= rate;
if( has_new_transforms_ || update )
{
robot_->update( TFLinkUpdater( context_->getFrameManager(),
boost::bind( linkUpdaterStatusFunction, _1, _2, _3, this ),
tf_prefix_property_->getStdString() ));
context_->queueRender();
has_new_transforms_ = false;
time_since_last_transform_ = 0.0f;
}
}
void RobotModelDisplay::fixedFrameChanged()
{
has_new_transforms_ = true;
}
void RobotModelDisplay::clear()
{
robot_->clear();
clearStatuses();
robot_description_.clear();
}
void RobotModelDisplay::reset()
{
Display::reset();
has_new_transforms_ = true;
}
} // namespace rviz
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS( rviz::RobotModelDisplay, rviz::Display )
| olivierdm/rviz | src/rviz/default_plugin/robot_model_display.cpp | C++ | gpl-2.0 | 7,930 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="fr" version="2.0">
<context>
<name>CacheCleaner</name>
<message>
<location filename="Projects/octopi/cachecleaner/ui/cachecleaner.ui" line="14"/>
<source>Cache Cleaner - Octopi</source>
<translation>Nettoyeur de cache - Octopi</translation>
</message>
<message>
<location filename="Projects/octopi/cachecleaner/ui/cachecleaner.ui" line="49"/>
<source>Uninstalled packages</source>
<translation>Paquets non installés</translation>
</message>
<message>
<location filename="Projects/octopi/cachecleaner/ui/cachecleaner.ui" line="75"/>
<location filename="Projects/octopi/cachecleaner/ui/cachecleaner.ui" line="150"/>
<source>Keep :</source>
<translation>Conserver :</translation>
</message>
<message>
<location filename="Projects/octopi/cachecleaner/ui/cachecleaner.ui" line="82"/>
<location filename="Projects/octopi/cachecleaner/ui/cachecleaner.ui" line="157"/>
<source>Number of old versions to keep</source>
<translation>Nombre d'anciennes versions à conserver</translation>
</message>
<message>
<location filename="Projects/octopi/cachecleaner/ui/cachecleaner.ui" line="102"/>
<location filename="Projects/octopi/cachecleaner/ui/cachecleaner.ui" line="183"/>
<source>Refresh</source>
<translation>Actualiser</translation>
</message>
<message>
<location filename="Projects/octopi/cachecleaner/ui/cachecleaner.ui" line="127"/>
<source>Installed packages</source>
<translation>Paquets installés</translation>
</message>
</context>
<context>
<name>PackageGroupModel</name>
<message>
<location filename="Projects/octopi/cachecleaner/packagegroupmodel.cpp" line="199"/>
<source>Clean</source>
<translation>Nettoyer</translation>
</message>
<message>
<location filename="Projects/octopi/cachecleaner/packagegroupmodel.cpp" line="222"/>
<source>Clean %1</source>
<translation>Nettoyer %1</translation>
</message>
</context>
</TS> | offa/octopi | cachecleaner/resources/translations/octopi_cachecleaner_fr.ts | TypeScript | gpl-2.0 | 2,168 |
/**
* ArrowHead ASP Server
* This is a source file for the ArrowHead ASP Server - an 100% Java
* VBScript interpreter and ASP server.
*
* For more information, see http://www.tripi.com/arrowhead
*
* Copyright (C) 2002 Terence Haddock
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
package com.tripi.asp;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Logger;
/**
* Base class for handling ASP requests.
*
* @author Terence Haddock
* @version 0.9
*/
public class AspServlet extends HttpServlet implements HttpSessionListener
{
/** Debugging */
private Logger DBG = Logger.getLogger(AspServlet.class);
/** Servlet configuration */
ServletConfig config;
/** List of handlers which should be called on exception */
private Vector exceptionHandlers = new Vector();
/**
* Initializes the ASP servlet.
*
* @param config Servlet configuration
* @throws ServletException if an error occurs
* @see javax.servlet.Servlet#init(ServletConfig)
*/
public void init(ServletConfig config)
throws ServletException
{
super.init(config);
try {
ServletContext sctx = getServletContext();
this.config = config;
/* Set up logging */
String log4jConfigure = config.getInitParameter(
"log4j.configure");
if (log4jConfigure != null) {
PropertyConfigurator.configure(log4jConfigure);
}
if (DBG.isDebugEnabled()) {
DBG.debug("INIT: " + config);
DBG.debug("this: " + this);
}
/* Prepare the exception handlers */
prepareExceptionHandlers();
/* Grab the global scope */
GlobalScope globalScope = GlobalScope.getGlobalScope(sctx);
/* This should be a new scope, initialize it */
globalScope.initializeScope(config);
/* Now call application_onstart */
GlobalScope.callApplicationOnStart(config);
} catch (AspException ex) {
DBG.error("Exception in global scope", ex);
}
}
/**
* Obtains the properties for the exception handler
* @param handlerName name of the handler
* @param prop destination properties
*/
private void fillExceptionHandlerProperties(String handlerName, Properties prop)
{
String lookingFor = "exception.parameter." + handlerName + ".";
for (Enumeration e = config.getInitParameterNames();
e.hasMoreElements() ;)
{
String name = (String)e.nextElement();
if (name.startsWith(lookingFor)) {
String paramName = name.substring(lookingFor.length());
prop.setProperty(paramName, config.getInitParameter(name));
}
}
}
/**
* Prepares the exception handlers.
*/
private void prepareExceptionHandlers()
{
boolean anyExceptionHandlers = false;
for (Enumeration e = config.getInitParameterNames();
e.hasMoreElements() ;)
{
String name = (String)e.nextElement();
if (name.startsWith("exception.handler.")) {
if (DBG.isDebugEnabled()) DBG.debug("Configuring " + name);
String handlerName = name.substring(18);
Properties prop = new Properties();
fillExceptionHandlerProperties(handlerName, prop);
String value = config.getInitParameter(name);
try {
AspExceptionHandler aeh = (AspExceptionHandler)
Class.forName(value).newInstance();
aeh.configureExceptionHandler(prop);
exceptionHandlers.add(aeh);
anyExceptionHandlers = true;
} catch (ClassNotFoundException ex) {
DBG.error("Class not found", ex);
} catch (InstantiationException ex) {
DBG.error("Error initializing class", ex);
} catch (IllegalAccessException ex) {
DBG.error("Error initializing class", ex);
} catch (AspException ex) {
DBG.error("Error initializing class", ex);
}
}
}
if (!anyExceptionHandlers) {
exceptionHandlers.add(new FileNotFoundExceptionHandler());
exceptionHandlers.add(new SetStatusExceptionHandler());
exceptionHandlers.add(new PrintExceptionHandler());
}
}
/**
* Processes an ASP file request.
* @param request Incoming request
* @param response Outgoing response
* @see javax.servlet.Servlet#service
*/
public void service(HttpServletRequest request,
HttpServletResponse response)
{
String uri = request.getServletPath();
if (DBG.isDebugEnabled()) {
DBG.debug("ServletPath: " + request.getServletPath());
DBG.debug("RequestURI: " + request.getRequestURI());
DBG.debug("PathInfo: " + request.getPathInfo());
DBG.debug("PathTranslated: " + request.getPathTranslated());
}
response.setContentType("text/html");
try {
final IdentNode respIdent = new IdentNode("response");
final IdentNode reqIdent = new IdentNode("request");
final IdentNode sessionIdent = new IdentNode("session");
final IdentNode serverIdent = new IdentNode("server");
final IdentNode filenameIdent = new IdentNode("!filename");
final IdentNode globalIdent = new IdentNode("!global");
ServletContext ctx = getServletContext();
GlobalScope globalScope = GlobalScope.getGlobalScope(ctx);
AspContext context = globalScope.createContext();
Response respObj = new Response(response);
JavaObjectNode javaObj = new JavaObjectNode(respObj);
context.setValue(respIdent, javaObj);
Request reqObj = new Request(request);
JavaObjectNode reqJavaObj = new JavaObjectNode(reqObj);
context.setValue(reqIdent, reqJavaObj);
Session sesObj = new Session(request, context);
JavaObjectNode sessionObj = new JavaObjectNode(sesObj);
context.setValue(sessionIdent, sessionObj);
Server servObj = new Server(config, context);
JavaObjectNode serverObj = new JavaObjectNode(servObj);
context.setValue(serverIdent, serverObj);
context.forceScope(globalIdent);
context.setValue(filenameIdent, uri);
Server server = context.getAspServer();
AspThread aspRunner = new AspThread(context, uri, globalScope.getScriptCache());
Thread aspThread = new Thread(aspRunner);
aspThread.start();
aspThread.join((long)server.ScriptTimeout * 1000);
if (aspThread.isAlive())
{
aspRunner.timeout(context);
aspThread.join();
}
context.callOnPageEnd();
Application application = context.getAspApplication();
application.unlockIfThreadHasLock(aspThread);
if (DBG.isDebugEnabled()) DBG.debug("Sub-exception: " + aspRunner.ex);
if (aspRunner.ex instanceof AspExitScriptException)
{
if (respObj.stringBuf != null) {
respObj.Flush();
}
return;
}
if (aspRunner.ex != null) {
Enumeration e = exceptionHandlers.elements();
while (e.hasMoreElements())
{
AspExceptionHandler aeh =
(AspExceptionHandler)e.nextElement();
try {
if (!aeh.onExceptionOccured(context, aspRunner.ex))
break;
} catch(Exception ex) {
DBG.error("Error while calling exception handler", ex);
}
}
}
if (respObj.stringBuf != null) {
respObj.Flush();
}
} catch (Exception ex) {
throw new AspNestedRuntimeException(ex);
}
};
/** Contains a refernece to a session handler. */
private AspSessionHandler sessionHandler = new AspSessionHandler();
/**
* Session initialized.
* @param e Event describing the initiazing of the session.
*/
public void sessionCreated(HttpSessionEvent e)
{
sessionHandler.sessionCreated(e);
}
/**
* Session destroyed.
* @param e Event describing the destruction of the session.
*/
public void sessionDestroyed(HttpSessionEvent e)
{
sessionHandler.sessionDestroyed(e);
}
}
| lazerdye/arrowheadasp | src/com/tripi/asp/AspServlet.java | Java | gpl-2.0 | 10,070 |
/**
* OWASP Benchmark Project v1.2beta
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The OWASP Benchmark 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.
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest01535")
public class BenchmarkTest01535 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheParameter("vector");
if (param == null) param = "";
String bar = new Test().doSomething(param);
Object[] obj = { "a", bar };
java.io.PrintWriter out = response.getWriter();
out.write("<!DOCTYPE html>\n<html>\n<body>\n<p>");
out.format(java.util.Locale.US,"Formatted like: %1$s and %2$s.",obj);
out.write("\n</p>\n</body>\n</html>");
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param);
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| marylinh/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01535.java | Java | gpl-2.0 | 2,365 |
/* Copyright (C) 2004 - 2009 Versant Inc. http://www.db4o.com */
using Db4objects.Db4o.Marshall;
namespace Db4objects.Db4o.Internal.Collections
{
public interface IBigSetPersistence
{
void Write(IWriteContext context);
void Read(IReadContext context);
void Invalidate();
}
}
| meebey/smuxi-head-mirror | lib/db4o-net/Db4objects.Db4o/Db4objects.Db4o/Internal/Collections/IBigSetPersistence.cs | C# | gpl-2.0 | 303 |
/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "icecrown_citadel.h"
#include "DB2Stores.h"
#include "GameObject.h"
#include "GridNotifiers.h"
#include "Group.h"
#include "InstanceScript.h"
#include "Map.h"
#include "MotionMaster.h"
#include "ObjectAccessor.h"
#include "ScriptedCreature.h"
#include "Spell.h"
#include "SpellAuraEffects.h"
#include "SpellAuras.h"
#include "SpellInfo.h"
#include "SpellMgr.h"
#include "SpellScript.h"
#include "TemporarySummon.h"
#include "Vehicle.h"
enum Say
{
// Festergut
SAY_FESTERGUT_GASEOUS_BLIGHT = 0,
SAY_FESTERGUT_DEATH = 1,
// Rotface
SAY_ROTFACE_OOZE_FLOOD = 2,
SAY_ROTFACE_DEATH = 3,
// Professor Putricide
SAY_AGGRO = 4,
EMOTE_UNSTABLE_EXPERIMENT = 5,
SAY_PHASE_TRANSITION_HEROIC = 6,
SAY_TRANSFORM_1 = 7,
SAY_TRANSFORM_2 = 8, // always used for phase2 change, DO NOT GROUP WITH SAY_TRANSFORM_1
EMOTE_MALLEABLE_GOO = 9,
EMOTE_CHOKING_GAS_BOMB = 10,
SAY_KILL = 11,
SAY_BERSERK = 12,
SAY_DEATH = 13
};
enum Spells
{
// Festergut
SPELL_RELEASE_GAS_VISUAL = 69125,
SPELL_GASEOUS_BLIGHT_LARGE = 69157,
SPELL_GASEOUS_BLIGHT_MEDIUM = 69162,
SPELL_GASEOUS_BLIGHT_SMALL = 69164,
SPELL_MALLEABLE_GOO_H = 72296,
SPELL_MALLEABLE_GOO_SUMMON = 72299,
// Professor Putricide
SPELL_SLIME_PUDDLE_TRIGGER = 70341,
SPELL_MALLEABLE_GOO = 70852,
SPELL_UNSTABLE_EXPERIMENT = 70351,
SPELL_TEAR_GAS = 71617, // phase transition
SPELL_TEAR_GAS_CREATURE = 71618,
SPELL_TEAR_GAS_CANCEL = 71620,
SPELL_TEAR_GAS_PERIODIC_TRIGGER = 73170,
SPELL_CREATE_CONCOCTION = 71621,
SPELL_GUZZLE_POTIONS = 71893,
SPELL_OOZE_TANK_PROTECTION = 71770, // protects the tank
SPELL_CHOKING_GAS_BOMB = 71255,
SPELL_OOZE_VARIABLE = 74118,
SPELL_GAS_VARIABLE = 74119,
SPELL_UNBOUND_PLAGUE = 70911,
SPELL_UNBOUND_PLAGUE_SEARCHER = 70917,
SPELL_PLAGUE_SICKNESS = 70953,
SPELL_UNBOUND_PLAGUE_PROTECTION = 70955,
SPELL_MUTATED_PLAGUE = 72451,
SPELL_MUTATED_PLAGUE_CLEAR = 72618,
// Slime Puddle
SPELL_GROW_STACKER = 70345,
SPELL_GROW = 70347,
SPELL_SLIME_PUDDLE_AURA = 70343,
// Gas Cloud
SPELL_GASEOUS_BLOAT_PROC = 70215,
SPELL_GASEOUS_BLOAT = 70672,
SPELL_GASEOUS_BLOAT_PROTECTION = 70812,
SPELL_EXPUNGED_GAS = 70701,
// Volatile Ooze
SPELL_OOZE_ERUPTION = 70492,
SPELL_VOLATILE_OOZE_ADHESIVE = 70447,
SPELL_OOZE_ERUPTION_SEARCH_PERIODIC = 70457,
SPELL_VOLATILE_OOZE_PROTECTION = 70530,
// Choking Gas Bomb
SPELL_CHOKING_GAS_BOMB_PERIODIC = 71259,
SPELL_CHOKING_GAS_EXPLOSION_TRIGGER = 71280,
// Mutated Abomination vehicle
SPELL_ABOMINATION_VEHICLE_POWER_DRAIN = 70385,
SPELL_MUTATED_TRANSFORMATION = 70311,
SPELL_MUTATED_TRANSFORMATION_DAMAGE = 70405,
SPELL_MUTATED_TRANSFORMATION_NAME = 72401,
// Unholy Infusion
SPELL_UNHOLY_INFUSION_CREDIT = 71518
};
#define SPELL_GASEOUS_BLOAT_HELPER RAID_MODE<uint32>(70672, 72455, 72832, 72833)
enum Events
{
// Festergut
EVENT_FESTERGUT_DIES = 1,
EVENT_FESTERGUT_GOO = 2,
// Rotface
EVENT_ROTFACE_DIES = 3,
EVENT_ROTFACE_OOZE_FLOOD = 5,
// Professor Putricide
EVENT_BERSERK = 6, // all phases
EVENT_SLIME_PUDDLE = 7, // all phases
EVENT_UNSTABLE_EXPERIMENT = 8, // P1 && P2
EVENT_TEAR_GAS = 9, // phase transition not heroic
EVENT_RESUME_ATTACK = 10,
EVENT_MALLEABLE_GOO = 11,
EVENT_CHOKING_GAS_BOMB = 12,
EVENT_UNBOUND_PLAGUE = 13,
EVENT_MUTATED_PLAGUE = 14,
EVENT_PHASE_TRANSITION = 15
};
enum Phases
{
PHASE_NONE = 0,
PHASE_FESTERGUT = 1,
PHASE_ROTFACE = 2,
PHASE_COMBAT_1 = 4,
PHASE_COMBAT_2 = 5,
PHASE_COMBAT_3 = 6
};
enum Points
{
POINT_FESTERGUT = 366260,
POINT_ROTFACE = 366270,
POINT_TABLE = 366780
};
Position const festergutWatchPos = {4324.820f, 3166.03f, 389.3831f, 3.316126f}; //emote 432 (release gas)
Position const rotfaceWatchPos = {4390.371f, 3164.50f, 389.3890f, 5.497787f}; //emote 432 (release ooze)
Position const tablePos = {4356.190f, 3262.90f, 389.4820f, 1.483530f};
// used in Rotface encounter
uint32 const oozeFloodSpells[4] = {69782, 69796, 69798, 69801};
enum PutricideData
{
DATA_EXPERIMENT_STAGE = 1,
DATA_PHASE = 2,
DATA_ABOMINATION = 3
};
#define EXPERIMENT_STATE_OOZE false
#define EXPERIMENT_STATE_GAS true
class AbominationDespawner
{
public:
explicit AbominationDespawner(Unit* owner) : _owner(owner) { }
bool operator()(ObjectGuid guid)
{
if (Unit* summon = ObjectAccessor::GetUnit(*_owner, guid))
{
if (summon->GetEntry() == NPC_MUTATED_ABOMINATION_10 || summon->GetEntry() == NPC_MUTATED_ABOMINATION_25)
{
if (Vehicle* veh = summon->GetVehicleKit())
veh->RemoveAllPassengers(); // also despawns the vehicle
// Found unit is Mutated Abomination, remove it
return true;
}
// Found unit is not Mutated Abomintaion, leave it
return false;
}
// No unit found, remove from SummonList
return true;
}
private:
Unit* _owner;
};
struct RotfaceHeightCheck
{
RotfaceHeightCheck(Creature* rotface) : _rotface(rotface) { }
bool operator()(Creature* stalker) const
{
return stalker->GetPositionZ() < _rotface->GetPositionZ() + 5.0f;
}
private:
Creature* _rotface;
};
class boss_professor_putricide : public CreatureScript
{
public:
boss_professor_putricide() : CreatureScript("boss_professor_putricide") { }
struct boss_professor_putricideAI : public BossAI
{
boss_professor_putricideAI(Creature* creature) : BossAI(creature, DATA_PROFESSOR_PUTRICIDE),
_baseSpeed(creature->GetSpeedRate(MOVE_RUN)), _experimentState(EXPERIMENT_STATE_OOZE)
{
_phase = PHASE_NONE;
_oozeFloodStage = 0;
}
void Reset() override
{
if (!(events.IsInPhase(PHASE_ROTFACE) || events.IsInPhase(PHASE_FESTERGUT)))
instance->SetBossState(DATA_PROFESSOR_PUTRICIDE, NOT_STARTED);
instance->SetData(DATA_NAUSEA_ACHIEVEMENT, uint32(true));
events.Reset();
summons.DespawnAll();
SetPhase(PHASE_COMBAT_1);
_experimentState = EXPERIMENT_STATE_OOZE;
me->SetReactState(REACT_DEFENSIVE);
me->SetWalk(false);
if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE)
me->GetMotionMaster()->MovementExpired();
if (instance->GetBossState(DATA_ROTFACE) == DONE && instance->GetBossState(DATA_FESTERGUT) == DONE)
me->RemoveUnitFlag(UnitFlags(UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_NOT_SELECTABLE));
}
void EnterCombat(Unit* who) override
{
if (events.IsInPhase(PHASE_ROTFACE) || events.IsInPhase(PHASE_FESTERGUT))
return;
if (!instance->CheckRequiredBosses(DATA_PROFESSOR_PUTRICIDE, who->ToPlayer()))
{
EnterEvadeMode();
instance->DoCastSpellOnPlayers(LIGHT_S_HAMMER_TELEPORT);
return;
}
me->setActive(true);
events.Reset();
events.ScheduleEvent(EVENT_BERSERK, 600000);
events.ScheduleEvent(EVENT_SLIME_PUDDLE, 10000);
events.ScheduleEvent(EVENT_UNSTABLE_EXPERIMENT, urand(30000, 35000));
if (IsHeroic())
events.ScheduleEvent(EVENT_UNBOUND_PLAGUE, 20000);
SetPhase(PHASE_COMBAT_1);
Talk(SAY_AGGRO);
DoCast(me, SPELL_OOZE_TANK_PROTECTION, true);
DoZoneInCombat(me);
instance->SetBossState(DATA_PROFESSOR_PUTRICIDE, IN_PROGRESS);
}
void JustReachedHome() override
{
_JustReachedHome();
me->SetWalk(false);
if (events.IsInPhase(PHASE_COMBAT_1) || events.IsInPhase(PHASE_COMBAT_2) || events.IsInPhase(PHASE_COMBAT_3))
instance->SetBossState(DATA_PROFESSOR_PUTRICIDE, FAIL);
}
void KilledUnit(Unit* victim) override
{
if (victim->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_KILL);
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
Talk(SAY_DEATH);
if (Is25ManRaid() && me->HasAura(SPELL_SHADOWS_FATE))
DoCastAOE(SPELL_UNHOLY_INFUSION_CREDIT, true);
DoCast(SPELL_MUTATED_PLAGUE_CLEAR);
}
void JustSummoned(Creature* summon) override
{
summons.Summon(summon);
switch (summon->GetEntry())
{
case NPC_MALLEABLE_OOZE_STALKER:
DoCast(summon, SPELL_MALLEABLE_GOO_H);
return;
case NPC_GROWING_OOZE_PUDDLE:
summon->CastSpell(summon, SPELL_GROW_STACKER, true);
summon->CastSpell(summon, SPELL_SLIME_PUDDLE_AURA, true);
// blizzard casts this spell 7 times initially (confirmed in sniff)
for (uint8 i = 0; i < 7; ++i)
summon->CastSpell(summon, SPELL_GROW, true);
break;
case NPC_GAS_CLOUD:
// no possible aura seen in sniff adding the aurastate
summon->ModifyAuraState(AURA_STATE_UNKNOWN22, true);
summon->SetReactState(REACT_PASSIVE);
break;
case NPC_VOLATILE_OOZE:
// no possible aura seen in sniff adding the aurastate
summon->ModifyAuraState(AURA_STATE_UNKNOWN19, true);
summon->SetReactState(REACT_PASSIVE);
break;
case NPC_CHOKING_GAS_BOMB:
summon->CastSpell(summon, SPELL_CHOKING_GAS_BOMB_PERIODIC, true);
summon->CastSpell(summon, SPELL_CHOKING_GAS_EXPLOSION_TRIGGER, true);
return;
case NPC_MUTATED_ABOMINATION_10:
case NPC_MUTATED_ABOMINATION_25:
return;
default:
break;
}
if (me->IsInCombat())
DoZoneInCombat(summon);
}
void DamageTaken(Unit* /*attacker*/, uint32& /*damage*/) override
{
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
switch (_phase)
{
case PHASE_COMBAT_1:
if (HealthAbovePct(80))
return;
me->SetReactState(REACT_PASSIVE);
DoAction(ACTION_CHANGE_PHASE);
break;
case PHASE_COMBAT_2:
if (HealthAbovePct(35))
return;
me->SetReactState(REACT_PASSIVE);
DoAction(ACTION_CHANGE_PHASE);
break;
default:
break;
}
}
void MovementInform(uint32 type, uint32 id) override
{
if (type != POINT_MOTION_TYPE)
return;
switch (id)
{
case POINT_FESTERGUT:
instance->SetBossState(DATA_FESTERGUT, IN_PROGRESS); // needed here for delayed gate close
me->SetSpeedRate(MOVE_RUN, _baseSpeed);
DoAction(ACTION_FESTERGUT_GAS);
if (Creature* festergut = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FESTERGUT)))
festergut->CastSpell(festergut, SPELL_GASEOUS_BLIGHT_LARGE, false, NULL, NULL, festergut->GetGUID());
break;
case POINT_ROTFACE:
instance->SetBossState(DATA_ROTFACE, IN_PROGRESS); // needed here for delayed gate close
me->SetSpeedRate(MOVE_RUN, _baseSpeed);
DoAction(ACTION_ROTFACE_OOZE);
events.ScheduleEvent(EVENT_ROTFACE_OOZE_FLOOD, 25000, 0, PHASE_ROTFACE);
break;
case POINT_TABLE:
// stop attack
me->GetMotionMaster()->MoveIdle();
me->SetSpeedRate(MOVE_RUN, _baseSpeed);
if (GameObject* table = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(DATA_PUTRICIDE_TABLE)))
me->SetFacingToObject(table);
// operating on new phase already
switch (_phase)
{
case PHASE_COMBAT_2:
{
SpellInfo const* spell = sSpellMgr->GetSpellInfo(SPELL_CREATE_CONCOCTION);
DoCast(me, SPELL_CREATE_CONCOCTION);
events.ScheduleEvent(EVENT_PHASE_TRANSITION, spell->CalcCastTime() + 100);
break;
}
case PHASE_COMBAT_3:
{
SpellInfo const* spell = sSpellMgr->GetSpellInfo(SPELL_GUZZLE_POTIONS);
DoCast(me, SPELL_GUZZLE_POTIONS);
events.ScheduleEvent(EVENT_PHASE_TRANSITION, spell->CalcCastTime() + 100);
break;
}
default:
break;
}
break;
default:
break;
}
}
void DoAction(int32 action) override
{
switch (action)
{
case ACTION_FESTERGUT_COMBAT:
SetPhase(PHASE_FESTERGUT);
me->SetSpeedRate(MOVE_RUN, _baseSpeed*2.0f);
me->GetMotionMaster()->MovePoint(POINT_FESTERGUT, festergutWatchPos);
me->SetReactState(REACT_PASSIVE);
DoZoneInCombat(me);
if (IsHeroic())
events.ScheduleEvent(EVENT_FESTERGUT_GOO, urand(13000, 18000), 0, PHASE_FESTERGUT);
break;
case ACTION_FESTERGUT_GAS:
Talk(SAY_FESTERGUT_GASEOUS_BLIGHT);
DoCast(me, SPELL_RELEASE_GAS_VISUAL, true);
break;
case ACTION_FESTERGUT_DEATH:
events.ScheduleEvent(EVENT_FESTERGUT_DIES, 4000, 0, PHASE_FESTERGUT);
break;
case ACTION_ROTFACE_COMBAT:
{
SetPhase(PHASE_ROTFACE);
me->SetSpeedRate(MOVE_RUN, _baseSpeed*2.0f);
me->GetMotionMaster()->MovePoint(POINT_ROTFACE, rotfaceWatchPos);
me->SetReactState(REACT_PASSIVE);
_oozeFloodStage = 0;
DoZoneInCombat(me);
// init random sequence of floods
if (Creature* rotface = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_ROTFACE)))
{
std::list<Creature*> list;
GetCreatureListWithEntryInGrid(list, rotface, NPC_PUDDLE_STALKER, 50.0f);
list.remove_if(RotfaceHeightCheck(rotface));
if (list.size() > 4)
{
list.sort(Trinity::ObjectDistanceOrderPred(rotface));
do
{
list.pop_back();
} while (list.size() > 4);
}
uint8 i = 0;
while (!list.empty())
{
std::list<Creature*>::iterator itr = list.begin();
std::advance(itr, urand(0, list.size()-1));
_oozeFloodDummyGUIDs[i++] = (*itr)->GetGUID();
list.erase(itr);
}
}
break;
}
case ACTION_ROTFACE_OOZE:
Talk(SAY_ROTFACE_OOZE_FLOOD);
if (Creature* dummy = ObjectAccessor::GetCreature(*me, _oozeFloodDummyGUIDs[_oozeFloodStage]))
dummy->CastSpell(dummy, oozeFloodSpells[_oozeFloodStage], true, NULL, NULL, me->GetGUID()); // cast from self for LoS (with prof's GUID for logs)
if (++_oozeFloodStage == 4)
_oozeFloodStage = 0;
break;
case ACTION_ROTFACE_DEATH:
events.ScheduleEvent(EVENT_ROTFACE_DIES, 4500, 0, PHASE_ROTFACE);
break;
case ACTION_CHANGE_PHASE:
me->SetSpeedRate(MOVE_RUN, _baseSpeed*2.0f);
events.DelayEvents(30000);
me->AttackStop();
if (!IsHeroic())
{
DoCast(me, SPELL_TEAR_GAS);
events.ScheduleEvent(EVENT_TEAR_GAS, 2500);
}
else
{
Talk(SAY_PHASE_TRANSITION_HEROIC);
DoCast(me, SPELL_UNSTABLE_EXPERIMENT, true);
DoCast(me, SPELL_UNSTABLE_EXPERIMENT, true);
// cast variables
if (Is25ManRaid())
{
std::list<Unit*> targetList;
{
const std::list<HostileReference*>& threatlist = me->getThreatManager().getThreatList();
for (std::list<HostileReference*>::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr)
if ((*itr)->getTarget()->GetTypeId() == TYPEID_PLAYER)
targetList.push_back((*itr)->getTarget());
}
size_t half = targetList.size()/2;
// half gets ooze variable
while (half < targetList.size())
{
std::list<Unit*>::iterator itr = targetList.begin();
advance(itr, urand(0, targetList.size() - 1));
(*itr)->CastSpell(*itr, SPELL_OOZE_VARIABLE, true);
targetList.erase(itr);
}
// and half gets gas
for (std::list<Unit*>::iterator itr = targetList.begin(); itr != targetList.end(); ++itr)
(*itr)->CastSpell(*itr, SPELL_GAS_VARIABLE, true);
}
me->GetMotionMaster()->MovePoint(POINT_TABLE, tablePos);
}
switch (_phase)
{
case PHASE_COMBAT_1:
SetPhase(PHASE_COMBAT_2);
events.ScheduleEvent(EVENT_MALLEABLE_GOO, urand(21000, 26000));
events.ScheduleEvent(EVENT_CHOKING_GAS_BOMB, urand(35000, 40000));
break;
case PHASE_COMBAT_2:
SetPhase(PHASE_COMBAT_3);
events.ScheduleEvent(EVENT_MUTATED_PLAGUE, 25000);
events.CancelEvent(EVENT_UNSTABLE_EXPERIMENT);
break;
default:
break;
}
break;
default:
break;
}
}
uint32 GetData(uint32 type) const override
{
switch (type)
{
case DATA_EXPERIMENT_STAGE:
return _experimentState;
case DATA_PHASE:
return _phase;
case DATA_ABOMINATION:
return uint32(summons.HasEntry(NPC_MUTATED_ABOMINATION_10) || summons.HasEntry(NPC_MUTATED_ABOMINATION_25));
default:
break;
}
return 0;
}
void SetData(uint32 id, uint32 data) override
{
if (id == DATA_EXPERIMENT_STAGE)
_experimentState = data != 0;
}
void UpdateAI(uint32 diff) override
{
if (!(events.IsInPhase(PHASE_ROTFACE) || events.IsInPhase(PHASE_FESTERGUT)) && !UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_FESTERGUT_DIES:
Talk(SAY_FESTERGUT_DEATH);
EnterEvadeMode();
break;
case EVENT_FESTERGUT_GOO:
me->CastCustomSpell(SPELL_MALLEABLE_GOO_SUMMON, SPELLVALUE_MAX_TARGETS, 1, NULL, true);
events.ScheduleEvent(EVENT_FESTERGUT_GOO, (Is25ManRaid() ? 10000 : 30000) + urand(0, 5000), 0, PHASE_FESTERGUT);
break;
case EVENT_ROTFACE_DIES:
Talk(SAY_ROTFACE_DEATH);
EnterEvadeMode();
break;
case EVENT_ROTFACE_OOZE_FLOOD:
DoAction(ACTION_ROTFACE_OOZE);
events.ScheduleEvent(EVENT_ROTFACE_OOZE_FLOOD, 25000, 0, PHASE_ROTFACE);
break;
case EVENT_BERSERK:
Talk(SAY_BERSERK);
DoCast(me, SPELL_BERSERK2);
break;
case EVENT_SLIME_PUDDLE:
{
std::list<Unit*> targets;
SelectTargetList(targets, 2, SELECT_TARGET_RANDOM, 0.0f, true);
if (!targets.empty())
for (std::list<Unit*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
DoCast(*itr, SPELL_SLIME_PUDDLE_TRIGGER);
events.ScheduleEvent(EVENT_SLIME_PUDDLE, 35000);
break;
}
case EVENT_UNSTABLE_EXPERIMENT:
Talk(EMOTE_UNSTABLE_EXPERIMENT);
DoCast(me, SPELL_UNSTABLE_EXPERIMENT);
events.ScheduleEvent(EVENT_UNSTABLE_EXPERIMENT, urand(35000, 40000));
break;
case EVENT_TEAR_GAS:
me->GetMotionMaster()->MovePoint(POINT_TABLE, tablePos);
DoCast(me, SPELL_TEAR_GAS_PERIODIC_TRIGGER, true);
break;
case EVENT_RESUME_ATTACK:
me->SetReactState(REACT_AGGRESSIVE);
AttackStart(me->GetVictim());
// remove Tear Gas
me->RemoveAurasDueToSpell(SPELL_TEAR_GAS_PERIODIC_TRIGGER);
instance->DoRemoveAurasDueToSpellOnPlayers(71615);
DoCastAOE(SPELL_TEAR_GAS_CANCEL);
instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_GAS_VARIABLE);
instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_OOZE_VARIABLE);
break;
case EVENT_MALLEABLE_GOO:
if (Is25ManRaid())
{
std::list<Unit*> targets;
SelectTargetList(targets, 2, SELECT_TARGET_RANDOM, -7.0f, true);
if (!targets.empty())
{
Talk(EMOTE_MALLEABLE_GOO);
for (std::list<Unit*>::iterator itr = targets.begin(); itr != targets.end(); ++itr)
DoCast(*itr, SPELL_MALLEABLE_GOO);
}
}
else
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, -7.0f, true))
{
Talk(EMOTE_MALLEABLE_GOO);
DoCast(target, SPELL_MALLEABLE_GOO);
}
}
events.ScheduleEvent(EVENT_MALLEABLE_GOO, urand(25000, 30000));
break;
case EVENT_CHOKING_GAS_BOMB:
Talk(EMOTE_CHOKING_GAS_BOMB);
DoCast(me, SPELL_CHOKING_GAS_BOMB);
events.ScheduleEvent(EVENT_CHOKING_GAS_BOMB, urand(35000, 40000));
break;
case EVENT_UNBOUND_PLAGUE:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, NonTankTargetSelector(me)))
{
DoCast(target, SPELL_UNBOUND_PLAGUE);
DoCast(target, SPELL_UNBOUND_PLAGUE_SEARCHER);
}
events.ScheduleEvent(EVENT_UNBOUND_PLAGUE, 90000);
break;
case EVENT_MUTATED_PLAGUE:
DoCastVictim(SPELL_MUTATED_PLAGUE);
events.ScheduleEvent(EVENT_MUTATED_PLAGUE, 10000);
break;
case EVENT_PHASE_TRANSITION:
{
switch (_phase)
{
case PHASE_COMBAT_2:
if (Creature* face = me->FindNearestCreature(NPC_TEAR_GAS_TARGET_STALKER, 50.0f))
me->SetFacingToObject(face);
me->HandleEmoteCommand(EMOTE_ONESHOT_KNEEL);
Talk(SAY_TRANSFORM_1);
events.ScheduleEvent(EVENT_RESUME_ATTACK, 5500, 0, PHASE_COMBAT_2);
break;
case PHASE_COMBAT_3:
if (Creature* face = me->FindNearestCreature(NPC_TEAR_GAS_TARGET_STALKER, 50.0f))
me->SetFacingToObject(face);
me->HandleEmoteCommand(EMOTE_ONESHOT_KNEEL);
Talk(SAY_TRANSFORM_2);
summons.DespawnIf(AbominationDespawner(me));
events.ScheduleEvent(EVENT_RESUME_ATTACK, 8500, 0, PHASE_COMBAT_3);
break;
default:
break;
}
}
default:
break;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
}
DoMeleeAttackIfReady();
}
private:
void SetPhase(Phases newPhase)
{
_phase = newPhase;
events.SetPhase(newPhase);
}
ObjectGuid _oozeFloodDummyGUIDs[4];
Phases _phase; // external of EventMap because event phase gets reset on evade
float const _baseSpeed;
uint8 _oozeFloodStage;
bool _experimentState;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetIcecrownCitadelAI<boss_professor_putricideAI>(creature);
}
};
class npc_putricide_oozeAI : public ScriptedAI
{
public:
npc_putricide_oozeAI(Creature* creature, uint32 auraSpellId, uint32 hitTargetSpellId) : ScriptedAI(creature),
_auraSpellId(auraSpellId), _hitTargetSpellId(hitTargetSpellId), _newTargetSelectTimer(0) { }
void SpellHitTarget(Unit* /*target*/, SpellInfo const* spell) override
{
if (!_newTargetSelectTimer && spell->Id == _hitTargetSpellId)
_newTargetSelectTimer = 1000;
}
void Reset() override
{
DoCastAOE(_auraSpellId, true);
}
void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override
{
if (spell->Id == SPELL_TEAR_GAS_CREATURE)
_newTargetSelectTimer = 1000;
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim() && !_newTargetSelectTimer)
return;
if (!_newTargetSelectTimer && !me->IsNonMeleeSpellCast(false, false, true, false, true))
_newTargetSelectTimer = 1000;
DoMeleeAttackIfReady();
if (!_newTargetSelectTimer)
return;
if (me->HasAura(SPELL_TEAR_GAS_CREATURE))
return;
if (_newTargetSelectTimer <= diff)
{
_newTargetSelectTimer = 0;
CastMainSpell();
}
else
_newTargetSelectTimer -= diff;
}
virtual void CastMainSpell() = 0;
private:
uint32 _auraSpellId;
uint32 _hitTargetSpellId;
uint32 _newTargetSelectTimer;
};
class npc_volatile_ooze : public CreatureScript
{
public:
npc_volatile_ooze() : CreatureScript("npc_volatile_ooze") { }
struct npc_volatile_oozeAI : public npc_putricide_oozeAI
{
npc_volatile_oozeAI(Creature* creature) : npc_putricide_oozeAI(creature, SPELL_OOZE_ERUPTION_SEARCH_PERIODIC, SPELL_OOZE_ERUPTION) { }
void CastMainSpell() override
{
me->CastSpell(me, SPELL_VOLATILE_OOZE_ADHESIVE, false);
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetIcecrownCitadelAI<npc_volatile_oozeAI>(creature);
}
};
class npc_gas_cloud : public CreatureScript
{
public:
npc_gas_cloud() : CreatureScript("npc_gas_cloud") { }
struct npc_gas_cloudAI : public npc_putricide_oozeAI
{
npc_gas_cloudAI(Creature* creature) : npc_putricide_oozeAI(creature, SPELL_GASEOUS_BLOAT_PROC, SPELL_EXPUNGED_GAS)
{
_newTargetSelectTimer = 0;
}
void CastMainSpell() override
{
me->CastCustomSpell(SPELL_GASEOUS_BLOAT, SPELLVALUE_AURA_STACK, 10, me, false);
}
private:
uint32 _newTargetSelectTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetIcecrownCitadelAI<npc_gas_cloudAI>(creature);
}
};
class spell_putricide_gaseous_bloat : public SpellScriptLoader
{
public:
spell_putricide_gaseous_bloat() : SpellScriptLoader("spell_putricide_gaseous_bloat") { }
class spell_putricide_gaseous_bloat_AuraScript : public AuraScript
{
PrepareAuraScript(spell_putricide_gaseous_bloat_AuraScript);
void HandleExtraEffect(AuraEffect const* /*aurEff*/)
{
Unit* target = GetTarget();
if (Unit* caster = GetCaster())
{
target->RemoveAuraFromStack(GetSpellInfo()->Id, GetCasterGUID());
if (!target->HasAura(GetId()))
caster->CastCustomSpell(SPELL_GASEOUS_BLOAT, SPELLVALUE_AURA_STACK, 10, caster, false);
}
}
void HandleProc(ProcEventInfo& eventInfo)
{
uint32 stack = GetStackAmount();
Unit* caster = eventInfo.GetActor();
int32 const mod = caster->GetMap()->Is25ManRaid() ? 1500 : 1250;
int32 dmg = 0;
for (uint8 i = 1; i <= stack; ++i)
dmg += mod * i;
caster->CastCustomSpell(SPELL_EXPUNGED_GAS, SPELLVALUE_BASE_POINT0, dmg);
}
void Register() override
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_putricide_gaseous_bloat_AuraScript::HandleExtraEffect, EFFECT_0, SPELL_AURA_PERIODIC_DAMAGE);
OnProc += AuraProcFn(spell_putricide_gaseous_bloat_AuraScript::HandleProc);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_putricide_gaseous_bloat_AuraScript();
}
};
class spell_putricide_ooze_channel : public SpellScriptLoader
{
public:
spell_putricide_ooze_channel() : SpellScriptLoader("spell_putricide_ooze_channel") { }
class spell_putricide_ooze_channel_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_ooze_channel_SpellScript);
public:
spell_putricide_ooze_channel_SpellScript()
{
_target = nullptr;
}
private:
bool Validate(SpellInfo const* spell) override
{
return spell->ExcludeTargetAuraSpell && ValidateSpellInfo({ spell->ExcludeTargetAuraSpell });
}
// set up initial variables and check if caster is creature
// this will let use safely use ToCreature() casts in entire script
bool Load() override
{
return GetCaster()->GetTypeId() == TYPEID_UNIT;
}
void SelectTarget(std::list<WorldObject*>& targets)
{
if (targets.empty())
{
FinishCast(SPELL_FAILED_NO_VALID_TARGETS);
GetCaster()->ToCreature()->DespawnOrUnsummon(1); // despawn next update
return;
}
WorldObject* target = Trinity::Containers::SelectRandomContainerElement(targets);
targets.clear();
targets.push_back(target);
_target = target;
}
void SetTarget(std::list<WorldObject*>& targets)
{
targets.clear();
if (_target)
targets.push_back(_target);
}
void StartAttack()
{
GetCaster()->ClearUnitState(UNIT_STATE_CASTING);
GetCaster()->DeleteThreatList();
GetCaster()->ToCreature()->AI()->AttackStart(GetHitUnit());
GetCaster()->AddThreat(GetHitUnit(), 500000000.0f); // value seen in sniff
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_ooze_channel_SpellScript::SelectTarget, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY);
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_ooze_channel_SpellScript::SetTarget, EFFECT_1, TARGET_UNIT_SRC_AREA_ENEMY);
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_ooze_channel_SpellScript::SetTarget, EFFECT_2, TARGET_UNIT_SRC_AREA_ENEMY);
AfterHit += SpellHitFn(spell_putricide_ooze_channel_SpellScript::StartAttack);
}
WorldObject* _target;
};
SpellScript* GetSpellScript() const override
{
return new spell_putricide_ooze_channel_SpellScript();
}
};
class ExactDistanceCheck
{
public:
ExactDistanceCheck(Unit* source, float dist) : _source(source), _dist(dist) { }
bool operator()(WorldObject* unit) const
{
return _source->GetExactDist2d(unit) > _dist;
}
private:
Unit* _source;
float _dist;
};
class spell_putricide_slime_puddle : public SpellScriptLoader
{
public:
spell_putricide_slime_puddle() : SpellScriptLoader("spell_putricide_slime_puddle") { }
class spell_putricide_slime_puddle_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_slime_puddle_SpellScript);
void ScaleRange(std::list<WorldObject*>& targets)
{
targets.remove_if(ExactDistanceCheck(GetCaster(), 2.5f * GetCaster()->GetObjectScale()));
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_slime_puddle_SpellScript::ScaleRange, EFFECT_0, TARGET_UNIT_DEST_AREA_ENEMY);
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_slime_puddle_SpellScript::ScaleRange, EFFECT_1, TARGET_UNIT_DEST_AREA_ENTRY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_putricide_slime_puddle_SpellScript();
}
};
// this is here only because on retail you dont actually enter HEROIC mode for ICC
class spell_putricide_slime_puddle_aura : public SpellScriptLoader
{
public:
spell_putricide_slime_puddle_aura() : SpellScriptLoader("spell_putricide_slime_puddle_aura") { }
class spell_putricide_slime_puddle_aura_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_slime_puddle_aura_SpellScript);
void ReplaceAura()
{
if (Unit* target = GetHitUnit())
GetCaster()->AddAura(GetCaster()->GetMap()->Is25ManRaid() ? 72456 : 70346, target);
}
void Register() override
{
OnHit += SpellHitFn(spell_putricide_slime_puddle_aura_SpellScript::ReplaceAura);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_putricide_slime_puddle_aura_SpellScript();
}
};
class spell_putricide_unstable_experiment : public SpellScriptLoader
{
public:
spell_putricide_unstable_experiment() : SpellScriptLoader("spell_putricide_unstable_experiment") { }
class spell_putricide_unstable_experiment_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_unstable_experiment_SpellScript);
void HandleScript(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
if (GetCaster()->GetTypeId() != TYPEID_UNIT)
return;
Creature* creature = GetCaster()->ToCreature();
uint32 stage = creature->AI()->GetData(DATA_EXPERIMENT_STAGE);
creature->AI()->SetData(DATA_EXPERIMENT_STAGE, stage ^ true);
Creature* target = NULL;
std::list<Creature*> creList;
GetCreatureListWithEntryInGrid(creList, GetCaster(), NPC_ABOMINATION_WING_MAD_SCIENTIST_STALKER, 200.0f);
// 2 of them are spawned at green place - weird trick blizz
for (std::list<Creature*>::iterator itr = creList.begin(); itr != creList.end(); ++itr)
{
target = *itr;
std::list<Creature*> tmp;
GetCreatureListWithEntryInGrid(tmp, target, NPC_ABOMINATION_WING_MAD_SCIENTIST_STALKER, 10.0f);
if ((!stage && tmp.size() > 1) || (stage && tmp.size() == 1))
break;
}
GetCaster()->CastSpell(target, uint32(GetSpellInfo()->GetEffect(stage)->CalcValue()), true);
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_putricide_unstable_experiment_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_putricide_unstable_experiment_SpellScript();
}
};
class spell_putricide_ooze_eruption_searcher : public SpellScriptLoader
{
public:
spell_putricide_ooze_eruption_searcher() : SpellScriptLoader("spell_putricide_ooze_eruption_searcher") { }
class spell_putricide_ooze_eruption_searcher_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_ooze_eruption_searcher_SpellScript);
void HandleDummy(SpellEffIndex /*effIndex*/)
{
if (GetHitUnit()->HasAura(SPELL_VOLATILE_OOZE_ADHESIVE))
{
GetHitUnit()->RemoveAurasDueToSpell(SPELL_VOLATILE_OOZE_ADHESIVE, GetCaster()->GetGUID(), 0, AURA_REMOVE_BY_ENEMY_SPELL);
GetCaster()->CastSpell(GetHitUnit(), SPELL_OOZE_ERUPTION, true);
}
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_putricide_ooze_eruption_searcher_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_putricide_ooze_eruption_searcher_SpellScript();
}
};
// 71770 - Ooze Spell Tank Protection
class spell_putricide_ooze_tank_protection : public SpellScriptLoader
{
public:
spell_putricide_ooze_tank_protection() : SpellScriptLoader("spell_putricide_ooze_tank_protection") { }
class spell_putricide_ooze_tank_protection_AuraScript : public AuraScript
{
PrepareAuraScript(spell_putricide_ooze_tank_protection_AuraScript);
bool Validate(SpellInfo const* spellInfo) override
{
SpellEffectInfo const* effect0 = spellInfo->GetEffect(EFFECT_0);
SpellEffectInfo const* effect1 = spellInfo->GetEffect(EFFECT_1);
return effect0 && effect1 && ValidateSpellInfo({ effect0->TriggerSpell, effect1->TriggerSpell });
}
void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo)
{
PreventDefaultAction();
Unit* actionTarget = eventInfo.GetActionTarget();
actionTarget->CastSpell((Unit*)nullptr, aurEff->GetSpellEffectInfo()->TriggerSpell, true, nullptr, aurEff);
}
void Register() override
{
OnEffectProc += AuraEffectProcFn(spell_putricide_ooze_tank_protection_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL);
OnEffectProc += AuraEffectProcFn(spell_putricide_ooze_tank_protection_AuraScript::HandleProc, EFFECT_1, SPELL_AURA_PROC_TRIGGER_SPELL);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_putricide_ooze_tank_protection_AuraScript();
}
};
class spell_putricide_choking_gas_bomb : public SpellScriptLoader
{
public:
spell_putricide_choking_gas_bomb() : SpellScriptLoader("spell_putricide_choking_gas_bomb") { }
class spell_putricide_choking_gas_bomb_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_choking_gas_bomb_SpellScript);
void HandleScript(SpellEffIndex /*effIndex*/)
{
uint32 skipIndex = urand(0, 2);
for (SpellEffectInfo const* effect : GetSpellInfo()->GetEffectsForDifficulty(GetCaster()->GetMap()->GetDifficultyID()))
{
if (!effect || effect->EffectIndex == skipIndex)
continue;
uint32 spellId = uint32(effect->CalcValue());
GetCaster()->CastSpell(GetCaster(), spellId, true, NULL, NULL, GetCaster()->GetGUID());
}
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_putricide_choking_gas_bomb_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_putricide_choking_gas_bomb_SpellScript();
}
};
class spell_putricide_unbound_plague : public SpellScriptLoader
{
public:
spell_putricide_unbound_plague() : SpellScriptLoader("spell_putricide_unbound_plague") { }
class spell_putricide_unbound_plague_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_unbound_plague_SpellScript);
bool Validate(SpellInfo const* /*spell*/) override
{
return ValidateSpellInfo({ SPELL_UNBOUND_PLAGUE, SPELL_UNBOUND_PLAGUE_SEARCHER });
}
void FilterTargets(std::list<WorldObject*>& targets)
{
if (AuraEffect const* eff = GetCaster()->GetAuraEffect(SPELL_UNBOUND_PLAGUE_SEARCHER, EFFECT_0))
{
if (eff->GetTickNumber() < 2)
{
targets.clear();
return;
}
}
targets.remove_if(Trinity::UnitAuraCheck(true, SPELL_UNBOUND_PLAGUE));
Trinity::Containers::RandomResize(targets, 1);
}
void HandleScript(SpellEffIndex /*effIndex*/)
{
if (!GetHitUnit())
return;
InstanceScript* instance = GetCaster()->GetInstanceScript();
if (!instance)
return;
if (!GetHitUnit()->HasAura(SPELL_UNBOUND_PLAGUE))
{
if (Creature* professor = ObjectAccessor::GetCreature(*GetCaster(), instance->GetGuidData(DATA_PROFESSOR_PUTRICIDE)))
{
if (Aura* oldPlague = GetCaster()->GetAura(SPELL_UNBOUND_PLAGUE, professor->GetGUID()))
{
if (Aura* newPlague = professor->AddAura(SPELL_UNBOUND_PLAGUE, GetHitUnit()))
{
newPlague->SetMaxDuration(oldPlague->GetMaxDuration());
newPlague->SetDuration(oldPlague->GetDuration());
oldPlague->Remove();
GetCaster()->RemoveAurasDueToSpell(SPELL_UNBOUND_PLAGUE_SEARCHER);
GetCaster()->CastSpell(GetCaster(), SPELL_PLAGUE_SICKNESS, true);
GetCaster()->CastSpell(GetCaster(), SPELL_UNBOUND_PLAGUE_PROTECTION, true);
professor->CastSpell(GetHitUnit(), SPELL_UNBOUND_PLAGUE_SEARCHER, true);
}
}
}
}
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_unbound_plague_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ALLY);
OnEffectHitTarget += SpellEffectFn(spell_putricide_unbound_plague_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_putricide_unbound_plague_SpellScript();
}
};
class spell_putricide_eat_ooze : public SpellScriptLoader
{
public:
spell_putricide_eat_ooze() : SpellScriptLoader("spell_putricide_eat_ooze") { }
class spell_putricide_eat_ooze_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_eat_ooze_SpellScript);
void SelectTarget(std::list<WorldObject*>& targets)
{
if (targets.empty())
return;
targets.sort(Trinity::ObjectDistanceOrderPred(GetCaster()));
WorldObject* target = targets.front();
targets.clear();
targets.push_back(target);
}
void HandleScript(SpellEffIndex /*effIndex*/)
{
Creature* target = GetHitCreature();
if (!target)
return;
if (Aura* grow = target->GetAura(uint32(GetEffectValue())))
{
if (grow->GetStackAmount() < 3)
{
target->RemoveAurasDueToSpell(SPELL_GROW_STACKER);
target->RemoveAura(grow);
target->DespawnOrUnsummon(1);
}
else
grow->ModStackAmount(-3);
}
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_putricide_eat_ooze_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_eat_ooze_SpellScript::SelectTarget, EFFECT_0, TARGET_UNIT_DEST_AREA_ENTRY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_putricide_eat_ooze_SpellScript();
}
};
class spell_putricide_mutated_plague : public SpellScriptLoader
{
public:
spell_putricide_mutated_plague() : SpellScriptLoader("spell_putricide_mutated_plague") { }
class spell_putricide_mutated_plague_AuraScript : public AuraScript
{
PrepareAuraScript(spell_putricide_mutated_plague_AuraScript);
void HandleTriggerSpell(AuraEffect const* aurEff)
{
PreventDefaultAction();
Unit* caster = GetCaster();
if (!caster)
return;
uint32 triggerSpell = GetSpellInfo()->GetEffect(aurEff->GetEffIndex())->TriggerSpell;
SpellInfo const* spell = sSpellMgr->AssertSpellInfo(triggerSpell);
int32 damage = spell->GetEffect(EFFECT_0)->CalcValue(caster);
float multiplier = 2.0f;
if (GetTarget()->GetMap()->Is25ManRaid())
multiplier = 3.0f;
damage *= int32(pow(multiplier, GetStackAmount()));
damage = int32(damage * 1.5f);
GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_BASE_POINT0, damage, GetTarget(), true, NULL, aurEff, GetCasterGUID());
}
void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
uint32 healSpell = uint32(GetSpellInfo()->GetEffect(EFFECT_0)->CalcValue());
SpellInfo const* healSpellInfo = sSpellMgr->GetSpellInfo(healSpell);
if (!healSpellInfo)
return;
int32 heal = healSpellInfo->GetEffect(EFFECT_0)->CalcValue() * GetStackAmount();
GetTarget()->CastCustomSpell(healSpell, SPELLVALUE_BASE_POINT0, heal, GetTarget(), true, NULL, NULL, GetCasterGUID());
}
void Register() override
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_putricide_mutated_plague_AuraScript::HandleTriggerSpell, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL);
AfterEffectRemove += AuraEffectRemoveFn(spell_putricide_mutated_plague_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_putricide_mutated_plague_AuraScript();
}
};
class spell_putricide_mutation_init : public SpellScriptLoader
{
public:
spell_putricide_mutation_init() : SpellScriptLoader("spell_putricide_mutation_init") { }
class spell_putricide_mutation_init_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_mutation_init_SpellScript);
SpellCastResult CheckRequirementInternal(SpellCustomErrors& extendedError)
{
InstanceScript* instance = GetExplTargetUnit()->GetInstanceScript();
if (!instance)
return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW;
Creature* professor = ObjectAccessor::GetCreature(*GetExplTargetUnit(), instance->GetGuidData(DATA_PROFESSOR_PUTRICIDE));
if (!professor)
return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW;
if (professor->AI()->GetData(DATA_PHASE) == PHASE_COMBAT_3 || !professor->IsAlive())
{
extendedError = SPELL_CUSTOM_ERROR_ALL_POTIONS_USED;
return SPELL_FAILED_CUSTOM_ERROR;
}
if (professor->AI()->GetData(DATA_ABOMINATION))
{
extendedError = SPELL_CUSTOM_ERROR_TOO_MANY_ABOMINATIONS;
return SPELL_FAILED_CUSTOM_ERROR;
}
return SPELL_CAST_OK;
}
SpellCastResult CheckRequirement()
{
if (!GetExplTargetUnit())
return SPELL_FAILED_BAD_TARGETS;
if (GetExplTargetUnit()->GetTypeId() != TYPEID_PLAYER)
return SPELL_FAILED_TARGET_NOT_PLAYER;
SpellCustomErrors extension = SPELL_CUSTOM_ERROR_NONE;
SpellCastResult result = CheckRequirementInternal(extension);
if (result != SPELL_CAST_OK)
{
Spell::SendCastResult(GetExplTargetUnit()->ToPlayer(), GetSpellInfo(), GetSpell()->m_SpellVisual, GetSpell()->m_castId, result, extension);
return result;
}
return SPELL_CAST_OK;
}
void Register() override
{
OnCheckCast += SpellCheckCastFn(spell_putricide_mutation_init_SpellScript::CheckRequirement);
}
};
class spell_putricide_mutation_init_AuraScript : public AuraScript
{
PrepareAuraScript(spell_putricide_mutation_init_AuraScript);
void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
uint32 spellId = 70311;
if (GetTarget()->GetMap()->Is25ManRaid())
spellId = 71503;
GetTarget()->CastSpell(GetTarget(), spellId, true);
}
void Register() override
{
AfterEffectRemove += AuraEffectRemoveFn(spell_putricide_mutation_init_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_putricide_mutation_init_SpellScript();
}
AuraScript* GetAuraScript() const override
{
return new spell_putricide_mutation_init_AuraScript();
}
};
class spell_putricide_mutated_transformation_dismiss : public SpellScriptLoader
{
public:
spell_putricide_mutated_transformation_dismiss() : SpellScriptLoader("spell_putricide_mutated_transformation_dismiss") { }
class spell_putricide_mutated_transformation_dismiss_AuraScript : public AuraScript
{
PrepareAuraScript(spell_putricide_mutated_transformation_dismiss_AuraScript);
void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
if (Vehicle* veh = GetTarget()->GetVehicleKit())
veh->RemoveAllPassengers();
}
void Register() override
{
AfterEffectRemove += AuraEffectRemoveFn(spell_putricide_mutated_transformation_dismiss_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_putricide_mutated_transformation_dismiss_AuraScript();
}
};
class spell_putricide_mutated_transformation : public SpellScriptLoader
{
public:
spell_putricide_mutated_transformation() : SpellScriptLoader("spell_putricide_mutated_transformation") { }
class spell_putricide_mutated_transformation_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_mutated_transformation_SpellScript);
void HandleSummon(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
Unit* caster = GetOriginalCaster();
if (!caster)
return;
InstanceScript* instance = caster->GetInstanceScript();
if (!instance)
return;
Creature* putricide = ObjectAccessor::GetCreature(*caster, instance->GetGuidData(DATA_PROFESSOR_PUTRICIDE));
if (!putricide)
return;
if (putricide->AI()->GetData(DATA_ABOMINATION))
{
if (Player* player = caster->ToPlayer())
Spell::SendCastResult(player, GetSpellInfo(), GetSpell()->m_SpellVisual, GetSpell()->m_castId, SPELL_FAILED_CUSTOM_ERROR, SPELL_CUSTOM_ERROR_TOO_MANY_ABOMINATIONS);
return;
}
uint32 entry = uint32(GetSpellInfo()->GetEffect(effIndex)->MiscValue);
SummonPropertiesEntry const* properties = sSummonPropertiesStore.LookupEntry(uint32(GetSpellInfo()->GetEffect(effIndex)->MiscValueB));
uint32 duration = uint32(GetSpellInfo()->GetDuration());
Position pos = caster->GetPosition();
TempSummon* summon = caster->GetMap()->SummonCreature(entry, pos, properties, duration, caster, GetSpellInfo()->Id);
if (!summon || !summon->IsVehicle())
return;
summon->CastSpell(summon, SPELL_ABOMINATION_VEHICLE_POWER_DRAIN, true);
summon->CastSpell(summon, SPELL_MUTATED_TRANSFORMATION_DAMAGE, true);
caster->CastSpell(summon, SPELL_MUTATED_TRANSFORMATION_NAME, true);
caster->EnterVehicle(summon, 0); // VEHICLE_SPELL_RIDE_HARDCODED is used according to sniff, this is ok
summon->SetCreatorGUID(caster->GetGUID());
putricide->AI()->JustSummoned(summon);
}
void Register() override
{
OnEffectHit += SpellEffectFn(spell_putricide_mutated_transformation_SpellScript::HandleSummon, EFFECT_0, SPELL_EFFECT_SUMMON);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_putricide_mutated_transformation_SpellScript();
}
};
class spell_putricide_mutated_transformation_dmg : public SpellScriptLoader
{
public:
spell_putricide_mutated_transformation_dmg() : SpellScriptLoader("spell_putricide_mutated_transformation_dmg") { }
class spell_putricide_mutated_transformation_dmg_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_mutated_transformation_dmg_SpellScript);
void FilterTargetsInitial(std::list<WorldObject*>& targets)
{
if (Unit* owner = ObjectAccessor::GetUnit(*GetCaster(), GetCaster()->GetCreatorGUID()))
targets.remove(owner);
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_putricide_mutated_transformation_dmg_SpellScript::FilterTargetsInitial, EFFECT_0, TARGET_UNIT_SRC_AREA_ALLY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_putricide_mutated_transformation_dmg_SpellScript();
}
};
class spell_putricide_regurgitated_ooze : public SpellScriptLoader
{
public:
spell_putricide_regurgitated_ooze() : SpellScriptLoader("spell_putricide_regurgitated_ooze") { }
class spell_putricide_regurgitated_ooze_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_regurgitated_ooze_SpellScript);
// the only purpose of this hook is to fail the achievement
void ExtraEffect(SpellEffIndex /*effIndex*/)
{
if (InstanceScript* instance = GetCaster()->GetInstanceScript())
instance->SetData(DATA_NAUSEA_ACHIEVEMENT, uint32(false));
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_putricide_regurgitated_ooze_SpellScript::ExtraEffect, EFFECT_0, SPELL_EFFECT_APPLY_AURA);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_putricide_regurgitated_ooze_SpellScript();
}
};
// Removes aura with id stored in effect value
class spell_putricide_clear_aura_effect_value : public SpellScriptLoader
{
public:
spell_putricide_clear_aura_effect_value() : SpellScriptLoader("spell_putricide_clear_aura_effect_value") { }
class spell_putricide_clear_aura_effect_value_SpellScript : public SpellScript
{
PrepareSpellScript(spell_putricide_clear_aura_effect_value_SpellScript);
void HandleScript(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
GetHitUnit()->RemoveAurasDueToSpell(GetEffectValue());
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_putricide_clear_aura_effect_value_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_putricide_clear_aura_effect_value_SpellScript();
}
};
// Stinky and Precious spell, it's here because its used for both (Festergut and Rotface "pets")
class spell_stinky_precious_decimate : public SpellScriptLoader
{
public:
spell_stinky_precious_decimate() : SpellScriptLoader("spell_stinky_precious_decimate") { }
class spell_stinky_precious_decimate_SpellScript : public SpellScript
{
PrepareSpellScript(spell_stinky_precious_decimate_SpellScript);
void HandleScript(SpellEffIndex /*effIndex*/)
{
if (GetHitUnit()->GetHealthPct() > float(GetEffectValue()))
{
uint32 newHealth = GetHitUnit()->GetMaxHealth() * uint32(GetEffectValue()) / 100;
GetHitUnit()->SetHealth(newHealth);
}
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_stinky_precious_decimate_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_stinky_precious_decimate_SpellScript();
}
};
void AddSC_boss_professor_putricide()
{
new boss_professor_putricide();
new npc_volatile_ooze();
new npc_gas_cloud();
new spell_putricide_gaseous_bloat();
new spell_putricide_ooze_channel();
new spell_putricide_slime_puddle();
new spell_putricide_slime_puddle_aura();
new spell_putricide_unstable_experiment();
new spell_putricide_ooze_eruption_searcher();
new spell_putricide_ooze_tank_protection();
new spell_putricide_choking_gas_bomb();
new spell_putricide_unbound_plague();
new spell_putricide_eat_ooze();
new spell_putricide_mutated_plague();
new spell_putricide_mutation_init();
new spell_putricide_mutated_transformation_dismiss();
new spell_putricide_mutated_transformation();
new spell_putricide_mutated_transformation_dmg();
new spell_putricide_regurgitated_ooze();
new spell_putricide_clear_aura_effect_value();
new spell_stinky_precious_decimate();
}
| Traesh/TrinityCore | src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp | C++ | gpl-2.0 | 68,058 |
<p class="rpbt_show_date">
<input class="checkbox" type="checkbox"<?php checked( $i['show_date'], 1, true ); ?> id="<?php echo $this->get_field_id( 'show_date' ); ?>" name="<?php echo $this->get_field_name( 'show_date' ); ?>" />
<label for="<?php echo $this->get_field_id( 'show_date' ); ?>">
<?php _e( 'Display post date', 'related-posts-by-taxonomy' ); ?>
</label>
</p> | keesiemeijer/related-posts-by-taxonomy | includes/assets/partials/widget/show-date.php | PHP | gpl-2.0 | 376 |
/*
** FamiTracker - NES/Famicom sound tracker
** Copyright (C) 2005-2014 Jonathan Liss
**
** 0CC-FamiTracker is (C) 2014-2018 HertzDevil
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Library General Public License for more details. To obtain a
** copy of the GNU Library General Public License, write to the Free
** Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**
** Any permitted reproduction of these routines, in whole or in part,
** must bear this legend.
*/
#include "APU/MMC5.h"
#include "APU/Types.h"
#include "RegisterState.h" // // //
// MMC5 external sound
CMMC5::CMMC5(CMixer &Mixer, std::uint8_t nInstance) :
CSoundChip(Mixer, nInstance), // // //
m_Square1(Mixer, nInstance, sound_chip_t::MMC5, value_cast(mmc5_subindex_t::pulse1)),
m_Square2(Mixer, nInstance, sound_chip_t::MMC5, value_cast(mmc5_subindex_t::pulse2)),
m_iMulLow(0),
m_iMulHigh(0)
{
m_pRegisterLogger->AddRegisterRange(0x5000, 0x5007); // // //
m_pRegisterLogger->AddRegisterRange(0x5015, 0x5015);
}
sound_chip_t CMMC5::GetID() const { // // //
return sound_chip_t::MMC5;
}
void CMMC5::Reset()
{
m_Square1.Reset();
m_Square2.Reset();
m_Square1.Write(0x01, 0x08);
m_Square2.Write(0x01, 0x08);
}
void CMMC5::Write(uint16_t Address, uint8_t Value)
{
if (Address >= 0x5C00 && Address <= 0x5FF5) {
m_iEXRAM[Address & 0x3FF] = Value;
return;
}
switch (Address) {
// Channel 1
case 0x5000:
m_Square1.Write(0, Value);
break;
case 0x5002:
m_Square1.Write(2, Value);
break;
case 0x5003:
m_Square1.Write(3, Value);
break;
// Channel 2
case 0x5004:
m_Square2.Write(0, Value);
break;
case 0x5006:
m_Square2.Write(2, Value);
break;
case 0x5007:
m_Square2.Write(3, Value);
break;
// Channel 3... (doesn't exist)
// Control
case 0x5015:
m_Square1.WriteControl(Value & 1);
m_Square2.WriteControl((Value >> 1) & 1);
break;
// Hardware multiplier
case 0x5205:
m_iMulLow = Value;
break;
case 0x5206:
m_iMulHigh = Value;
break;
}
}
uint8_t CMMC5::Read(uint16_t Address, bool &Mapped)
{
if (Address >= 0x5C00 && Address <= 0x5FF5) {
Mapped = true;
return m_iEXRAM[Address & 0x3FF];
}
switch (Address) {
case 0x5205:
Mapped = true;
return (m_iMulLow * m_iMulHigh) & 0xFF;
case 0x5206:
Mapped = true;
return (m_iMulLow * m_iMulHigh) >> 8;
}
return 0;
}
void CMMC5::EndFrame()
{
m_Square1.EndFrame();
m_Square2.EndFrame();
}
void CMMC5::Process(uint32_t Time)
{
m_Square1.Process(Time);
m_Square2.Process(Time);
}
double CMMC5::GetFreq(int Channel) const // // //
{
switch (Channel) {
case 0: return m_Square1.GetFrequency();
case 1: return m_Square2.GetFrequency();
}
return 0.;
}
void CMMC5::LengthCounterUpdate()
{
m_Square1.LengthCounterUpdate();
m_Square2.LengthCounterUpdate();
}
void CMMC5::EnvelopeUpdate()
{
m_Square1.EnvelopeUpdate();
m_Square2.EnvelopeUpdate();
}
void CMMC5::ClockSequence()
{
EnvelopeUpdate(); // // //
LengthCounterUpdate(); // // //
}
| jpmac26/0CC-FamiTracker | Source/APU/MMC5.cpp | C++ | gpl-2.0 | 3,583 |
/*
* Created on Mar 22, 2013
* Created by Paul Gardner
*
* Copyright 2013 Azureus Software, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
package com.aelitis.azureus.core.tag.impl;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.gudy.azureus2.core3.download.DownloadManager;
import org.gudy.azureus2.core3.download.DownloadManagerState;
import org.gudy.azureus2.core3.download.DownloadManagerStats;
import org.gudy.azureus2.core3.util.AERunnable;
import org.gudy.azureus2.core3.util.AsyncDispatcher;
import org.gudy.azureus2.core3.util.Debug;
import org.gudy.azureus2.core3.util.SystemTime;
import com.aelitis.azureus.core.networkmanager.LimitedRateGroup;
import com.aelitis.azureus.core.tag.Tag;
import com.aelitis.azureus.core.tag.TagDownload;
import com.aelitis.azureus.core.tag.TagFeature;
import com.aelitis.azureus.core.tag.TagFeatureProperties;
import com.aelitis.azureus.core.tag.TagFeatureRateLimit;
import com.aelitis.azureus.core.tag.TagFeatureRunState;
import com.aelitis.azureus.core.tag.TagListener;
import com.aelitis.azureus.core.tag.Taggable;
public class
TagDownloadWithState
extends TagWithState
implements TagDownload
{
private int upload_rate_limit;
private int download_rate_limit;
private int upload_rate = -1;
private int download_rate = -1;
private long last_rate_update;
private Object UPLOAD_PRIORITY_ADDED_KEY = new Object();
private int upload_priority;
private int min_share_ratio;
private int max_share_ratio;
private boolean supports_xcode;
private boolean supports_file_location;
private LimitedRateGroup upload_limiter =
new LimitedRateGroup()
{
public String
getName()
{
return( "tag_up: " + getTagName( true ));
}
public int
getRateLimitBytesPerSecond()
{
return( upload_rate_limit );
}
public void
updateBytesUsed(
int used )
{
}
};
private LimitedRateGroup download_limiter =
new LimitedRateGroup()
{
public String
getName()
{
return( "tag_down: " + getTagName( true ));
}
public int
getRateLimitBytesPerSecond()
{
return( download_rate_limit );
}
public void
updateBytesUsed(
int used )
{
}
};
private boolean do_rates;
private boolean do_up;
private boolean do_down;
private int run_states;
private static AsyncDispatcher rs_async = new AsyncDispatcher(2000);
private TagProperty[] tag_properties =
new TagProperty[]{
createTagProperty( TagFeatureProperties.PR_TRACKERS, TagFeatureProperties.PT_STRING_LIST ),
createTagProperty( TagFeatureProperties.PR_UNTAGGED, TagFeatureProperties.PT_BOOLEAN ),
createTagProperty( TagFeatureProperties.PR_TRACKER_TEMPLATES, TagFeatureProperties.PT_STRING_LIST ),
createTagProperty( TagFeatureProperties.PR_CONSTRAINT, TagFeatureProperties.PT_STRING_LIST )
};
public
TagDownloadWithState(
TagTypeBase tt,
int tag_id,
String name,
boolean do_rates,
boolean do_up,
boolean do_down,
int run_states )
{
super( tt, tag_id, name );
init( do_rates, do_up, do_down, run_states );
}
protected
TagDownloadWithState(
TagTypeBase tt,
int tag_id,
Map details,
boolean do_rates,
boolean do_up,
boolean do_down,
int run_states )
{
super( tt, tag_id, details );
init( do_rates, do_up, do_down, run_states );
}
private void
init(
boolean _do_rates,
boolean _do_up,
boolean _do_down,
int _run_states )
{
do_rates = _do_rates;
do_up = _do_up;
do_down = _do_down;
run_states = _run_states;
if ( do_up ){
upload_rate_limit = (int)readLongAttribute( AT_RATELIMIT_UP, 0 );
}
if ( do_down ){
download_rate_limit = (int)readLongAttribute( AT_RATELIMIT_DOWN, 0 );
}
upload_priority = (int)readLongAttribute( AT_RATELIMIT_UP_PRI, 0 );
min_share_ratio = (int)readLongAttribute( AT_RATELIMIT_MIN_SR, 0 );
max_share_ratio = (int)readLongAttribute( AT_RATELIMIT_MAX_SR, 0 );
addTagListener(
new TagListener()
{
public void
taggableAdded(
Tag tag,
Taggable tagged )
{
DownloadManager manager = (DownloadManager)tagged;
manager.addRateLimiter( upload_limiter, true );
manager.addRateLimiter( download_limiter, false );
if ( upload_priority > 0 ){
manager.updateAutoUploadPriority( UPLOAD_PRIORITY_ADDED_KEY, true );
}
if ( min_share_ratio > 0 ){
updateMinShareRatio( manager, min_share_ratio );
}
if ( max_share_ratio > 0 ){
updateMaxShareRatio( manager, max_share_ratio );
}
}
public void
taggableSync(
Tag tag )
{
}
public void
taggableRemoved(
Tag tag,
Taggable tagged )
{
DownloadManager manager = (DownloadManager)tagged;
manager.removeRateLimiter( upload_limiter, true );
manager.removeRateLimiter( download_limiter, false );
if ( upload_priority > 0 ){
manager.updateAutoUploadPriority( UPLOAD_PRIORITY_ADDED_KEY, false );
}
if ( min_share_ratio > 0 ){
updateMinShareRatio( manager, 0 );
}
if ( max_share_ratio > 0 ){
updateMaxShareRatio( manager, 0 );
}
}
private void
updateMinShareRatio(
DownloadManager manager,
int sr )
{
List<Tag> dm_tags = getTagType().getTagsForTaggable( manager );
for ( Tag t: dm_tags ){
if ( t == TagDownloadWithState.this ){
continue;
}
if ( t instanceof TagFeatureRateLimit ){
int o_sr = ((TagFeatureRateLimit)t).getTagMinShareRatio();
if ( o_sr > sr ){
sr = o_sr;
}
}
}
manager.getDownloadState().setIntParameter( DownloadManagerState.PARAM_MIN_SHARE_RATIO, sr );
}
private void
updateMaxShareRatio(
DownloadManager manager,
int sr )
{
List<Tag> dm_tags = getTagType().getTagsForTaggable( manager );
for ( Tag t: dm_tags ){
if ( t == TagDownloadWithState.this ){
continue;
}
if ( t instanceof TagFeatureRateLimit ){
int o_sr = ((TagFeatureRateLimit)t).getTagMaxShareRatio();
if ( o_sr > sr ){
sr = o_sr;
}
}
}
manager.getDownloadState().setIntParameter( DownloadManagerState.PARAM_MAX_SHARE_RATIO, sr );
}
},
true );
}
@Override
public void
removeTag()
{
for ( DownloadManager dm: getTaggedDownloads()){
dm.removeRateLimiter( upload_limiter, true );
dm.removeRateLimiter( download_limiter, false );
if ( upload_priority > 0 ){
dm.updateAutoUploadPriority( UPLOAD_PRIORITY_ADDED_KEY, false );
}
}
super.removeTag();
}
@Override
public void
addTaggable(
Taggable t )
{
if ( t instanceof DownloadManager ){
DownloadManager dm = (DownloadManager)t;
if ( dm.isDestroyed()){
Debug.out( "Invalid Taggable added - download is destroyed: " + dm.getDisplayName());
}else{
super.addTaggable( t );
}
}else{
Debug.out( "Invalid Taggable added: " + t );
}
}
public int
getTaggableTypes()
{
return( Taggable.TT_DOWNLOAD );
}
public Set<DownloadManager>
getTaggedDownloads()
{
return((Set<DownloadManager>)(Object)getTagged());
}
public boolean
supportsTagRates()
{
return( do_rates );
}
public boolean
supportsTagUploadLimit()
{
return( do_up );
}
public boolean
supportsTagDownloadLimit()
{
return( do_down );
}
public int
getTagUploadLimit()
{
return( upload_rate_limit );
}
public void
setTagUploadLimit(
int bps )
{
if ( upload_rate_limit == bps ){
return;
}
if ( !do_up ){
Debug.out( "Not supported" );
return;
}
upload_rate_limit = bps;
writeLongAttribute( AT_RATELIMIT_UP, upload_rate_limit );
}
public int
getTagCurrentUploadRate()
{
updateRates();
return( upload_rate );
}
public int
getTagDownloadLimit()
{
return( download_rate_limit );
}
public void
setTagDownloadLimit(
int bps )
{
if ( download_rate_limit == bps ){
return;
}
if ( !do_down ){
Debug.out( "Not supported" );
return;
}
download_rate_limit = bps;
writeLongAttribute( AT_RATELIMIT_DOWN, download_rate_limit );
}
public int
getTagCurrentDownloadRate()
{
updateRates();
return( download_rate );
}
public int
getTagUploadPriority()
{
return( upload_priority );
}
public void
setTagUploadPriority(
int priority )
{
if ( priority < 0 ){
priority = 0;
}
if ( priority == upload_priority ){
return;
}
int old_up = upload_priority;
upload_priority = priority;
writeLongAttribute( AT_RATELIMIT_UP_PRI, priority );
if ( old_up == 0 || priority == 0 ){
Set<DownloadManager> dms = getTaggedDownloads();
for ( DownloadManager dm: dms ){
dm.updateAutoUploadPriority( UPLOAD_PRIORITY_ADDED_KEY, priority>0 );
}
}
}
public int
getTagMinShareRatio()
{
return( min_share_ratio );
}
public void
setTagMinShareRatio(
int sr )
{
if ( sr < 0 ){
sr = 0;
}
if ( sr == min_share_ratio ){
return;
}
min_share_ratio = sr;
writeLongAttribute( AT_RATELIMIT_MIN_SR, sr );
Set<DownloadManager> dms = getTaggedDownloads();
for ( DownloadManager dm: dms ){
List<Tag> dm_tags = getTagType().getTagsForTaggable( dm );
for ( Tag t: dm_tags ){
if ( t == this ){
continue;
}
if ( t instanceof TagFeatureRateLimit ){
int o_sr = ((TagFeatureRateLimit)t).getTagMinShareRatio();
if ( o_sr > sr ){
sr = o_sr;
}
}
}
dm.getDownloadState().setIntParameter( DownloadManagerState.PARAM_MIN_SHARE_RATIO, sr );
}
}
public int
getTagMaxShareRatio()
{
return( max_share_ratio );
}
public void
setTagMaxShareRatio(
int sr )
{
if ( sr < 0 ){
sr = 0;
}
if ( sr == max_share_ratio ){
return;
}
max_share_ratio = sr;
writeLongAttribute( AT_RATELIMIT_MAX_SR, sr );
Set<DownloadManager> dms = getTaggedDownloads();
for ( DownloadManager dm: dms ){
List<Tag> dm_tags = getTagType().getTagsForTaggable( dm );
for ( Tag t: dm_tags ){
if ( t == this ){
continue;
}
if ( t instanceof TagFeatureRateLimit ){
int o_sr = ((TagFeatureRateLimit)t).getTagMaxShareRatio();
if ( o_sr > sr ){
sr = o_sr;
}
}
}
dm.getDownloadState().setIntParameter( DownloadManagerState.PARAM_MAX_SHARE_RATIO, sr );
}
}
private void
updateRates()
{
long now = SystemTime.getCurrentTime();
if ( now - last_rate_update > 2500 ){
int new_up = 0;
int new_down = 0;
Set<DownloadManager> dms = getTaggedDownloads();
if ( dms.size() == 0 ){
new_up = -1;
new_down = -1;
}else{
new_up = 0;
new_down = 0;
for ( DownloadManager dm: dms ){
DownloadManagerStats stats = dm.getStats();
new_up += stats.getDataSendRate() + stats.getProtocolSendRate();
new_down += stats.getDataReceiveRate() + stats.getProtocolReceiveRate();
}
}
upload_rate = new_up;
download_rate = new_down;
last_rate_update = now;
}
}
public int
getRunStateCapabilities()
{
return( run_states );
}
public boolean
hasRunStateCapability(
int capability )
{
return((run_states & capability ) != 0 );
}
public boolean[]
getPerformableOperations(
int[] ops )
{
boolean[] result = new boolean[ ops.length];
Set<DownloadManager> dms = getTaggedDownloads();
for ( DownloadManager dm: dms ){
int dm_state = dm.getState();
for ( int i=0;i<ops.length;i++){
if ( result[i]){
continue;
}
int op = ops[i];
if (( op & TagFeatureRunState.RSC_START ) != 0 ){
if ( dm_state == DownloadManager.STATE_STOPPED ||
dm_state == DownloadManager.STATE_ERROR ){
result[i] = true;
}
}
if (( op & TagFeatureRunState.RSC_STOP ) != 0 ){
if ( dm_state != DownloadManager.STATE_STOPPED &&
dm_state != DownloadManager.STATE_STOPPING &&
dm_state != DownloadManager.STATE_ERROR ){
result[i] = true;
}
}
if (( op & TagFeatureRunState.RSC_PAUSE ) != 0 ){
if ( dm_state != DownloadManager.STATE_STOPPED &&
dm_state != DownloadManager.STATE_STOPPING &&
dm_state != DownloadManager.STATE_ERROR ){
if ( !dm.isPaused()){
result[i] = true;
}
}
}
if (( op & TagFeatureRunState.RSC_RESUME ) != 0 ){
if ( dm.isPaused()){
result[i] = true;
}
}
}
}
return( result );
}
public void
performOperation(
int op )
{
Set<DownloadManager> dms = getTaggedDownloads();
for ( final DownloadManager dm: dms ){
int dm_state = dm.getState();
if ( op == TagFeatureRunState.RSC_START ){
if ( dm_state == DownloadManager.STATE_STOPPED ||
dm_state == DownloadManager.STATE_ERROR ){
rs_async.dispatch(
new AERunnable()
{
public void
runSupport()
{
dm.setStateQueued();
}
});
}
}else if ( op == TagFeatureRunState.RSC_STOP ){
if ( dm_state != DownloadManager.STATE_STOPPED &&
dm_state != DownloadManager.STATE_STOPPING &&
dm_state != DownloadManager.STATE_ERROR ){
rs_async.dispatch(
new AERunnable()
{
public void
runSupport()
{
dm.stopIt( DownloadManager.STATE_STOPPED, false, false );
}
});
}
}else if ( op == TagFeatureRunState.RSC_PAUSE ){
if ( dm_state != DownloadManager.STATE_STOPPED &&
dm_state != DownloadManager.STATE_STOPPING &&
dm_state != DownloadManager.STATE_ERROR ){
rs_async.dispatch(
new AERunnable()
{
public void
runSupport()
{
dm.pause();
}
});
}
}else if ( op == TagFeatureRunState.RSC_RESUME ){
if ( dm.isPaused()){
rs_async.dispatch(
new AERunnable()
{
public void
runSupport()
{
dm.resume();
}
});
}
}
}
}
protected void
setSupportsTagTranscode(
boolean sup )
{
supports_xcode = sup;
}
public boolean
supportsTagTranscode()
{
return( supports_xcode );
}
public String[]
getTagTranscodeTarget()
{
String temp = readStringAttribute( AT_XCODE_TARGET, null );
if ( temp == null ){
return( null );
}
String[] bits = temp.split( "\n" );
if ( bits.length != 2 ){
return( null );
}
return( bits );
}
public void
setTagTranscodeTarget(
String uid,
String name )
{
writeStringAttribute( AT_XCODE_TARGET, uid==null?null:(uid + "\n" + name ));
getTagType().fireChanged( this );
getManager().featureChanged( this, TagFeature.TF_XCODE );
}
protected void
setSupportsFileLocation(
boolean sup )
{
supports_file_location = sup;
}
@Override
public boolean
supportsTagInitialSaveFolder()
{
return( supports_file_location );
}
@Override
public boolean
supportsTagMoveOnComplete()
{
return( supports_file_location );
}
@Override
public boolean
supportsTagCopyOnComplete()
{
return( supports_file_location );
}
@Override
public TagProperty[]
getSupportedProperties()
{
return( getTagType().isTagTypeAuto()?new TagProperty[0]:tag_properties );
}
@Override
public boolean
isTagAuto()
{
TagProperty[] props = getSupportedProperties();
for ( TagProperty prop: props ){
String name = prop.getName( false );
if ( name.equals( TagFeatureProperties.PR_TRACKER_TEMPLATES )){
continue;
}
int type = prop.getType();
if ( type == TagFeatureProperties.PT_BOOLEAN ){
Boolean b = prop.getBoolean();
if ( b != null && b ){
return( true );
}
}else if ( type == TagFeatureProperties.PT_STRING_LIST ){
String[] val = prop.getStringList();
if ( val != null && val.length > 0 ){
return( true );
}
}
}
return( false );
}
}
| AcademicTorrents/AcademicTorrents-Downloader | vuze/com/aelitis/azureus/core/tag/impl/TagDownloadWithState.java | Java | gpl-2.0 | 18,123 |