repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
damonsharp/dws_s | 404.php | 1776 | <?php
/**
* The template for displaying 404 pages (not found).
*
* @link https://codex.wordpress.org/Creating_an_Error_404_Page
*
* @package DWS_Starter_Theme
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<section class="error-404 not-found">
<header class="page-header">
<h1 class="page-title"><?php esc_html_e( 'Oops! That page can’t be found.', 'dws_s' ); ?></h1>
</header><!-- .page-header -->
<div class="page-content">
<p><?php esc_html_e( 'It looks like nothing was found at this location. Maybe try one of the links below or a search?', 'dws_s' ); ?></p>
<?php get_search_form(); ?>
<?php the_widget( 'WP_Widget_Recent_Posts' ); ?>
<?php if ( dws_s_categorized_blog() ) : // Only show the widget if site has multiple categories. ?>
<div class="widget widget_categories">
<h2 class="widget-title"><?php esc_html_e( 'Most Used Categories', 'dws_s' ); ?></h2>
<ul>
<?php
wp_list_categories( array(
'orderby' => 'count',
'order' => 'DESC',
'show_count' => 1,
'title_li' => '',
'number' => 10,
) );
?>
</ul>
</div><!-- .widget -->
<?php endif; ?>
<?php
/* translators: %1$s: smiley */
$archive_content = '<p>' . sprintf( esc_html__( 'Try looking in the monthly archives. %1$s', 'dws_s' ), convert_smilies( ':)' ) ) . '</p>';
the_widget( 'WP_Widget_Archives', 'dropdown=1', "after_title=</h2>$archive_content" );
?>
<?php the_widget( 'WP_Widget_Tag_Cloud' ); ?>
</div><!-- .page-content -->
</section><!-- .error-404 -->
</main><!-- #main -->
</div><!-- #primary -->
<?php get_footer(); ?>
| gpl-2.0 |
ylatuya/Flumotion | flumotion/component/misc/httpserver/admin_gtk.py | 11840 | # -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the Free Software Foundation.
# This file is distributed without any warranty; without even the implied
# warranty of merchantability or fitness for a particular purpose.
# See "LICENSE.GPL" in the source distribution for more information.
# Licensees having purchased or holding a valid Flumotion Advanced
# Streaming Server license may use this file in accordance with the
# Flumotion Advanced Streaming Server Commercial License Agreement.
# See "LICENSE.Flumotion" in the source distribution for more information.
# Headers in this file shall remain intact.
import time
import gettext
import os
import webbrowser
import gtk
from flumotion.common.i18n import N_
from flumotion.common.format import formatTime, formatStorage, formatTimeStamp
from flumotion.component.base.admin_gtk import BaseAdminGtk
from flumotion.component.base.baseadminnode import BaseAdminGtkNode
from flumotion.ui.linkwidget import LinkWidget
from flumotion.component.misc.httpserver.ondemandbrowser import OnDemandBrowser
__version__ = "$Rev$"
_ = gettext.gettext
class StatisticsAdminGtkNode(BaseAdminGtkNode):
def __init__(self, *args, **kwargs):
BaseAdminGtkNode.__init__(self, *args, **kwargs)
self._shown = False
self._state = None
self._reqStats = {} # {name: (widget, converter, format, default)}
# BaseAdminGtkNode
def haveWidgetTree(self):
self._reqStats = {}
self.widget = self._initWidgets(self.wtree)
if self._state:
self._shown = True
self._refreshStats(self._state)
self.widget.show()
else:
self._defaultStats()
return self.widget
# Public API
def setStats(self, state):
"""Update the state containing all information used by this
interface
@param state:
@type state: AdminComponentUIState
"""
# Set _stats regardless of if condition
# Used to be a race where _stats was
# not set if widget tree was gotten before
# ui state
self._state = state
if not self.widget:
# widget tree not created yet
return
# Update the statistics
self._refreshStats(state)
self._onStateSet(state)
if not self._shown:
# widget tree created but not yet shown
self._shown = True
self.widget.show_all()
# Protected
def _initWidgets(self, wtree):
raise NotImplementedError
def _onStateSet(self, state):
pass
def _defaultStats(self):
pass
def _refreshStats(self, state):
pass
# Private
def _regReqStat(self, name, converter=str, format="%s", default=0):
widget = self.wtree.get_widget('label-' + name)
if not widget:
self.warning("FIXME: no widget %s" % name)
return
self._reqStats[name] = (widget, converter, format, default)
def _refreshStatistics(self, state):
for name in self._reqStats:
widget, converter, format, default = self._reqStats[name]
value = state.get(name)
if value is not None:
widget.set_text(format % converter(value))
else:
widget.set_text(format % converter(default))
def _updateStatistic(self, name, value):
if name not in self._reqStats:
return
widget, converter, format, default = self._reqStats[name]
if value is not None:
widget.set_text(format % converter(value))
else:
widget.set_text(format % converter(default))
class ServerStatsAdminGtkNode(StatisticsAdminGtkNode):
gladeFile = os.path.join('flumotion', 'component', 'misc',
'httpserver', 'httpserver.glade')
def __init__(self, *args, **kwargs):
StatisticsAdminGtkNode.__init__(self, *args, **kwargs)
self._uptime = None
self._link = None
# StatisticsAdminGtkNode
def _initWidgets(self, wtree):
statistics = wtree.get_widget('main_vbox')
self._uptime = wtree.get_widget('label-server-uptime')
self._regReqStat('current-request-count', _formatClientCount)
self._regReqStat('mean-request-count', _formatClientCount)
self._regReqStat('request-count-peak', _formatClientCount)
self._regReqStat('request-count-peak-time', _formatTimeStamp,
_("at %s"))
self._regReqStat('current-request-rate', _formatReqRate)
self._regReqStat('mean-request-rate', _formatReqRate)
self._regReqStat('request-rate-peak', _formatReqRate)
self._regReqStat('request-rate-peak-time', _formatTimeStamp,
_("at %s"))
self._regReqStat('total-bytes-sent', _formatBytes)
self._regReqStat('current-bitrate', _formatBitrate)
self._regReqStat('mean-bitrate', _formatBitrate)
self._regReqStat('bitrate-peak', _formatBitrate)
self._regReqStat('bitrate-peak-time', _formatTimeStamp, _("at %s"))
self._regReqStat('mean-file-read-ratio', _formatPercent)
return statistics
# BaseAdminGtkNode
def stateSetitem(self, state, key, subkey, value):
if key == "request-statistics":
self._updateStatistic(subkey, value)
# StatisticsAdminGtkNode
def _refreshStats(self, state):
self._refreshStatistics(state.get("request-statistics", {}))
def _defaultStats(self):
self._refreshStatistics({})
def _onStateSet(self, state):
# Update the URI
uri = state.get('stream-url')
if uri is not None:
if not self._link:
self._link = self._createLinkWidget(uri)
else:
self._link.set_uri(uri)
# Update Server Uptime
uptime = state.get('server-uptime')
self._uptime.set_text(formatTime(uptime))
# Private
def _createLinkWidget(self, uri):
link = LinkWidget(uri)
link.set_callback(self._on_link_show_url)
link.show_all()
holder = self.wtree.get_widget('link-holder')
holder.add(link)
return link
# Callbacks
def _on_link_show_url(self, url):
webbrowser.open_new(url)
class CacheStatsAdminGtkNode(StatisticsAdminGtkNode):
gladeFile = os.path.join('flumotion', 'component', 'misc',
'httpserver', 'httpserver.glade')
def show(self):
if self.widget:
self.widget.show()
def hide(self):
if self.widget:
self.widget.hide()
# StatisticsAdminGtkNode
def _initWidgets(self, wtree):
statistics = wtree.get_widget('cache_vbox')
self._regReqStat('cache-usage-estimation', _formatBytes)
self._regReqStat('cache-usage-ratio-estimation', _formatPercent)
self._regReqStat('cache-hit-count')
self._regReqStat('temp-hit-count')
self._regReqStat('cache-miss-count')
self._regReqStat('cache-outdate-count')
self._regReqStat('cache-read-ratio', _formatPercent)
self._regReqStat('cleanup-count')
self._regReqStat('last-cleanup-time', _formatTimeStamp)
self._regReqStat('current-copy-count')
self._regReqStat('finished-copy-count')
self._regReqStat('cancelled-copy-count')
return statistics
# BaseAdminGtkNode
def stateSetitem(self, state, key, subkey, value):
if key == "provider-statistics":
self._updateStatistic(subkey, value)
# StatisticsAdminGtkNode
def _refreshStats(self, state):
self._refreshStatistics(state.get("provider-statistics", {}))
def _defaultStats(self):
self._refreshStatistics({})
def _formatClientCount(value):
if isinstance(value, (int, long)):
format = gettext.ngettext(N_("%d client"), N_("%d clients"), value)
else:
format = gettext.ngettext(N_("%.2f client"), N_("%.2f clients"), value)
return format % value
def _formatTimeStamp(value):
return time.strftime("%c", time.localtime(value))
def _formatReqRate(value):
return _("%.2f requests/m") % float(value * 60)
def _formatBytes(value):
return formatStorage(value) + _('Byte')
def _formatBitrate(value):
return formatStorage(value) + _('bit/s')
def _formatPercent(value):
return "%.2f %%" % (value * 100.0)
class BrowserAdminGtkNode(BaseAdminGtkNode):
gladeFile = os.path.join('flumotion', 'component', 'misc',
'httpserver', 'httpserver.glade')
def __init__(self, state, admin, title=None):
BaseAdminGtkNode.__init__(self, state, admin, title)
self.browser = self._create_browser()
self._path = self.state.get('config').get('properties').get('path')
def haveWidgetTree(self):
self.widget = self.wtree.get_widget('browser_vbox')
self.widget.connect('realize', self._on_realize)
self.widget.pack_start(self.browser)
self.browser.show()
self.widget.show_all()
return self.widget
def setUIState(self, state):
BaseAdminGtkNode.setUIState(self, state)
if self._path and state.hasKey('allow-browsing') \
and state.get('allow-browsing'):
self.browser.setBaseUri(state.get('stream-url'))
else:
self.browser.hide_all()
warning = gtk.Label()
warning.set_markup(_('Browsing files is not allowed.'))
warning.show()
self.widget.pack_start(warning)
def _create_browser(self):
browser = OnDemandBrowser(self.widget, self.admin)
worker_name = self.state.get('workerRequested')
browser.setWorkerName(worker_name)
browser.connect('selected', self._on_file_selector__selected)
return browser
def _configure_browser(self):
if self._path:
self.browser.setRoot(self._path)
def _on_realize(self, widget):
self._configure_browser()
def _on_file_selector__selected(self, browser, vfsFile):
webbrowser.open_new(vfsFile.filename)
class HTTPFileAdminGtk(BaseAdminGtk):
def setup(self):
statistics = ServerStatsAdminGtkNode(self.state, self.admin,
_("Statistics"))
browser = BrowserAdminGtkNode(self.state, self.admin,
_("Browser"))
self.nodes['Statistics'] = statistics
self.nodes['Browser'] = browser
#FIXME: We need to figure out how to create or delete
# a nodes after receiving the UI State,
# so we do not have a cache tab when not using a caching plug.
#cache = CacheStatsAdminGtkNode(self.state, self.admin, _("Cache"))
#self.nodes["Cache"] = cache
# FIXME: maybe make a protocol instead of overriding
return BaseAdminGtk.setup(self)
def uiStateChanged(self, state):
self.nodes['Statistics'].setStats(state)
#FIXME: Same as for the setup method.
#if state:
# providerName = None
# providerStats = state.get("provider-statistics")
# if providerStats:
# providerName = providerStats.get("provider-name")
# if providerName and providerName.startswith("cached-"):
# self.nodes['Cache'].setStats(state)
# self.nodes["Cache"].show()
# else:
# self.nodes["Cache"].hide()
GUIClass = HTTPFileAdminGtk
| gpl-2.0 |
sufism/qucs_chs | qucs/components/vpulse.cpp | 2897 | /***************************************************************************
vpulse.cpp
------------
begin : Sat Sep 18 2004
copyright : (C) 2004 by Michael Margraf
email : michael.margraf@alumni.tu-berlin.de
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include "vpulse.h"
vPulse::vPulse()
{
Description = QObject::tr("ideal voltage pulse source");
Arcs.append(new Arc(-12,-12, 24, 24, 0, 16*360,QPen(Qt::darkBlue,2)));
Lines.append(new Line(-30, 0,-12, 0,QPen(Qt::darkBlue,2)));
Lines.append(new Line( 30, 0, 12, 0,QPen(Qt::darkBlue,2)));
Lines.append(new Line( 18, 5, 18, 11,QPen(Qt::red,1)));
Lines.append(new Line( 21, 8, 15, 8,QPen(Qt::red,1)));
Lines.append(new Line(-18, 5,-18, 11,QPen(Qt::black,1)));
Lines.append(new Line( 6, -3, 6, 3,QPen(Qt::darkBlue,2)));
Lines.append(new Line( -6, -7, -6, -3,QPen(Qt::darkBlue,2)));
Lines.append(new Line( -6, 3, -6, 7,QPen(Qt::darkBlue,2)));
Lines.append(new Line( -6, -3, 6, -3,QPen(Qt::darkBlue,2)));
Lines.append(new Line( -6, 3, 6, 3,QPen(Qt::darkBlue,2)));
Ports.append(new Port( 30, 0));
Ports.append(new Port(-30, 0));
x1 = -30; y1 = -14;
x2 = 30; y2 = 14;
tx = x1+4;
ty = y2+4;
Model = "Vpulse";
Name = "V";
Props.append(new Property("U1", "0 V", true,
QObject::tr("voltage before and after the pulse")));
Props.append(new Property("U2", "1 V", true,
QObject::tr("voltage of the pulse")));
Props.append(new Property("T1", "0", true,
QObject::tr("start time of the pulse")));
Props.append(new Property("T2", "1 ms", true,
QObject::tr("ending time of the pulse")));
Props.append(new Property("Tr", "1 ns", false,
QObject::tr("rise time of the leading edge")));
Props.append(new Property("Tf", "1 ns", false,
QObject::tr("fall time of the trailing edge")));
rotate(); // fix historical flaw
}
vPulse::~vPulse()
{
}
Component* vPulse::newOne()
{
return new vPulse();
}
Element* vPulse::info(QString& Name, char* &BitmapFile, bool getNewOne)
{
Name = QObject::tr("Voltage Pulse");
BitmapFile = (char *) "vpulse";
if(getNewOne) return new vPulse();
return 0;
}
| gpl-2.0 |
MiguelGonzalez/fribone-php-server | application/application/config/routes.php | 1882 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| http://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There area two reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router what URI segments to use if those provided
| in the URL cannot be matched to a valid route.
|
*/
$route['default_controller'] = "home";
$route['404_override'] = '';
/*
* Own
*/
$route['fridge/(\d+)'] = 'tablon/index';
$route['fridge/(\d+)/productos'] = 'tablon/index';
$route['fridge/(\d+)/compras'] = 'tablon/index';
$route['fridge/(\d+)/compras/(\d+)'] = 'tablon/index';
$route['supermercados'] = 'tablon/index';
$route['supermercados/(\d+)'] = 'tablon/index';
$route['lector/(\d+)'] = 'tablon/index';
/* End of file routes.php */
/* Location: ./application/config/routes.php */ | gpl-2.0 |
tempest200903/20141015-GuiceExperimental | src/test/java/com/github/tempest200903/example102/ProductATest.java | 690 | package com.github.tempest200903.example102;
import org.junit.Test;
public class ProductATest {
/**
* テスト成功。
*/
@Test
public void testStab() {
AbstractA abstractA = new StubA();
System.out.println("abstractA.getClass() =: " + abstractA.getClass());
AbstractB abstractB = abstractA.getAbstractB();
System.out.println("abstractB.getClass() =: " + abstractB.getClass());
AbstractC abstractC = abstractB.getAbstractC();
System.out.println("abstractC.getClass() =: " + abstractC.getClass());
AbstractD abstractD = abstractC.getAbstractD();
System.out.println("abstractD.getClass() =: " + abstractD.getClass());
abstractD.add(3);
abstractA.add(3);
}
}
| gpl-2.0 |
cuongnd/banhangonline88_joomla | modules/mod_sj_hk_minicart_pro/core/fields/sjhkcategories.php | 4544 | <?php
/**
* @package SJ Minicart Pro for HikaShop
* @version 1.0.0
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
* @copyright (c) 2014 YouTech Company. All Rights Reserved.
* @author YouTech Company http://www.smartaddons.com
*
*/
defined('_JEXEC') or die;
jimport('joomla.form.formfield');
if (!class_exists('JFormFieldSjHkCategories')){
class JFormFieldSjHkCategories extends JFormField {
protected $type = 'sjhkcategories';
public function getInput(){
$html = array();
if ($this->com_hikiashop_installed()){
$html[] = $this->getInputHtml();
} else {
$html[] = "<div style='clear:both; margin: 0 0 0 150px; font-weight:bold; color:red;'>";
$html[] = "There are no data table for Zoo.<br>";
$html[] = "If you have HikaShop component installed.<br>";
$html[] = "Please contact us on <a href=\"http://www.smartaddons.com\" target=\"_blank\">http://www.smartaddons.com</a><br>";
$html[] = "Thank you";
$html[] = "</div>";
}
return implode("\n", $html);
}
protected function getInputHtml(){
if(!defined('DS')) define('DS', DIRECTORY_SEPARATOR);
if(!include_once(rtrim(JPATH_ADMINISTRATOR,DS).DS.'components'.DS.'com_hikashop'.DS.'helpers'.DS.'helper.php')){
echo 'This module can not work without the Hikashop Component';
return;
};
$_categories = array();
$categories = array();
$_children = array();
$class = hikashop_get('class.category');
$database = JFactory::getDBO();
//$query = 'SELECT * FROM '.hikashop_table('category').' as c ORDER BY c.category_left ASC';
$query = 'SELECT * FROM '.hikashop_table('category').' as c WHERE c.category_type <> "root" ORDER BY c.category_left ASC';
$database->setQuery($query);
$categories = $database->loadObjectList();
$select_all = isset($this->element['selectall']) && $this->element['selectall']=='true';
$is_multiple = isset($this->element['multiple']) && $this->element['multiple']=='multiple';
if (count($categories)>0){
foreach ($categories as $i => $category){
$_categories[$category->category_id] = $categories[$i];
}
foreach ($categories as $i => $category) {
$cid = $category->category_id;
$pid = $category->category_parent_id;
if (isset($_categories[$pid])) {
$_categories[$pid]->child[$cid] = $category;
}
}
if (!is_array($this->value)){
$this->value = array($this->value);
}
$select_attr = "";
if (isset($this->element['multiple'])){
$select_attr .= " multiple=\"multiple\"";
$size = $this->element['size'] ?(int) $this->element['size']: 15;
$select_attr .= " size=\"$size\"";
}
if (isset($this->element['css'])){
$select_attr .= ' class="' . trim($this->element['css']) . '"';;
} else {
$select_attr .= ' class="inputbox"';;
}
// var_dump($_categories);die;
$html = "<select $select_attr id=\"" . $this->id . '" name="' . $this->name . '">';
foreach($_categories as $j => $category){
$pid = $category->category_parent_id;
if (!isset($_categories[$pid])){
$_categories[$j]->level = 1;
$stack = array($_categories[$j]);
while( count($stack)>0 ){
$opt = array_pop($stack);
$option = array(
'label' => ($opt->level>1 ? str_repeat(' - - | ', $opt->level-1) : ' - ') . ucwords($opt->category_name) ,
'value' => $opt->category_id
);
$selected = in_array($opt->category_id, $this->value) ? 'selected="selected" ' : ' ';
$html .= '<option value="' . $option['value'] . '" ' . $selected . '>' . $option['label'] . '</option>';
if (isset($opt->child) && count($opt->child)){
foreach(array_reverse($opt->child) as $child){
$child->level = $opt->level+1;
array_push($stack, $child);
}
}
}
}
}
$html .= '</select>';
} else {
$html = "<div style='clear:both; margin: 0 0 0 150px; font-weight:bold; color:red;'>";
$html .= "Problem on reading <b>{$db->getPrefix()}hikashop_category</b><br>";
$html .= "Please contact us on <a href=\"http://www.smartaddons.com\" target=\"_blank\">http://www.smartaddons.com</a><br>";
$html .= "Thank you";
$html .= "</div>";
}
return $html;
}
protected function com_hikiashop_installed(){
$db = JFactory::getDbo();
$prefix = $db->getPrefix();
$tables = $db->getTableList();
return in_array($prefix.'hikashop_category', $tables);
}
}
} | gpl-2.0 |
jfarcher/PiThermostat | django/homeauto/settings.py | 5882 | # Django settings for homeauto project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '/usr/local/django/home.db', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = [ '433board', 'django', 'homeauto', ]
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/London'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-gb'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'g2ghi_c66=@ahzg%23&yx@bu1yo1rtz1_&ual*pz77fj+mqq*7'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'homeauto.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'homeauto.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/usr/local/django/lights/templates',
'/usr/local/django/lights/templates/lights',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.request",
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'lights',
'happenings',
'icons_tango',
# 'django.contrib.sites',
# Uncomment the next line to enable the admin:
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| gpl-2.0 |
tucocorp/Vendo-Mi-Telefono | db/migrate/20141114125206_add_barcode_read.rb | 118 | class AddBarcodeRead < ActiveRecord::Migration
def change
add_column :coupons, :barcode_read, :string
end
end
| gpl-2.0 |
MaddTheSane/scummvm | engines/lastexpress/graphics.cpp | 4282 | /* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "lastexpress/graphics.h"
#include "common/rect.h"
#include "common/system.h"
#include "common/textconsole.h"
namespace LastExpress {
#define COLOR_KEY 0xFFFF
GraphicsManager::GraphicsManager() : _changed(false) {
const Graphics::PixelFormat format(2, 5, 5, 5, 0, 10, 5, 0, 0);
_screen.create(640, 480, format);
// Create the game surfaces
_backgroundA.create(640, 480, format);
_backgroundC.create(640, 480, format);
_overlay.create(640, 480, format);
_inventory.create(640, 480, format);
clear(kBackgroundAll);
}
GraphicsManager::~GraphicsManager() {
// Free the game surfaces
_screen.free();
_backgroundA.free();
_backgroundC.free();
_overlay.free();
_inventory.free();
}
void GraphicsManager::update() {
// Update the screen if needed and reset the status
if (_changed) {
mergePlanes();
updateScreen();
_changed = false;
}
}
void GraphicsManager::change() {
_changed = true;
}
void GraphicsManager::clear(BackgroundType type) {
clear(type, Common::Rect(640, 480));
}
void GraphicsManager::clear(BackgroundType type, const Common::Rect &rect) {
switch (type) {
default:
error("[GraphicsManager::clear] Unknown background type: %d", type);
break;
case kBackgroundA:
case kBackgroundC:
case kBackgroundOverlay:
case kBackgroundInventory:
getSurface(type)->fillRect(rect, COLOR_KEY);
break;
case kBackgroundAll:
_backgroundA.fillRect(rect, COLOR_KEY);
_backgroundC.fillRect(rect, COLOR_KEY);
_overlay.fillRect(rect, COLOR_KEY);
_inventory.fillRect(rect, COLOR_KEY);
break;
}
}
bool GraphicsManager::draw(Drawable *drawable, BackgroundType type, bool transition) {
// TODO handle transition properly
if (transition)
clear(type);
// TODO store rect for later use
Common::Rect rect = drawable->draw(getSurface(type));
return (!rect.isEmpty());
}
Graphics::Surface *GraphicsManager::getSurface(BackgroundType type) {
switch (type) {
default:
error("[GraphicsManager::getSurface] Unknown surface type: %d", type);
break;
case kBackgroundA:
return &_backgroundA;
case kBackgroundC:
return &_backgroundC;
case kBackgroundOverlay:
return &_overlay;
case kBackgroundInventory:
return &_inventory;
case kBackgroundAll:
error("[GraphicsManager::getSurface] Cannot return a surface for kBackgroundAll");
break;
}
}
// TODO optimize to only merge dirty rects
void GraphicsManager::mergePlanes() {
// Clear screen surface
_screen.fillRect(Common::Rect(640, 480), 0);
uint16 *screen = (uint16 *)_screen.getPixels();
uint16 *inventory = (uint16 *)_inventory.getPixels();
uint16 *overlay = (uint16 *)_overlay.getPixels();
uint16 *backgroundC = (uint16 *)_backgroundC.getPixels();
uint16 *backgroundA = (uint16 *)_backgroundA.getPixels();
for (int i = 0; i < 640 * 480; i++) {
if (*inventory != COLOR_KEY)
*screen = *inventory;
else if (*overlay != COLOR_KEY)
*screen = *overlay;
else if (*backgroundA != COLOR_KEY)
*screen = *backgroundA;
else if (*backgroundC != COLOR_KEY)
*screen = *backgroundC;
else
*screen = 0;
inventory++;
screen++;
overlay++;
backgroundA++;
backgroundC++;
}
}
void GraphicsManager::updateScreen() {
g_system->fillScreen(0);
g_system->copyRectToScreen(_screen.getPixels(), 640 * 2, 0, 0, 640, 480);
}
} // End of namespace LastExpress
| gpl-2.0 |
openearth/PyWPS | pywps/processes/__init__.py | 104 | __all__ = ["buffer", "dummyprocess","ultimatequestionprocess","moreInOne","moreInstancesInOne","tests"]
| gpl-2.0 |
manojh/firstrepo | administrator/components/com_messages/models/message.php | 6460 | <?php
/**
* @package Joomla.Administrator
* @subpackage com_messages
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Private Message model.
*
* @package Joomla.Administrator
* @subpackage com_messages
* @since 1.6
*/
class MessagesModelMessage extends JModelAdmin
{
/**
* message
*/
protected $item;
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* @since 1.6
*/
protected function populateState()
{
parent::populateState();
$input = JFactory::getApplication()->input;
$user = JFactory::getUser();
$this->setState('user.id', $user->get('id'));
$messageId = (int) $input->getInt('message_id');
$this->setState('message.id', $messageId);
$replyId = (int) $input->getInt('reply_id');
$this->setState('reply.id', $replyId);
}
/**
* Returns a Table object, always creating it.
*
* @param type The table type to instantiate
* @param string A prefix for the table class name. Optional.
* @param array Configuration array for model. Optional.
* @return JTable A database object
* @since 1.6
*/
public function getTable($type = 'Message', $prefix = 'MessagesTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
/**
* Method to get a single record.
*
* @param integer The id of the primary key.
* @return mixed Object on success, false on failure.
* @since 1.6
*/
public function getItem($pk = null)
{
if (!isset($this->item))
{
if ($this->item = parent::getItem($pk))
{
// Prime required properties.
if (empty($this->item->message_id))
{
// Prepare data for a new record.
if ($replyId = $this->getState('reply.id'))
{
// If replying to a message, preload some data.
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->select('subject, user_id_from');
$query->from('#__messages');
$query->where('message_id = '.(int) $replyId);
try
{
$message = $db->setQuery($query)->loadObject();
}
catch (RuntimeException $e)
{
$this->setError($e->getMessage());
return false;
}
$this->item->set('user_id_to', $message->user_id_from);
$re = JText::_('COM_MESSAGES_RE');
if (stripos($message->subject, $re) !== 0)
{
$this->item->set('subject', $re.$message->subject);
}
}
}
elseif ($this->item->user_id_to != JFactory::getUser()->id)
{
$this->setError(JText::_('JERROR_ALERTNOAUTHOR'));
return false;
}
else {
// Mark message read
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->update('#__messages');
$query->set('state = 1');
$query->where('message_id = '.$this->item->message_id);
$db->setQuery($query)->execute();
}
}
// Get the user name for an existing messasge.
if ($this->item->user_id_from && $fromUser = new JUser($this->item->user_id_from))
{
$this->item->set('from_user_name', $fromUser->name);
}
}
return $this->item;
}
/**
* Method to get the record form.
*
* @param array $data Data for the form.
* @param boolean $loadData True if the form is to load its own data (default case), false if not.
* @return JForm A JForm object on success, false on failure
* @since 1.6
*/
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_messages.message', 'message', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
return $form;
}
/**
* Method to get the data that should be injected in the form.
*
* @return mixed The data for the form.
* @since 1.6
*/
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_messages.edit.message.data', array());
if (empty($data))
{
$data = $this->getItem();
}
$this->preprocessData('com_messages.message', $data);
return $data;
}
/**
* Method to save the form data.
*
* @param array The form data.
*
* @return boolean True on success.
*/
public function save($data)
{
$table = $this->getTable();
// Bind the data.
if (!$table->bind($data))
{
$this->setError($table->getError());
return false;
}
// Assign empty values.
if (empty($table->user_id_from))
{
$table->user_id_from = JFactory::getUser()->get('id');
}
if ((int) $table->date_time == 0)
{
$table->date_time = JFactory::getDate()->toSql();
}
// Check the data.
if (!$table->check())
{
$this->setError($table->getError());
return false;
}
// Load the recipient user configuration.
$model = JModelLegacy::getInstance('Config', 'MessagesModel', array('ignore_request' => true));
$model->setState('user.id', $table->user_id_to);
$config = $model->getItem();
if (empty($config))
{
$this->setError($model->getError());
return false;
}
if ($config->get('locked', false))
{
$this->setError(JText::_('COM_MESSAGES_ERR_SEND_FAILED'));
return false;
}
// Store the data.
if (!$table->store())
{
$this->setError($table->getError());
return false;
}
if ($config->get('mail_on_new', true))
{
// Load the user details (already valid from table check).
$fromUser = JUser::getInstance($table->user_id_from);
$toUser = JUser::getInstance($table->user_id_to);
$debug = JFactory::getConfig()->get('debug_lang');
$default_language = JComponentHelper::getParams('com_languages')->get('administrator');
$lang = JLanguage::getInstance($toUser->getParam('admin_language', $default_language), $debug);
$lang->load('com_messages', JPATH_ADMINISTRATOR);
$siteURL = JURI::root() . 'administrator/index.php?option=com_messages&view=message&message_id='.$table->message_id;
$sitename = JFactory::getApplication()->getCfg('sitename');
$subject = sprintf($lang->_('COM_MESSAGES_NEW_MESSAGE_ARRIVED'), $sitename);
$msg = sprintf($lang->_('COM_MESSAGES_PLEASE_LOGIN'), $siteURL);
JFactory::getMailer()->sendMail($fromUser->email, $fromUser->name, $toUser->email, $subject, $msg);
}
return true;
}
}
| gpl-2.0 |
patux/YaCOMAS | includes/core/FormHelper.php | 1142 | <?php
class FormHelper {
public static function createSelect($label, $name, $options, $selected='', $default='', $input_parameters='') {
$string = '';
$selected = ($selected=='')?$default:$selected;
$string .= "<label for=\"$name\"/>$label</label>";
$string .= "<select name=\"$name\" id=\"$estudios\" $input_parameters>";
foreach($options as $value=>$descr){
if ($value!=$selected) {
$string .="<option value=\"$value\">$descr</option>";
} else {
$string .="<option value=\"$value\" selected='selected'>$descr</option>";
}
}
$string .= "</select>";
return $string;
}
public static function createRadio($label, $name, $options, $checked='', $default='') {
$string = '';
$checked = ($checked=='')?$default:$checked;
$string .= "<label for=\"$name\"/>$label</label>";
foreach($options as $value=>$descr){
if ($value!=$checked) {
$string .="<input type=\"radio\" name=\"$name\" value=\"$value\"/>$descr ";
} else {
$string .="<input type=\"radio\" name=\"$name\" value=\"$value\" checked/>$descr ";
}
}
$string .= "</select>";
return $string;
}
} | gpl-2.0 |
scgraph/SCGraph | src/face.cc | 676 | #include "face.h"
Face::Face (GeometryType) :
//_per_vertex_colors (false),
_geometry_type (POINTS),
_render_mode (NORMAL),
_texture_index (0),
_frame_id (0),
_alpha_mul (1.0),
_thickness (1.0),
_culling (0)
{
}
Face::Face (const Face &f) :
_geometry_type(f._geometry_type),
_render_mode(f._render_mode),
_vertices(f._vertices),
//_per_vertex_colors(f._per_vertex_colors),
_normals(f._normals),
_texture_coordinates(f._texture_coordinates),
_texture_index(f._texture_index),
_frame_id(f._frame_id),
_colors(f._colors),
_alpha_mul(f._alpha_mul),
_face_color(f._face_color),
_material(f._material),
_thickness(f._thickness),
_culling(f._culling)
{
}
| gpl-2.0 |
NationalLibraryOfNorway/Bibliotekstatistikk | old-and-depricated/finances/src/main/java/no/abmu/finances/domain/ReportSchema.java | 5773 | /*
* Copyright (c) 2006 Your Corporation. All Rights Reserved.
*/
package no.abmu.finances.domain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import no.abmu.common.domain.Entity;
import no.abmu.util.hibernate3.ClassUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* ReportSchema.
*
* @author Erik Romson, erik@zenior.no
* @author $Author: jens $
* @version $Rev: 12852 $
* @date $Date: 2009-01-30 22:10:45 +0100 (Fri, 30 Jan 2009) $
* @copyright ABM-Utvikling
* @hibernate.class table="FINANCE_REPORT_SCHEMA" lazy="false"
* @hibernate.discriminator column="report_schema"
* @hibernate.cache usage="nonstrict-read-write"
*
* @assoc 1..* - 1..* no.abmu.finances.domain.Account
*/
public class ReportSchema implements Entity {
private static final Log logger = (Log) LogFactory.getLog(ReportSchema.class);
protected Long id;
protected String name;
protected String description;
protected Set accounts = new HashSet();
protected String version;
protected ReportSchema() {
}
public ReportSchema(String name) {
this.name = name;
}
public ReportSchema(String name, String description) {
this.name = name;
this.description = description;
}
/**
* getId.
*
* @return
* @hibernate.id generator-class="increment"
*/
public Long getId() {
return id;
}
/**
* getName.
*
* unique_key="unique_name_version"
*
* @hibernate.property not-null="true"
*/
public String getName() {
return name;
}
/**
* getDescription.
*
* @hibernate.property not-null="true"
*/
public String getDescription() {
return description;
}
/**
* getVersion.
*
* unique_key="unique_name_version"
*
* @hibernate.property not-null="true"
*/
public String getVersion() {
return version;
}
/**
* getAccounts.
*
* @hibernate.set lazy="false"
* cascade="save-update"
* table="FINANCE_REPORT_SCHEMA_ACCOUNT"
* @hibernate.key column="FK_REPORT_SCHEMA_ID"
* @hibernate.many-to-many class="no.abmu.finances.domain.Account"
* column="FK_ACCOUNT_ID"
* @hibernate.collection-key column="FK_REPORT_SCHEMA_ID"
* @hibernate.collection-many-to-many class="no.abmu.finances.domain.Account"
* column="FK_ACCOUNT_ID"
*/
public Set getAccounts() {
return accounts;
}
public void addAccount(Account account) {
account.addReportSchema(this);
accounts.add(account);
}
public Post getPost(String code) {
//TODO Temporært!!
for (Iterator iterator = accounts.iterator(); iterator.hasNext();) {
Account account = (Account) iterator.next();
Set posts = account.getPosts();
for (Iterator postIter = posts.iterator(); postIter.hasNext();) {
Post post = (Post) postIter.next();
if (post.getCode().equals(code)) {
return post;
}
}
}
return null;
}
public String[] getAvailablePostCodes() {
List list = new ArrayList();
//TODO Temporært!!
for (Iterator iterator = accounts.iterator(); iterator.hasNext();) {
Account account = (Account) iterator.next();
Set posts = account.getPosts();
for (Iterator postIter = posts.iterator(); postIter.hasNext();) {
Post post = (Post) postIter.next();
list.add(post.getCode());
}
}
return (String[]) list.toArray(new String[list.size()]);
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(String description) {
this.description = description;
}
private void setAccounts(Set accounts) {
this.accounts = accounts;
}
public void setVersion(String version) {
this.version = version;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!ClassUtil.sameClass(this, obj)) {
return false;
}
final ReportSchema reportSchema = (ReportSchema) obj;
if (getName() != null) {
if (!getName().equals(reportSchema.getName())) {
return false;
}
} else {
if (reportSchema.getName() != null) {
return false;
}
}
if (getVersion() != null) {
if (!getVersion().equals(reportSchema.getVersion())) {
return false;
}
} else {
if (reportSchema.getVersion() != null) {
return false;
}
}
return true;
}
public int hashCode() {
int result;
result = 29 * (getName() != null ? getName().hashCode() : 0);
result = 29 * (getVersion() != null ? getVersion().hashCode() : 0);
return result;
}
public String toString() {
return getClass().getName() + "{"
+ "id=" + id
+ ", name='" + name + '\''
+ ", description='" + description + '\''
+ ", version='" + version + '\''
+ '}';
}
}
| gpl-2.0 |
jwpully/pchapub | administrator/components/com_phocadownload/models/phocadownloaddownloads.php | 6358 | <?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined( '_JEXEC' ) or die();
jimport( 'joomla.application.component.modellist' );
class PhocaDownloadCpModelPhocaDownloadDownloads extends JModelList
{
protected $option = 'com_phocadownload';
public function __construct($config = array())
{
if (empty($config['filter_fields'])) {
$config['filter_fields'] = array(
'id', 'a.id',
'title', 'd.title',
'alias', 'd.alias',
'checked_out', 'd.checked_out',
'checked_out_time', 'd.checked_out_time',
'category_id', 'category_id',
'usernameno', 'ua.usernameno',
'username', 'ua.username',
'ordering', 'a.ordering',
'count', 'a.count',
'date', 'a.date',
'published','d.published',
'filename', 'd.filename'
);
}
parent::__construct($config);
}
protected function populateState($ordering = NULL, $direction = NULL)
{
// Initialise variables.
$app = JFactory::getApplication('administrator');
// Load the filter state.
$search = $app->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
$this->setState('filter.search', $search);
/*
$accessId = $app->getUserStateFromRequest($this->context.'.filter.access', 'filter_access', null, 'int');
$this->setState('filter.access', $accessId);
$state = $app->getUserStateFromRequest($this->context.'.filter.state', 'filter_published', '', 'string');
$this->setState('filter.state', $state);
*/
$id = JRequest::getVar( 'id', '', '', 'int');
if ((int)$id > 0) {
$this->setState('filter.filestat_id', $id);
} else {
//$fileStatId = $app->getUserStateFromRequest($this->context.'.filter.filestat_id', 'filter_filestat_id', $id);
$this->setState('filter.filestat_id', 0);
}
/*
$language = $app->getUserStateFromRequest($this->context.'.filter.language', 'filter_language', '');
$this->setState('filter.language', $language);*/
// Load the parameters.
$params = JComponentHelper::getParams('com_phocadownload');
$this->setState('params', $params);
// List state information.
parent::populateState('username', 'asc');
}
protected function getStoreId($id = '')
{
// Compile the store id.
$id .= ':'.$this->getState('filter.search');
/*$id .= ':'.$this->getState('filter.access');
$id .= ':'.$this->getState('filter.state');
$id .= ':'.$this->getState('filter.category_id');*/
$id .= ':'.$this->getState('filter.filestat_id');
return parent::getStoreId($id);
}
protected function getListQuery()
{
/*$query = ' SELECT a.id, a.userid, a.fileid, d.filename AS filename, d.title AS filetitle, a.count, a.date, u.name AS uname, u.username AS username, 0 AS checked_out'
. ' FROM #__phocadownload_user_stat AS a '
. ' LEFT JOIN #__phocadownload AS d ON d.id = a.fileid '
. ' LEFT JOIN #__users AS u ON u.id = a.userid '
. $where
. ' GROUP by a.id'
. $orderby;
*/
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
// Select the required fields from the table.
$query->select(
$this->getState(
'list.select',
'a.*'
)
);
$query->from('`#__phocadownload_user_stat` AS a');
// Join over the language
//$query->select('l.title AS language_title');
//$query->join('LEFT', '`#__languages` AS l ON l.lang_code = a.language');
// Join over the users for the checked out user.
//$query->select('uc.name AS editor');
//$query->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');
// Join over the asset groups.
//$query->select('ag.title AS access_level');
//$query->join('LEFT', '#__viewlevels AS ag ON ag.id = a.access');
// Join over the categories.
$query->select('d.filename AS filename, d.title AS filetitle');
$query->join('LEFT', '#__phocadownload AS d ON d.id = a.fileid');
$query->select('ua.id AS userid, ua.username AS username, ua.name AS usernameno');
$query->join('LEFT', '#__users AS ua ON ua.id = a.userid');
//$query->select('v.average AS ratingavg');
//$query->join('LEFT', '#__phocadownload_img_votes_statistics AS v ON v.imgid = a.id');
// Filter by access level.
//if ($access = $this->getState('filter.access')) {
// $query->where('a.access = '.(int) $access);
//}
// Filter by published state.
/*$published = $this->getState('filter.state');
if (is_numeric($published)) {
$query->where('a.published = '.(int) $published);
}
else if ($published === '') {
$query->where('(a.published IN (0, 1))');
}
// Filter by category.*/
/*$fileStatId = $this->getState('filter.filestat_id');
if (is_numeric($fileStatId)) {
$query->where('a.fileid = ' . (int) $fileStatId);
}*/
// Filter by search in title
$search = $this->getState('filter.search');
if (!empty($search))
{
if (stripos($search, 'id:') === 0) {
$query->where('a.id = '.(int) substr($search, 3));
}
else
{
$search = $db->Quote('%'.$db->escape($search, true).'%');
$query->where('( ua.username LIKE '.$search.' OR ua.name LIKE '.$search.' OR d.filename LIKE '.$search.' OR d.title LIKE '.$search.')');
}
}
$query->group('a.id');
// Add the list ordering clause.
//$orderCol = $this->state->get('list.ordering');
//$orderDirn = $this->state->get('list.direction');
$orderCol = $this->state->get('list.ordering', 'username');
$orderDirn = $this->state->get('list.direction', 'asc');
if ($orderCol == 'a.id' || $orderCol == 'username') {
$orderCol = 'ua.username '.$orderDirn.', a.id';
}
$query->order($db->escape($orderCol.' '.$orderDirn));
return $query;
}
function reset($cid = array()) {
if (count( $cid )) {
JArrayHelper::toInteger($cid);
$cids = implode( ',', $cid );
$date = gmdate('Y-m-d H:i:s');
//Delete it from DB
$query = 'UPDATE #__phocadownload_user_stat'
.' SET count = 0,'
.' date = '.$this->_db->Quote($date)
.' WHERE id IN ( '.$cids.' )';
$this->_db->setQuery( $query );
if(!$this->_db->query()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
}
return true;
}
}
?> | gpl-2.0 |
magnus2lin/opendlv | code/system/core/proxy/src/can/can.cpp | 8531 | /**
* Copyright (C) 2016 Chalmers REVERE
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
#include <iostream>
#include <string>
#include <vector>
#include <opendavinci/odcore/data/Container.h>
#include <opendavinci/odcore/data/TimeStamp.h>
#include <opendavinci/odtools/recorder/Recorder.h>
#include <odcantools/MessageToCANDataStore.h>
#include <odcantools/CANDevice.h>
#include <automotivedata/generated/automotive/GenericCANMessage.h>
#include "can/can.hpp"
#include "can/canmessagedatastore.hpp"
namespace opendlv {
namespace proxy {
namespace can {
Can::Can(int32_t const &a_argc, char **a_argv)
: odcore::base::module::TimeTriggeredConferenceClientModule(
a_argc, a_argv, "proxy-can")
, automotive::odcantools::GenericCANMessageListener()
, m_fifoGenericCanMessages()
, m_recorderGenericCanMessages()
, m_fifoMappedCanMessages()
, m_recorderMappedCanMessages()
, m_device()
, m_canMessageDataStore()
, m_revereFh16CanMessageMapping()
{
}
Can::~Can()
{
}
void Can::setUp()
{
using namespace std;
using namespace odcore::base;
using namespace odcore::data;
using namespace odtools::recorder;
using namespace automotive::odcantools;
string const DEVICE_NODE =
getKeyValueConfiguration().getValue<string>("proxy-can.devicenode");
// Try to open CAN device and register this instance as receiver for
// GenericCANMessages.
m_device = shared_ptr<CANDevice>(new CANDevice(DEVICE_NODE, *this));
// If the device could be successfully opened, create a recording file with a
// dump of the data.
if (m_device.get() && m_device->isOpen()) {
cout << "Successfully opened CAN device '" << DEVICE_NODE << "'." << endl;
// Automatically record all received raw CAN messages.
TimeStamp ts;
const bool RECORD_GCM =
(getKeyValueConfiguration().getValue<int>("proxy-can.record_gcm") == 1);
if (RECORD_GCM) {
// URL for storing containers containing GenericCANMessages.
stringstream recordingUrl;
recordingUrl << "file://"
<< "can_gcm_" << ts.getYYYYMMDD_HHMMSS() << ".rec";
// Size of memory segments (not needed for recording GenericCANMessages).
const uint32_t MEMORY_SEGMENT_SIZE = 0;
// Number of memory segments (not needed for recording
// GenericCANMessages).
const uint32_t NUMBER_OF_SEGMENTS = 0;
// Run recorder in asynchronous mode to allow real-time recording in
// background.
const bool THREADING = true;
// Dump shared images and shared data (not needed for recording
// GenericCANMessages)?
const bool DUMP_SHARED_DATA = false;
// Create a recorder instance.
m_recorderGenericCanMessages = unique_ptr<Recorder>(new Recorder(recordingUrl.str(),
MEMORY_SEGMENT_SIZE, NUMBER_OF_SEGMENTS, THREADING, DUMP_SHARED_DATA));
}
const bool RECORD_MAPPED =
(getKeyValueConfiguration().getValue<int>("proxy-can.record_mapped_data") == 1);
if (RECORD_MAPPED) {
// URL for storing containers containing GenericCANMessages.
stringstream recordingUrl;
recordingUrl << "file://"
<< "can_mapped_data_" << ts.getYYYYMMDD_HHMMSS() << ".rec";
// Size of memory segments (not needed for recording GenericCANMessages).
const uint32_t MEMORY_SEGMENT_SIZE = 0;
// Number of memory segments (not needed for recording
// GenericCANMessages).
const uint32_t NUMBER_OF_SEGMENTS = 0;
// Run recorder in asynchronous mode to allow real-time recording in
// background.
const bool THREADING = true;
// Dump shared images and shared data (not needed for recording
// mapped containers)?
const bool DUMP_SHARED_DATA = false;
// Create a recorder instance.
m_recorderMappedCanMessages = unique_ptr<Recorder>(new Recorder(recordingUrl.str(),
MEMORY_SEGMENT_SIZE, NUMBER_OF_SEGMENTS, THREADING, DUMP_SHARED_DATA));
}
// Create a data sink that automatically receives all Containers and
// selectively relays them based on the Container type to the CAN device.
m_canMessageDataStore =
unique_ptr<CanMessageDataStore>(new CanMessageDataStore(m_device));
addDataStoreFor(*m_canMessageDataStore);
// Start the wrapped CAN device to receive CAN messages concurrently.
m_device->start();
}
}
void Can::tearDown()
{
opendlv::proxy::reverefh16::BrakeRequest brakeRequest;
brakeRequest.setEnableRequest(false);
brakeRequest.setBrake(0.0);
odcore::data::Container brakeRequestContainer(brakeRequest);
canmapping::opendlv::proxy::reverefh16::BrakeRequest
brakeRequestMapping;
automotive::GenericCANMessage genericCanMessage = brakeRequestMapping.encode(brakeRequestContainer);
m_device->write(genericCanMessage);
opendlv::proxy::reverefh16::AccelerationRequest accelerationRequest;
accelerationRequest.setEnableRequest(false);
accelerationRequest.setAcceleration(0.0);
odcore::data::Container accelerationRequestContainer(accelerationRequest);
canmapping::opendlv::proxy::reverefh16::AccelerationRequest
accelerationRequestMapping;
genericCanMessage = accelerationRequestMapping.encode(accelerationRequestContainer);
m_device->write(genericCanMessage);
opendlv::proxy::reverefh16::SteeringRequest steeringRequest;
steeringRequest.setEnableRequest(false);
steeringRequest.setSteeringRoadWheelAngle(0.0);
steeringRequest.setSteeringDeltaTorque(0.0);
odcore::data::Container steeringRequestContainer(steeringRequest);
canmapping::opendlv::proxy::reverefh16::SteeringRequest
steeringRequestMapping;
genericCanMessage = steeringRequestMapping.encode(steeringRequestContainer);
m_device->write(genericCanMessage);
if (m_device.get()) {
// Stop the wrapper CAN device.
m_device->stop();
}
// Fix linker error.
opendlv::proxy::reverefh16::Steering s;
(void)s;
}
void Can::nextGenericCANMessage(const automotive::GenericCANMessage &gcm)
{
// Map CAN message to high-level data structure.
vector<odcore::data::Container> result = m_revereFh16CanMessageMapping.mapNext(gcm);
for (auto c : result) {
// Enqueue mapped container for direct recording.
if (m_recorderMappedCanMessages.get()) {
m_fifoMappedCanMessages.add(c);
}
// Send container to conference.
getConference().send(c);
m_canMessageDataStore->add(c);
}
// Enqueue CAN message wrapped as Container to be recorded if we have a valid
// recorder.
if (m_recorderGenericCanMessages.get()) {
odcore::data::Container c(gcm);
m_fifoGenericCanMessages.add(c);
}
}
/**
* Receives control commands from the action layer.
* Prepares data for the CAN gateway.
*/
//void Can::nextContainer(odcore::data::Container &c)
//{
// m_canMessageDataStore.Add(c);
//}
odcore::data::dmcp::ModuleExitCodeMessage::ModuleExitCode Can::body()
{
while (getModuleStateAndWaitForRemainingTimeInTimeslice() ==
odcore::data::dmcp::ModuleStateMessage::RUNNING) {
// Record GenericCANMessages.
if (m_recorderGenericCanMessages.get()) {
const uint32_t ENTRIES = m_fifoGenericCanMessages.getSize();
for (uint32_t i = 0; i < ENTRIES; i++) {
odcore::data::Container c = m_fifoGenericCanMessages.leave();
// Store container to dump file.
m_recorderGenericCanMessages->store(c);
}
}
// Record mapped messages from GenericCANMessages.
if (m_recorderMappedCanMessages.get()) {
const uint32_t ENTRIES = m_fifoMappedCanMessages.getSize();
for (uint32_t i = 0; i < ENTRIES; i++) {
odcore::data::Container c = m_fifoMappedCanMessages.leave();
// Store container to dump file.
m_recorderMappedCanMessages->store(c);
}
}
}
return odcore::data::dmcp::ModuleExitCodeMessage::OKAY;
}
} // can
} // proxy
} // opendlv
| gpl-2.0 |
AARCprofessionals/obrs | aarctest/wp-content/themes/academy/aarc-course-california.php | 1693 | <?php
/*
Template Name: Course Modules - California
*/
?>
<?php get_header();
$login = $_POST['Username']; /* Get login from form */
$password = $_POST['Password']; /* Get password from form */
$email = "wordpress@aarc.org";
//Create User id
$user_id=wp_create_user( $login, $password, $email );
//Assign User to course
ThemexCourse::subscribeUser(2128, $user_id, true);
?>
<div class="column eightcol">
<!-- comment out sample code
<?php echo('This is the California course modules template'); ?><br>
<h2>A Listing of All Categories</h2>
<?php list_cats(); ?>
<br>
<p> </p>
end commenting of sample code -->
<!-- Query by post
<h2>Query by Post</h2>
<?php query_posts('showposts=5'); ?>
<ul>
<?php while (have_posts()) : the_post(); ?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endwhile;?>
</ul>
end code for query by post -->
<h1>Course Modules</h1>
<!-- Query a list of posts by post type -->
<p><a href="?npcms_logout=true">Click here</a> to log out</p>
<div class="user-courses-listing" style="width: 80%;">
<?php
$recentposts = get_posts('numberposts=22&post_type=course&tag_ID=10');
foreach ($recentposts as $post) :
setup_postdata($post);
?>
<li class="course-title" style="display: block;"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</div>
<!-- -->
</div>
<aside class="sidebar column fourcol last">
<?php get_sidebar(); ?>
</aside>
<?php get_footer(); ?> | gpl-2.0 |
m-stein/genode | base-hw/src/core/vea9x4/no_trustzone/platform_support.cc | 1926 | /*
* \brief Platform implementations specific for base-hw and VEA9X4
* \author Martin Stein
* \date 2012-04-27
*/
/*
* Copyright (C) 2012-2013 Genode Labs GmbH
*
* This file is part of the Genode OS framework, which is distributed
* under the terms of the GNU General Public License version 2.
*/
/* core includes */
#include <platform.h>
#include <board.h>
#include <cpu.h>
#include <pic.h>
using namespace Genode;
Native_region * Platform::_ram_regions(unsigned const i)
{
static Native_region _regions[] =
{
{ Board::RAM_0_BASE, Board::RAM_0_SIZE },
{ Board::RAM_1_BASE, Board::RAM_1_SIZE },
{ Board::RAM_2_BASE, Board::RAM_2_SIZE },
{ Board::RAM_3_BASE, Board::RAM_3_SIZE }
};
return i < sizeof(_regions)/sizeof(_regions[0]) ? &_regions[i] : 0;
}
Native_region * Platform::_irq_regions(unsigned const i)
{
static Native_region _regions[] =
{
{ 0, Kernel::Pic::MAX_INTERRUPT_ID + 1 }
};
return i < sizeof(_regions)/sizeof(_regions[0]) ? &_regions[i] : 0;
}
Native_region * Platform::_core_only_irq_regions(unsigned const i)
{
static Native_region _regions[] =
{
/* Core timer */
{ Genode::Cpu::PRIVATE_TIMER_IRQ, 1 },
/* Core UART */
{ Board::PL011_0_IRQ, 1 }
};
return i < sizeof(_regions)/sizeof(_regions[0]) ? &_regions[i] : 0;
}
Native_region * Platform::_mmio_regions(unsigned const i)
{
static Native_region _regions[] =
{
{ Board::MMIO_0_BASE, Board::MMIO_0_SIZE },
{ Board::MMIO_1_BASE, Board::MMIO_1_SIZE },
};
return i < sizeof(_regions)/sizeof(_regions[0]) ? &_regions[i] : 0;
}
Native_region * Platform::_core_only_mmio_regions(unsigned const i)
{
static Native_region _regions[] =
{
/* Core timer and PIC */
{ Board::CORTEX_A9_PRIVATE_MEM_BASE,
Board::CORTEX_A9_PRIVATE_MEM_SIZE },
/* Core UART */
{ Board::PL011_0_MMIO_BASE, Board::PL011_0_MMIO_SIZE }
};
return i < sizeof(_regions)/sizeof(_regions[0]) ? &_regions[i] : 0;
}
| gpl-2.0 |
nbrouse-deep/nestleactionstations_com | wp-content/themes/nestle-action-stations/partials/single-station-main.php | 7839 | <?php
$theme_url = get_bloginfo('template_directory');
include 'hero-main.partial.php';
$download_kit_url = get_zip_download_link($post->post_name);
$show_recipes = get_field('bar_show_recipe');
if ($show_recipes == 'yes') {
$recipe_bg_object = get_field('bar_recipe_heading_background');
if ( empty($recipe_bg_object) ) $recipe_bg_url = $theme_url."/assets/images/spoons.jpg";
else $recipe_bg_url = $recipe_bg_object['sizes']['large'];
$recipe_heading = get_field('bar_heading_recipe');
$recipe_description = get_field('bar_description_recipe');
$guide_download = get_field('bar_guide_download');
$guide_text = get_field('bar_guide_download_text');
if ( empty($guide_text) ) $guide_text = "Download Station Set Up Guides";
$order_prep_download = get_field('bar_order_prep_download');
$order_prep_text = get_field('bar_order_prep_download_text');
if ( empty($order_prep_text) ) $order_prep_text = "Download a Customizable Order and Prep Guide";
}
$show_calendar = get_field('bar_show_calendar');
if ($show_calendar == 'yes') {
$calendar_bg_object = get_field('bar_calendar_heading_background');
if ( empty($calendar_bg_object) ) $calendar_bg_url = $theme_url."/assets/images/spoons.jpg";
else $calendar_bg_url = $calendar_bg_object['sizes']['large'];
$calendar_heading = get_field('bar_heading_calendar');
$calendar_description = get_field('bar_description_calendar');
$calendar_download_url = get_field('bar_download_calendar');
}
$show_merchandising = get_field('bar_show_merchandising');
if ($show_merchandising == 'yes') {
$merchandising_bg_object = get_field('bar_merchandising_heading_background');
if ( empty($merchandising_bg_object) ) $merchandising_bg_url = $theme_url."/assets/images/spoons.jpg";
else $merchandising_bg_url = $merchandising_bg_object['sizes']['large'];
$merchandising_heading = get_field('bar_heading_merchandising');
$merchandising_description = get_field('bar_description_merchandising');
$merchandising_url = get_field('bar_see_all_merchandise');
if ( empty($merchandising_url) ) $merchandising_url = get_field('merchandise_fulfillment_url', 'options');
if ( empty($merchandising_url) ) $merchandising_url = "http://www.nestle.com/";
}
$show_sales = get_field('bar_show_sales');
if ($show_sales == 'yes') {
$sales_bg_object = get_field('bar_sales_heading_background');
if ( empty($sales_bg_object) ) $sales_bg_url = $theme_url."/assets/images/spoons.jpg";
else $sales_bg_url = $sales_bg_object['sizes']['large'];
$sales_heading = get_field('bar_heading_sales');
$sales_description = get_field('bar_description_sales');
}
?>
<?php if( $show_recipes == 'yes' ): ?>
<div class="station-section-outer-wrap" id="recipes" style="background-image: url(<?php echo $recipe_bg_url; ?>)">
<div class="station-section-inner-wrap">
<div class="row station-section recipes">
<div class="section-content">
<i class="icon"></i>
<h2><?php echo $recipe_heading; ?></h2>
<?php echo $recipe_description; ?>
<?php if ( !empty($guide_download) ): ?>
<a href="<?php echo $guide_download; ?>"><?php echo $guide_text; ?></a>
<?php endif; ?>
<?php if ( !empty($order_prep_download) ): ?>
<a href="<?php echo $order_prep_download; ?>"><?php echo $order_prep_text; ?></a>
<?php endif; ?>
</div>
<div class="section-button">
<a class="button fill" href="<?php echo get_permalink( $post->ID ); ?>recipes" alt="">See All Concepts</a>
</div>
</div>
</div>
</div>
<div class="row columns station-themes">
<?php include 'recipe-themes-partial.php'; ?>
</div>
<?php endif; ?>
<?php if( $show_calendar == 'yes' ): ?>
<div class="station-section-outer-wrap" id="calendar" style="background-image: url(<?php echo $calendar_bg_url; ?>)">
<div class="station-section-inner-wrap">
<div class="row station-section calendar">
<div class="section-content">
<i class="icon"></i>
<h2><?php echo $calendar_heading; ?></h2>
<?php echo $calendar_description; ?>
</div>
<div class="section-button">
<a class="button fill" href="<?php echo $calendar_download_url; ?>" alt="">Download Calendar</a>
</div>
</div>
</div>
</div>
<div data-sr class="row calendar-table">
<?php include 'calendar-partial.php'; ?>
</div>
<?php endif; ?>
<?php if ( $show_merchandising == 'yes' && have_rows('bar_merchandise_assets') ): ?>
<div class="station-section-outer-wrap" id="merchandise" style="background-image: url(<?php echo $merchandising_bg_url; ?>)">
<div class="station-section-inner-wrap">
<div class="row station-section merchandising">
<div class="section-content">
<i class="icon"></i>
<h2><?php echo $merchandising_heading; ?></h2>
<?php echo $merchandising_description; ?>
</div>
<div class="section-button">
<a class="button fill" href="<?php echo $merchandising_url; ?>" target="_blank" alt="see all merchandise">See All Merchandise</a>
</div>
</div>
</div>
</div>
<div class="station-col-wrap">
<?php while ( have_rows('bar_merchandise_assets') ):
the_row();
$merch_label = get_sub_field('label');
$merch_description = get_sub_field('description');
$merch_image_object = get_sub_field('media_preview');
if (empty($merch_image_object)) break; // don't display merch if no image
$merch_image_url = $merch_image_object['url'];
$merch_customize_url = get_sub_field('customize'); ?>
<div data-sr class="station-col">
<img src="<?php echo $merch_image_url; ?>" />
<h3><?php echo $merch_label; ?></h3>
<?php echo $merch_description; ?>
<a href="<?php echo $merch_customize_url; ?>" target="_blank" alt="customize">Customize</a>
</div>
<?php endwhile; ?>
</div>
<?php
$merch_phone = get_field('merchandise_fulfillment_phone', 'options');
$merch_email = get_field('merchandise_fulfillment_email', 'options');
if ( !isset($merch_phone) ) $merch_phone = "312.235.5725";
if ( !isset($merch_email) ) $merch_email = "nestle_help@brandmuscle.com";
?>
<div class="merch-info row">
<h4>Merchandising is fulfilled by Brand Muscle. Need access?</h4>
<p>Call <?php echo $merch_phone; ?> or email <a href="mailto:<?php echo $merch_email; ?>"><?php echo $merch_email; ?></a></p>
</div>
<?php endif; ?>
<?php if ( $show_merchandising == 'yes' && have_rows('bar_sales_assets') ): ?>
<div class="station-section-outer-wrap" id="support" style="background-image: url(<?php echo $sales_bg_url; ?>)">
<div class="station-section-inner-wrap">
<div class="row station-section sales-materials">
<div class="section-content">
<i class="icon"></i>
<h2><?php echo $sales_heading; ?></h2>
<?php echo $sales_description; ?>
</div>
<div class="section-button">
<a class="button fill" href="<?php echo get_zip_download_link($post->post_name, true); ?>">Download Materials</a>
</div>
</div>
</div>
</div>
<div class="station-col-wrap">
<?php while ( have_rows('bar_sales_assets') ):
the_row();
$sales_title = get_sub_field('title');
$sales_description = get_sub_field('description');
$sales_image_object = get_sub_field('media_preview');
$sales_image_url = $sales_image_object['url'];
$sales_file_url = get_sub_field('file'); ?>
<div data-sr class="station-col">
<img src="<?php echo $sales_image_url; ?>" />
<h3><?php echo $sales_title; ?></h3>
<?php echo $sales_description; ?>
<?php if ( !empty($sales_file_url) ): ?>
<a href="<?php echo $sales_file_url; ?>" alt="customize" target="_blank">Download</a>
<?php endif; ?>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
<?php if ( !isset($single_name) ) $single_name = get_field('bar_single_name'); ?>
<div class="download-wrapper">
<div class="row columns download">
<p>Do you need everything? Download the <?php echo $single_name; ?> Action Station Kit. <a class="button fill" href="<?php echo $download_kit_url; ?>">Download Kit</a></p>
</div>
</div> | gpl-2.0 |
divsinghal/strut-viewer | StrutViewer/StrutViewer_UnitTests/MenuItemTests/MenuItemCallback.cs | 3654 | /***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Collections;
using System.Text;
using System.Reflection;
using System.ComponentModel.Design;
using Microsoft.VsSDK.UnitTestLibrary;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.Shell;
using DivyaSinghal.StrutViewer;
namespace StrutViewer_UnitTests.MenuItemTests
{
[TestClass()]
public class MenuItemTest
{
/// <summary>
/// Verify that a new menu command object gets added to the OleMenuCommandService.
/// This action takes place In the Initialize method of the Package object
/// </summary>
[TestMethod]
public void InitializeMenuCommand()
{
// Create the package
IVsPackage package = new StrutViewerPackage() as IVsPackage;
Assert.IsNotNull(package, "The object does not implement IVsPackage");
// Create a basic service provider
OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices();
// Site the package
Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK");
//Verify that the menu command can be found
CommandID menuCommandID = new CommandID(DivyaSinghal.StrutViewer.GuidList.guidStrutViewerCmdSet, (int)DivyaSinghal.StrutViewer.PkgCmdIDList.StrutViewerToolCommand);
System.Reflection.MethodInfo info = typeof(Package).GetMethod("GetService", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.IsNotNull(info);
OleMenuCommandService mcs = info.Invoke(package, new object[] { (typeof(IMenuCommandService)) }) as OleMenuCommandService;
Assert.IsNotNull(mcs.FindCommand(menuCommandID));
}
[TestMethod]
public void MenuItemCallback()
{
// Create the package
IVsPackage package = new StrutViewerPackage() as IVsPackage;
Assert.IsNotNull(package, "The object does not implement IVsPackage");
// Create a basic service provider
OleServiceProvider serviceProvider = OleServiceProvider.CreateOleServiceProviderWithBasicServices();
// Create a UIShell service mock and proffer the service so that it can called from the MenuItemCallback method
BaseMock uishellMock = UIShellServiceMock.GetUiShellInstance();
serviceProvider.AddService(typeof(SVsUIShell), uishellMock, true);
// Site the package
Assert.AreEqual(0, package.SetSite(serviceProvider), "SetSite did not return S_OK");
//Invoke private method on package class and observe that the method does not throw
System.Reflection.MethodInfo info = package.GetType().GetMethod("MenuItemCallback", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.IsNotNull(info, "Failed to get the private method MenuItemCallback throug refplection");
info.Invoke(package, new object[] { null, null });
//Clean up services
serviceProvider.RemoveService(typeof(SVsUIShell));
}
}
}
| gpl-2.0 |
sondang86/nilongxanhnixa | wp-content/themes/shop-isle/template-fullwidth.php | 1906 | <?php
/**
* The template for displaying full width pages.
*
* Template Name: Full width
*
*/
get_header(); ?>
<!-- Wrapper start -->
<div class="main">
<!-- Header section start -->
<?php
$shop_isle_header_image = get_header_image();
if( !empty($shop_isle_header_image) ):
echo '<section class="module bg-dark" data-background="'.$shop_isle_header_image.'">';
else:
echo '<section class="module bg-dark">';
endif;
?>
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<h1 class="module-title font-alt"><?php the_title(); ?></h1>
<?php
/* Header description */
$shop_isle_shop_id = get_the_ID();
if( !empty($shop_isle_shop_id) ):
$shop_isle_page_description = get_post_meta($shop_isle_shop_id, 'shop_isle_page_description');
if( !empty($shop_isle_page_description[0]) ):
echo '<div class="module-subtitle font-serif mb-0">'.$shop_isle_page_description[0].'</div>';
endif;
endif;
?>
</div>
</div><!-- .row -->
</div>
</section>
<!-- Header section end -->
<!-- Pricing start -->
<section class="module">
<div class="container">
<div class="row">
<!-- Content column start -->
<div class="col-sm-12">
<?php
/**
* @hooked woocommerce_breadcrumb - 10
*/
do_action( 'shop_isle_content_top' ); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
do_action( 'storefront_page_before' );
?>
<?php get_template_part( 'content', 'page' ); ?>
<?php
/**
* @hooked storefront_display_comments - 10
*/
do_action( 'storefront_page_after' );
?>
<?php endwhile; // end of the loop. ?>
</div>
</div> <!-- .row -->
</div>
</section>
<!-- Pricing end -->
<?php get_footer(); ?>
| gpl-2.0 |
shannah/cn1 | CodenameOne/src/com/codename1/ui/plaf/DefaultLookAndFeel.java | 68689 | /*
* Copyright (c) 2008, 2010, 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.codename1.ui.plaf;
import com.codename1.components.InfiniteProgress;
import com.codename1.ui.geom.Dimension;
import com.codename1.ui.Graphics;
import com.codename1.ui.Image;
import com.codename1.ui.Button;
import com.codename1.ui.Component;
import com.codename1.ui.Container;
import com.codename1.ui.Display;
import com.codename1.ui.Label;
import com.codename1.ui.List;
import com.codename1.ui.TextArea;
import com.codename1.ui.list.ListCellRenderer;
import com.codename1.ui.list.ListModel;
import com.codename1.ui.Font;
import com.codename1.ui.animations.Animation;
import com.codename1.ui.events.FocusListener;
import com.codename1.ui.geom.Rectangle;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.util.Resources;
/**
* Used to render the default look of Codename One
*
* @author Chen Fishbein
*/
public class DefaultLookAndFeel extends LookAndFeel implements FocusListener {
private Image[] chkBoxImages = null;
private Image comboImage = null;
private Image[] rButtonImages = null;
private Image[] chkBoxImagesFocus = null;
private Image[] rButtonImagesFocus = null;
private boolean tickWhenFocused = true;
private char passwordChar = '\u25CF';
//used for the pull to refresh feature
private Container pull;
private Component updating;
private Component pullDown;
private Component releaseToRefresh;
/** Creates a new instance of DefaultLookAndFeel */
public DefaultLookAndFeel(UIManager manager) {
super(manager);
}
/**
* @inheritDoc
*/
public void bind(Component cmp) {
if (tickWhenFocused && cmp instanceof Label) {
((Label) cmp).addFocusListener(this);
}
}
/**
* This method allows to set all Labels, Buttons, CheckBoxes, RadioButtons
* to start ticking when the text is too long.
* @param tickWhenFocused
*/
public void setTickWhenFocused(boolean tickWhenFocused) {
this.tickWhenFocused = tickWhenFocused;
}
/**
* This method allows to set all Labels, Buttons, CheckBoxes, RadioButtons
* to start ticking when the text is too long.
* @return tickWhenFocused
*/
public boolean isTickWhenFocused() {
return tickWhenFocused;
}
/**
* Sets images for checkbox checked/unchecked modes
*
* @param checkedX the image to draw in order to represent a checked checkbox
* @param uncheckedX the image to draw in order to represent an uncheck checkbox
*/
public void setCheckBoxImages(Image checkedX, Image uncheckedX) {
setCheckBoxImages(checkedX, uncheckedX, checkedX, uncheckedX);
}
/**
* Sets images for checkbox checked/unchecked modes
*
* @param checkedX the image to draw in order to represent a checked checkbox
* @param uncheckedX the image to draw in order to represent an uncheck checkbox
* @param disabledChecked same as checked for the disabled state
* @param disabledUnchecked same as unchecked for the disabled state
*/
public void setCheckBoxImages(Image checkedX, Image uncheckedX, Image disabledChecked, Image disabledUnchecked) {
if (checkedX == null || uncheckedX == null) {
chkBoxImages = null;
} else {
if(disabledUnchecked == null) {
disabledUnchecked = uncheckedX;
}
if(disabledChecked == null) {
disabledChecked = checkedX;
}
chkBoxImages = new Image[]{uncheckedX, checkedX, disabledUnchecked, disabledChecked};
}
}
/**
* Sets images for checkbox when in focused mode
*
* @param checkedX the image to draw in order to represent a checked checkbox
* @param uncheckedX the image to draw in order to represent an uncheck checkbox
* @param disabledChecked same as checked for the disabled state
* @param disabledUnchecked same as unchecked for the disabled state
*/
public void setCheckBoxFocusImages(Image checkedX, Image uncheckedX, Image disabledChecked, Image disabledUnchecked) {
if (checkedX == null || uncheckedX == null) {
chkBoxImagesFocus = null;
} else {
if(disabledUnchecked == null) {
disabledUnchecked = uncheckedX;
}
if(disabledChecked == null) {
disabledChecked = checkedX;
}
chkBoxImagesFocus = new Image[]{uncheckedX, checkedX, disabledUnchecked, disabledChecked};
}
}
/**
* Sets image for the combo box dropdown drawing
*
* @param picker picker image
*/
public void setComboBoxImage(Image picker) {
comboImage = picker;
}
/**
* Sets images for radio button selected/unselected modes
*
* @param selected the image to draw in order to represent a selected radio button
* @param unselected the image to draw in order to represent an unselected radio button
*/
public void setRadioButtonImages(Image selected, Image unselected) {
if (selected == null || unselected == null) {
rButtonImages = null;
} else {
rButtonImages = new Image[]{unselected, selected};
}
}
/**
* Sets images for radio button selected/unselected modes
*
* @param selected the image to draw in order to represent a selected radio button
* @param unselected the image to draw in order to represent an unselected radio button
* @param disabledSelected same as selected for the disabled state
* @param disabledUnselected same as unselected for the disabled state
*/
public void setRadioButtonImages(Image selected, Image unselected, Image disabledSelected, Image disabledUnselected) {
if (selected == null || unselected == null) {
rButtonImages = null;
} else {
if(disabledUnselected == null) {
disabledUnselected = unselected;
}
if(disabledSelected == null) {
disabledSelected = selected;
}
rButtonImages = new Image[]{unselected, selected, disabledUnselected, disabledSelected};
}
}
/**
* Sets images for radio button selected/unselected and disabled modes, when the radio button has focus, these are entirely optional
*
* @param selected the image to draw in order to represent a selected radio button
* @param unselected the image to draw in order to represent an unselected radio button
* @param disabledSelected same as selected for the disabled state
* @param disabledUnselected same as unselected for the disabled state
*/
public void setRadioButtonFocusImages(Image selected, Image unselected, Image disabledSelected, Image disabledUnselected) {
if (selected == null || unselected == null) {
rButtonImagesFocus = null;
} else {
if(disabledUnselected == null) {
disabledUnselected = unselected;
}
if(disabledSelected == null) {
disabledSelected = selected;
}
rButtonImagesFocus = new Image[]{unselected, selected, disabledUnselected, disabledSelected};
}
}
/**
* Sets the password character to display in the TextArea and the TextField
* @param the char to display
*/
public void setPasswordChar(char c){
passwordChar = c;
}
/**
* Returns the images used to represent the radio button (selected followed by unselected).
*
* @return images representing the radio button or null for using the default drawing
*/
public Image[] getRadioButtonImages() {
return rButtonImages;
}
/**
* Returns the images used to represent the radio button when in focused mode
*
* @return images representing the radio button or null for using the default drawing
*/
public Image[] getRadioButtonFocusImages() {
return rButtonImagesFocus;
}
/**
* Returns the images used to represent the checkbox (selected followed by unselected).
*
* @return images representing the check box or null for using the default drawing
*/
public Image[] getCheckBoxImages() {
return chkBoxImages;
}
/**
* Returns the images used to represent the checkbox when focused
*
* @return images representing the check box or null for using the default drawing
*/
public Image[] getCheckBoxFocusImages() {
return chkBoxImagesFocus;
}
/**
* @inheritDoc
*/
public void drawButton(Graphics g, Button b) {
drawComponent(g, b, b.getIconFromState(), null, 0);
}
/**
* @inheritDoc
*/
public void drawCheckBox(Graphics g, Button cb) {
if (chkBoxImages != null) {
Image x;
if(chkBoxImagesFocus != null && chkBoxImagesFocus[0] != null && cb.hasFocus() && Display.getInstance().shouldRenderSelection(cb)) {
if(cb.isEnabled()) {
x = chkBoxImagesFocus[cb.isSelected() ? 1 : 0];
} else {
x = chkBoxImagesFocus[cb.isSelected() ? 3 : 2];
}
} else {
if(cb.isEnabled()) {
x = chkBoxImages[cb.isSelected() ? 1 : 0];
} else {
x = chkBoxImages[cb.isSelected() ? 3 : 2];
}
}
drawComponent(g, cb, cb.getIconFromState(), x, 0);
} else {
Style style = cb.getStyle();
// checkbox square needs to be the height and width of the font height even
// when no text is in the check box this is a good indication of phone DPI
int height = cb.getStyle().getFont().getHeight();
drawComponent(g, cb, cb.getIconFromState(), null, height);
int gradientColor;
g.setColor(style.getFgColor());
gradientColor = style.getBgColor();
int width = height;
int rectWidth = scaleCoordinate(12f, 16, width);
int tX = cb.getX();
if (cb.isRTL()) {
tX = tX + cb.getWidth() - style.getPadding(cb.isRTL(), Component.LEFT) - rectWidth;
} else {
tX += style.getPadding(cb.isRTL(), Component.LEFT);
}
int tY = cb.getY() + style.getPadding(false, Component.TOP) + (cb.getHeight() - style.getPadding(false, Component.TOP) - style.getPadding(false, Component.BOTTOM)) / 2 - height / 2;
g.translate(tX, tY);
int x = scaleCoordinate(1.04f, 16, width);
int y = scaleCoordinate(4.0f, 16, height);
int rectHeight = scaleCoordinate(12f, 16, height);
// brighten or darken the color slightly
int destColor = findDestColor(gradientColor);
g.fillLinearGradient(gradientColor, destColor, x + 1, y + 1, rectWidth - 2, rectHeight - 1, false);
g.drawRoundRect(x, y, rectWidth, rectHeight, 5, 5);
if (cb.isSelected()) {
int color = g.getColor();
g.setColor(0x111111);
g.translate(0, 1);
fillCheckbox(g, width, height);
g.setColor(color);
g.translate(0, -1);
fillCheckbox(g, width, height);
}
g.translate(-tX, -tY);
}
}
private static void fillCheckbox(Graphics g, int width, int height) {
int x1 = scaleCoordinate(2.0450495f, 16, width);
int y1 = scaleCoordinate(9.4227722f, 16, height);
int x2 = scaleCoordinate(5.8675725f, 16, width);
int y2 = scaleCoordinate(13.921746f, 16, height);
int x3 = scaleCoordinate(5.8675725f, 16, width);
int y3 = scaleCoordinate(11f, 16, height);
g.fillTriangle(x1, y1, x2, y2, x3, y3);
x1 = scaleCoordinate(14.38995f, 16, width);
y1 = scaleCoordinate(0, 16, height);
g.fillTriangle(x1, y1, x2, y2, x3, y3);
}
private static int round(float x) {
int rounded = (int) x;
if (x - rounded > 0.5f) {
return rounded + 1;
}
return rounded;
}
/**
* Takes a floating point coordinate on a virtual axis and rusterizes it to
* a coordinate in the pixel surface. This is a very simple algorithm since
* anti-aliasing isn't supported.
*
* @param coordinate a position in a theoretical plain
* @param plain the amount of space in the theoretical plain
* @param pixelSize the amount of pixels available on the screen
* @return the pixel which we should color
*/
private static int scaleCoordinate(float coordinate, float plain, int pixelSize) {
return round(coordinate / plain * pixelSize);
}
/**
* @inheritDoc
*/
public void drawLabel(Graphics g, Label l) {
drawComponent(g, l, l.getMaskedIcon(), null, 0);
}
/**
* @inheritDoc
*/
public void drawRadioButton(Graphics g, Button rb) {
if (rButtonImages != null) {
Image x;
if(rButtonImagesFocus != null && rButtonImagesFocus[0] != null && rb.hasFocus() && Display.getInstance().shouldRenderSelection(rb)) {
if(rb.isEnabled()) {
x = rButtonImagesFocus[rb.isSelected() ? 1 : 0];
} else {
x = rButtonImagesFocus[rb.isSelected() ? 3 : 2];
}
} else {
if(rb.isEnabled()) {
x = rButtonImages[rb.isSelected() ? 1 : 0];
} else {
x = rButtonImages[rb.isSelected() ? 3 : 2];
}
}
drawComponent(g, rb, rb.getIconFromState(), x, 0);
} else {
Style style = rb.getStyle();
// radio button radius needs to be of the size of the font height even
// when no text is in the radio button this is a good indication of phone DPI
int height = rb.getStyle().getFont().getHeight();
drawComponent(g, rb, rb.getIconFromState(), null, height + rb.getGap());
g.setColor(style.getFgColor());
int x = rb.getX();
if (rb.isRTL()) {
x = x + rb.getWidth() - style.getPadding(rb.isRTL(), Component.LEFT) - height;
} else {
x += style.getPadding(rb.isRTL(), Component.LEFT);
}
int y = rb.getY();
// center the RadioButton
y += Math.max(0, rb.getHeight() / 2 - height / 2);
g.drawArc(x, y, height, height, 0, 360);
if (rb.isSelected()) {
int color = g.getColor();
int destColor = findDestColor(color);
g.fillRadialGradient(color, destColor, x + 3, y + 3, height - 5, height - 5);
}
}
}
/**
* @inheritDoc
*/
public void drawComboBox(Graphics g, List cb) {
int border = 2;
Style style = cb.getStyle();
int leftPadding = style.getPadding(cb.isRTL(), Component.LEFT);
int rightPadding = style.getPadding(cb.isRTL(), Component.RIGHT);
setFG(g, cb);
ListModel model = cb.getModel();
ListCellRenderer renderer = cb.getRenderer();
Object value = model.getItemAt(model.getSelectedIndex());
int comboImageWidth;
if (comboImage != null) {
comboImageWidth = comboImage.getWidth();
} else {
comboImageWidth = style.getFont().getHeight();
}
int cellX = cb.getX() + style.getPadding(false, Component.TOP);
if(cb.isRTL()){
cellX += comboImageWidth;
}
if (model.getSize() > 0) {
Component cmp = renderer.getListCellRendererComponent(cb, value, model.getSelectedIndex(), cb.hasFocus());
cmp.setX(cellX);
cmp.setY(cb.getY() + style.getPadding(false, Component.TOP));
cmp.setWidth(cb.getWidth() - comboImageWidth - rightPadding - leftPadding);
cmp.setHeight(cb.getHeight() - style.getPadding(false, Component.TOP) - style.getPadding(false, Component.BOTTOM));
cmp.paint(g);
}
g.setColor(style.getBgColor());
int y = cb.getY();
int height = cb.getHeight();
int width = comboImageWidth + border;
int x = cb.getX();
if (cb.isRTL()) {
x += leftPadding;
} else {
x += cb.getWidth() - comboImageWidth - rightPadding;
}
if (comboImage != null) {
g.drawImage(comboImage, x, y + height / 2 - comboImage.getHeight() / 2);
} else {
int color = g.getColor();
// brighten or darken the color slightly
int destColor = findDestColor(color);
g.fillLinearGradient(g.getColor(), destColor, x, y, width, height, false);
g.setColor(color);
g.drawRect(x, y, width, height - 1);
width--;
height--;
//g.drawRect(x, y, width, height);
g.translate(x + 1, y + 1);
g.setColor(0x111111);
int x1 = scaleCoordinate(2.5652081f, 16, width);
int y1 = scaleCoordinate(4.4753664f, 16, height);
int x2 = scaleCoordinate(8.2872691f, 16, width);
int y2 = scaleCoordinate(10f, 16, height);
int x3 = scaleCoordinate(13.516078f, 16, width);
int y3 = y1;
g.fillTriangle(x1, y1, x2, y2, x3, y3);
g.translate(-1, -1);
g.setColor(style.getFgColor());
g.fillTriangle(x1, y1, x2, y2, x3, y3);
//g.setColor(style.getFgColor());
//g.fillTriangle(x1 + 2, y1 + 2, x2, y2 - 2, x3 - 2, y3 + 2);
g.translate(-x, -y);
}
}
/**
* Finds a suitable destination color for gradient values
*/
private int findDestColor(int color) {
// brighten or darken the color slightly
int sourceR = color >> 16 & 0xff;
int sourceG = color >> 8 & 0xff;
int sourceB = color & 0xff;
if (sourceR > 128 && sourceG > 128 && sourceB > 128) {
// darken
sourceR = Math.max(sourceR >> 1, 0);
sourceG = Math.max(sourceG >> 1, 0);
sourceB = Math.max(sourceB >> 1, 0);
} else {
// special case for black, since all channels are 0 it can't be brightened properly...
if(color == 0) {
return 0x222222;
}
// brighten
sourceR = Math.min(sourceR << 1, 0xff);
sourceG = Math.min(sourceG << 1, 0xff);
sourceB = Math.min(sourceB << 1, 0xff);
}
return ((sourceR << 16) & 0xff0000) | ((sourceG << 8) & 0xff00) | (sourceB & 0xff);
}
/**
* @inheritDoc
*/
public void drawList(Graphics g, List l) {
}
/**
* @inheritDoc
*/
public void drawTextArea(Graphics g, TextArea ta) {
setFG(g, ta);
int line = ta.getLines();
int oX = g.getClipX();
int oY = g.getClipY();
int oWidth = g.getClipWidth();
int oHeight = g.getClipHeight();
Font f = ta.getStyle().getFont();
int fontHeight = f.getHeight();
int align = reverseAlignForBidi(ta);
int leftPadding = ta.getStyle().getPadding(ta.isRTL(), Component.LEFT);
int rightPadding = ta.getStyle().getPadding(ta.isRTL(), Component.RIGHT);
int topPadding = ta.getStyle().getPadding(false, Component.TOP);
boolean shouldBreak = false;
for (int i = 0; i < line; i++) {
int x = ta.getX() + leftPadding;
int y = ta.getY() + topPadding +
(ta.getRowsGap() + fontHeight) * i;
if(Rectangle.intersects(x, y, ta.getWidth(), fontHeight, oX, oY, oWidth, oHeight)) {
String rowText = (String) ta.getTextAt(i);
//display ******** if it is a password field
String displayText = "";
if ((ta.getConstraint() & TextArea.PASSWORD) != 0) {
for (int j = 0; j < rowText.length(); j++) {
displayText += passwordChar;
}
} else {
displayText = rowText;
}
switch(align) {
case Component.RIGHT:
x = ta.getX() + ta.getWidth() - rightPadding - f.stringWidth(displayText);
break;
case Component.CENTER:
x+= (ta.getWidth()-leftPadding-rightPadding-f.stringWidth(displayText))/2;
break;
}
int nextY = ta.getY() + topPadding + (ta.getRowsGap() + fontHeight) * (i + 2);
//if this is the last line to display and there is more content and isEndsWith3Points() is true
//add "..." at the last row
if(ta.isEndsWith3Points() && ta.getGrowLimit() == (i + 1) && ta.getGrowLimit() != line){
if(displayText.length() > 3){
displayText = displayText.substring(0, displayText.length() - 3);
}
g.drawString(displayText + "...", x, y ,ta.getStyle().getTextDecoration());
return;
}else{
g.drawString(displayText, x, y ,ta.getStyle().getTextDecoration());
}
shouldBreak = true;
}else{
if(shouldBreak){
break;
}
}
}
}
/**
* @inheritDoc
*/
public Dimension getButtonPreferredSize(Button b) {
return getPreferredSize(b, new Image[]{b.getMaskedIcon(), b.getRolloverIcon(), b.getPressedIcon()}, null);
}
/**
* @inheritDoc
*/
public Dimension getCheckBoxPreferredSize(Button cb) {
if(cb.isToggle()) {
return getButtonPreferredSize(cb);
}
if (chkBoxImages != null) {
return getPreferredSize(cb, new Image[]{cb.getMaskedIcon(), cb.getRolloverIcon(), cb.getPressedIcon()}, chkBoxImages[0]);
}
Dimension d = getPreferredSize(cb, new Image[]{cb.getMaskedIcon(), cb.getRolloverIcon(), cb.getPressedIcon()}, null);
// checkbox square needs to be the height and width of the font height even
// when no text is in the check box this is a good indication of phone DPI
int checkBoxSquareSize = cb.getStyle().getFont().getHeight();
// allow for checkboxes without a string within them
d.setHeight(Math.max(checkBoxSquareSize, d.getHeight()));
d.setWidth(d.getWidth() + checkBoxSquareSize + cb.getGap());
return d;
}
/**
* @inheritDoc
*/
public Dimension getLabelPreferredSize(Label l) {
return getPreferredSize(l, new Image[]{l.getMaskedIcon()}, null);
}
/**
* @inheritDoc
*/
private Dimension getPreferredSize(Label l, Image[] icons, Image stateImage) {
int prefW = 0;
int prefH = 0;
Style style = l.getStyle();
int gap = l.getGap();
for (int i = 0; i < icons.length; i++) {
Image icon = icons[i];
if (icon != null) {
prefW = Math.max(prefW, icon.getWidth());
prefH = Math.max(prefH, icon.getHeight());
}
}
String text = l.getText();
Font font = style.getFont();
if (font == null) {
System.out.println("Missing font for " + l);
font = Font.getDefaultFont();
}
if (text != null && text.length() > 0) {
//add the text size
switch (l.getTextPosition()) {
case Label.LEFT:
case Label.RIGHT:
prefW += font.stringWidth(text);
prefH = Math.max(prefH, font.getHeight());
break;
case Label.BOTTOM:
case Label.TOP:
prefW = Math.max(prefW, font.stringWidth(text));
prefH += font.getHeight();
break;
}
}
//add the state image(relevant for CheckBox\RadioButton)
if (stateImage != null) {
prefW += (stateImage.getWidth() + gap);
prefH = Math.max(prefH, stateImage.getHeight());
}
if (icons[0] != null && text != null && text.length() > 0) {
switch (l.getTextPosition()) {
case Label.LEFT:
case Label.RIGHT:
prefW += gap;
break;
case Label.BOTTOM:
case Label.TOP:
prefH += gap;
break;
}
}
if (prefH != 0) {
prefH += (style.getPadding(false, Component.TOP) + style.getPadding(false, Component.BOTTOM));
}
if (prefW != 0) {
prefW += (style.getPadding(l.isRTL(), Component.RIGHT) + style.getPadding(l.isRTL(), Component.LEFT));
}
if(style.getBorder() != null) {
prefW = Math.max(style.getBorder().getMinimumWidth(), prefW);
prefH = Math.max(style.getBorder().getMinimumHeight(), prefH);
}
if(isBackgroundImageDetermineSize() && style.getBgImage() != null) {
prefW = Math.max(style.getBgImage().getWidth(), prefW);
prefH = Math.max(style.getBgImage().getHeight(), prefH);
}
return new Dimension(prefW, prefH);
}
/**
* @inheritDoc
*/
public Dimension getListPreferredSize(List l) {
Dimension d = getListPreferredSizeImpl(l);
Style style = l.getStyle();
if(style.getBorder() != null) {
d.setWidth(Math.max(style.getBorder().getMinimumWidth(), d.getWidth()));
d.setHeight(Math.max(style.getBorder().getMinimumHeight(), d.getHeight()));
}
return d;
}
private Dimension getListPreferredSizeImpl(List l) {
int width = 0;
int height = 0;
int selectedHeight;
int selectedWidth;
ListModel model = l.getModel();
int numOfcomponents = Math.max(model.getSize(), l.getMinElementHeight());
numOfcomponents = Math.min(numOfcomponents, l.getMaxElementHeight());
Object prototype = l.getRenderingPrototype();
Style unselectedEntryStyle = null;
Style selectedEntryStyle;
if(prototype != null) {
ListCellRenderer renderer = l.getRenderer();
Component cmp = renderer.getListCellRendererComponent(l, prototype, 0, false);
height = cmp.getPreferredH();
width = cmp.getPreferredW();
unselectedEntryStyle = cmp.getStyle();
cmp = renderer.getListCellRendererComponent(l, prototype, 0, true);
selectedEntryStyle = cmp.getStyle();
selectedHeight = Math.max(height, cmp.getPreferredH());
selectedWidth = Math.max(width, cmp.getPreferredW());
} else {
int hightCalcComponents = Math.min(l.getListSizeCalculationSampleCount(), numOfcomponents);
Object dummyProto = l.getRenderingPrototype();
if(model.getSize() > 0 && dummyProto == null) {
dummyProto = model.getItemAt(0);
}
ListCellRenderer renderer = l.getRenderer();
for (int i = 0; i < hightCalcComponents; i++) {
Object value;
if(i < model.getSize()) {
value = model.getItemAt(i);
} else {
value = dummyProto;
}
Component cmp = renderer.getListCellRendererComponent(l, value, i, false);
if(cmp instanceof Container) {
cmp.setShouldCalcPreferredSize(true);
}
unselectedEntryStyle = cmp.getStyle();
height = Math.max(height, cmp.getPreferredH());
width = Math.max(width, cmp.getPreferredW());
}
selectedEntryStyle = unselectedEntryStyle;
selectedHeight = height;
selectedWidth = width;
if (model.getSize() > 0) {
Object value = model.getItemAt(0);
Component cmp = renderer.getListCellRendererComponent(l, value, 0, true);
if(cmp instanceof Container) {
cmp.setShouldCalcPreferredSize(true);
}
selectedHeight = Math.max(height, cmp.getPreferredH());
selectedWidth = Math.max(width, cmp.getPreferredW());
selectedEntryStyle = cmp.getStyle();
}
}
if(unselectedEntryStyle != null) {
selectedWidth += selectedEntryStyle.getMargin(false, Component.LEFT) + selectedEntryStyle.getMargin(false, Component.RIGHT);
selectedHeight += selectedEntryStyle.getMargin(false, Component.TOP) + selectedEntryStyle.getMargin(false, Component.BOTTOM);
width += unselectedEntryStyle.getMargin(false, Component.LEFT) + unselectedEntryStyle.getMargin(false, Component.RIGHT);
height += unselectedEntryStyle.getMargin(false, Component.TOP) + unselectedEntryStyle.getMargin(false, Component.BOTTOM);
}
Style lStyle = l.getStyle();
int verticalPadding = lStyle.getPadding(false, Component.TOP) + lStyle.getPadding(false, Component.BOTTOM);
int horizontalPadding = lStyle.getPadding(false, Component.RIGHT) + lStyle.getPadding(false, Component.LEFT);
if (numOfcomponents == 0) {
return new Dimension(horizontalPadding, verticalPadding);
}
// If combobox without ever importing the ComboBox class dependency
if(l.getOrientation() > List.HORIZONTAL) {
int boxWidth = l.getStyle().getFont().getHeight() + 2;
return new Dimension(boxWidth + selectedWidth + horizontalPadding, selectedHeight + verticalPadding);
} else {
if (l.getOrientation() == List.VERTICAL) {
return new Dimension(selectedWidth + horizontalPadding, selectedHeight + (height + l.getItemGap()) * (numOfcomponents - 1) + verticalPadding);
} else {
return new Dimension(selectedWidth + (width + l.getItemGap()) * (numOfcomponents - 1) + horizontalPadding, selectedHeight + verticalPadding);
}
}
}
/**
* @inheritDoc
*/
public Dimension getRadioButtonPreferredSize(Button rb) {
if(rb.isToggle()) {
return getButtonPreferredSize(rb);
}
if (rButtonImages != null) {
return getPreferredSize(rb, new Image[]{rb.getMaskedIcon(), rb.getRolloverIcon(), rb.getPressedIcon()}, rButtonImages[0]);
}
Dimension d = getPreferredSize(rb, new Image[]{rb.getMaskedIcon(), rb.getRolloverIcon(), rb.getPressedIcon()}, null);
// radio button radius needs to be of the size of the font height even
// when no text is in the radio button this is a good indication of phone DPI
int height = rb.getStyle().getFont().getHeight();
// allow for radio buttons without a string within them
d.setHeight(Math.max(height, d.getHeight()));
d.setWidth(d.getWidth() + height + rb.getGap());
return d;
}
/**
* @inheritDoc
*/
public Dimension getTextAreaSize(TextArea ta, boolean pref) {
int prefW = 0;
int prefH = 0;
Style style = ta.getStyle();
Font f = style.getFont();
//if this is a text field the preferred size should be the text width
if (ta.getRows() == 1) {
prefW = f.stringWidth(ta.getText());
} else {
prefW = f.charWidth(TextArea.getWidestChar()) * ta.getColumns();
}
int rows;
if(pref) {
rows = ta.getActualRows();
} else {
rows = ta.getLines();
}
prefH = (f.getHeight() + ta.getRowsGap()) * rows;
int columns = ta.getColumns();
String str = "";
for (int iter = 0; iter < columns; iter++) {
str += TextArea.getWidestChar();
}
if(columns > 0) {
prefW = Math.max(prefW, f.stringWidth(str));
}
prefH = Math.max(prefH, rows * f.getHeight());
prefW += style.getPadding(false, Component.RIGHT) + style.getPadding(false, Component.LEFT);
prefH += style.getPadding(false, Component.TOP) + style.getPadding(false, Component.BOTTOM);
if(style.getBorder() != null) {
prefW = Math.max(style.getBorder().getMinimumWidth(), prefW);
prefH = Math.max(style.getBorder().getMinimumHeight(), prefH);
}
if(isBackgroundImageDetermineSize() && style.getBgImage() != null) {
prefW = Math.max(style.getBgImage().getWidth(), prefW);
prefH = Math.max(style.getBgImage().getHeight(), prefH);
}
return new Dimension(prefW, prefH);
}
/**
* Reverses alignment in the case of bidi
*/
private int reverseAlignForBidi(Component c) {
return reverseAlignForBidi(c, c.getStyle().getAlignment());
}
/**
* Reverses alignment in the case of bidi
*/
private int reverseAlignForBidi(Component c, int align) {
if(c.isRTL()) {
switch(align) {
case Component.RIGHT:
return Component.LEFT;
case Component.LEFT:
return Component.RIGHT;
}
}
return align;
}
private void drawComponent(Graphics g, Label l, Image icon, Image stateIcon, int preserveSpaceForState) {
setFG(g, l);
int gap = l.getGap();
int stateIconSize = 0;
int stateIconYPosition = 0;
String text = l.getText();
Style style = l.getStyle();
int cmpX = l.getX();
int cmpY = l.getY();
int cmpHeight = l.getHeight();
int cmpWidth = l.getWidth();
boolean rtl = l.isRTL();
int leftPadding = style.getPadding(rtl, Component.LEFT);
int rightPadding = style.getPadding(rtl, Component.RIGHT);
int topPadding = style.getPadding(false, Component.TOP);
int bottomPadding = style.getPadding(false, Component.BOTTOM);
Font font = style.getFont();
int fontHeight = 0;
if (text == null) {
text = "";
}
if(text.length() > 0){
fontHeight = font.getHeight();
}
if (stateIcon != null) {
stateIconSize = stateIcon.getWidth(); //square image width == height
stateIconYPosition = cmpY + topPadding +
(cmpHeight - topPadding -
bottomPadding) / 2 - stateIconSize / 2;
int tX = cmpX;
if(((Button)l).isOppositeSide()) {
if (rtl) {
tX += leftPadding;
} else {
tX = tX + cmpWidth - leftPadding - stateIconSize;
}
cmpWidth -= leftPadding - stateIconSize;
} else {
preserveSpaceForState = stateIconSize + gap;
if (rtl) {
tX = tX + cmpWidth - leftPadding - stateIconSize;
} else {
tX += leftPadding;
}
}
g.drawImage(stateIcon, tX, stateIconYPosition);
}
//default for bottom left alignment
int x = cmpX + leftPadding + preserveSpaceForState;
int y = cmpY + topPadding;
int align = reverseAlignForBidi(l, style.getAlignment());
int textPos= reverseAlignForBidi(l, l.getTextPosition());
//set initial x,y position according to the alignment and textPosition
if (align == Component.LEFT) {
switch (textPos) {
case Label.LEFT:
case Label.RIGHT:
y = y + (cmpHeight - (topPadding + bottomPadding + Math.max(((icon != null) ? icon.getHeight() : 0), fontHeight))) / 2;
break;
case Label.BOTTOM:
case Label.TOP:
y = y + (cmpHeight - (topPadding + bottomPadding + ((icon != null) ? icon.getHeight() + gap : 0) + fontHeight)) / 2;
break;
}
} else if (align == Component.CENTER) {
switch (textPos) {
case Label.LEFT:
case Label.RIGHT:
x = x + (cmpWidth - (preserveSpaceForState +
leftPadding +
rightPadding +
((icon != null) ? icon.getWidth() + l.getGap() : 0) +
font.stringWidth(text))) / 2;
x = Math.max(x, cmpX + leftPadding + preserveSpaceForState);
y = y + (cmpHeight - (topPadding +
bottomPadding +
Math.max(((icon != null) ? icon.getHeight() : 0),
fontHeight))) / 2;
break;
case Label.BOTTOM:
case Label.TOP:
x = x + (cmpWidth - (preserveSpaceForState + leftPadding +
rightPadding +
Math.max(((icon != null) ? icon.getWidth() + l.getGap() : 0),
font.stringWidth(text)))) / 2;
x = Math.max(x, cmpX + leftPadding + preserveSpaceForState);
y = y + (cmpHeight - (topPadding +
bottomPadding +
((icon != null) ? icon.getHeight() + gap : 0) +
fontHeight)) / 2;
break;
}
} else if (align == Component.RIGHT) {
switch (textPos) {
case Label.LEFT:
case Label.RIGHT:
x = cmpX + cmpWidth - rightPadding -
( ((icon != null) ? (icon.getWidth() + gap) : 0) +
font.stringWidth(text));
if(l.isRTL()) {
x = Math.max(x - preserveSpaceForState, cmpX + leftPadding);
} else {
x = Math.max(x, cmpX + leftPadding + preserveSpaceForState);
}
y = y + (cmpHeight - (topPadding +
bottomPadding +
Math.max(((icon != null) ? icon.getHeight() : 0),
fontHeight))) / 2;
break;
case Label.BOTTOM:
case Label.TOP:
x = cmpX + cmpWidth - rightPadding -
(Math.max(((icon != null) ? (icon.getWidth()) : 0),
font.stringWidth(text)));
x = Math.max(x, cmpX + leftPadding + preserveSpaceForState);
y = y + (cmpHeight - (topPadding +
bottomPadding +
((icon != null) ? icon.getHeight() + gap : 0) + fontHeight)) / 2;
break;
}
}
int textSpaceW = cmpWidth - rightPadding - leftPadding;
if (icon != null && (textPos == Label.RIGHT || textPos == Label.LEFT)) {
textSpaceW = textSpaceW - icon.getWidth();
}
if (stateIcon != null) {
textSpaceW = textSpaceW - stateIconSize;
} else {
textSpaceW = textSpaceW - preserveSpaceForState;
}
if (icon == null) { // no icon only string
drawLabelString(g, l, text, x, y, textSpaceW);
} else {
int strWidth = font.stringWidth(text);
int iconWidth = icon.getWidth();
int iconHeight = icon.getHeight();
int iconStringWGap;
int iconStringHGap;
switch (textPos) {
case Label.LEFT:
if (iconHeight > fontHeight) {
iconStringHGap = (iconHeight - fontHeight) / 2;
strWidth = drawLabelStringValign(g, l, text, x, y, iconStringHGap, iconHeight, textSpaceW, fontHeight);
g.drawImage(icon, x + strWidth + gap, y);
} else {
iconStringHGap = (fontHeight - iconHeight) / 2;
strWidth = drawLabelString(g, l, text, x, y, textSpaceW);
g.drawImage(icon, x + strWidth + gap, y + iconStringHGap);
}
break;
case Label.RIGHT:
if (iconHeight > fontHeight) {
iconStringHGap = (iconHeight - fontHeight) / 2;
g.drawImage(icon, x, y);
drawLabelStringValign(g, l, text, x + iconWidth + gap, y, iconStringHGap, iconHeight, textSpaceW, fontHeight);
} else {
iconStringHGap = (fontHeight - iconHeight) / 2;
g.drawImage(icon, x, y + iconStringHGap);
drawLabelString(g, l, text, x + iconWidth + gap, y, textSpaceW);
}
break;
case Label.BOTTOM:
if (iconWidth > strWidth) { //center align the smaller
iconStringWGap = (iconWidth - strWidth) / 2;
g.drawImage(icon, x, y);
drawLabelString(g, l, text, x + iconStringWGap, y + iconHeight + gap, textSpaceW);
} else {
iconStringWGap = (Math.min(strWidth, textSpaceW) - iconWidth) / 2;
g.drawImage(icon, x + iconStringWGap, y);
drawLabelString(g, l, text, x, y + iconHeight + gap, textSpaceW);
}
break;
case Label.TOP:
if (iconWidth > strWidth) { //center align the smaller
iconStringWGap = (iconWidth - strWidth) / 2;
drawLabelString(g, l, text, x + iconStringWGap, y, textSpaceW);
g.drawImage(icon, x, y + fontHeight + gap);
} else {
iconStringWGap = (Math.min(strWidth, textSpaceW) - iconWidth) / 2;
drawLabelString(g, l, text, x, y, textSpaceW);
g.drawImage(icon, x + iconStringWGap, y + fontHeight + gap);
}
break;
}
}
}
/**
* Implements the drawString for the text component and adjust the valign
* assuming the icon is in one of the sides
*/
private int drawLabelStringValign(Graphics g, Label l, String str, int x, int y,
int iconStringHGap, int iconHeight, int textSpaceW, int fontHeight) {
switch (l.getVerticalAlignment()) {
case Component.TOP:
return drawLabelString(g, l, str, x, y, textSpaceW);
case Component.CENTER:
return drawLabelString(g, l, str, x, y + iconHeight / 2 - fontHeight / 2, textSpaceW);
default:
return drawLabelString(g, l, str, x, y + iconStringHGap, textSpaceW);
}
}
/**
* Implements the drawString for the text component and adjust the valign
* assuming the icon is in one of the sides
*/
private int drawLabelString(Graphics g, Label l, String text, int x, int y, int textSpaceW) {
Style style = l.getStyle();
int cx = g.getClipX();
int cy = g.getClipY();
int cw = g.getClipWidth();
int ch = g.getClipHeight();
//g.pushClip();
g.clipRect(x, cy, textSpaceW, ch);
if (l.isTickerRunning()) {
if (l.getShiftText() > 0) {
if (l.getShiftText() > textSpaceW) {
l.setShiftText(x - l.getX() - style.getFont().stringWidth(text));
}
} else if (l.getShiftText() + style.getFont().stringWidth(text) < 0) {
l.setShiftText(textSpaceW);
}
}
int drawnW = drawLabelText(g, l, text, x, y, textSpaceW);
g.setClip(cx, cy, cw, ch);
//g.popClip();
return drawnW;
}
/**
* Draws the text of a label
*
* @param g graphics context
* @param l label component
* @param text the text for the label
* @param x position for the label
* @param y position for the label
* @param textSpaceW the width available for the component
* @return the space used by the drawing
*/
protected int drawLabelText(Graphics g, Label l, String text, int x, int y, int textSpaceW) {
Style style = l.getStyle();
Font f = style.getFont();
boolean rtl = l.isRTL();
boolean isTickerRunning = l.isTickerRunning();
int txtW = f.stringWidth(text);
if ((!isTickerRunning) || rtl) {
//if there is no space to draw the text add ... at the end
if (txtW > textSpaceW && textSpaceW > 0) {
// Handling of adding 3 points and in fact all text positioning when the text is bigger than
// the allowed space is handled differently in RTL, this is due to the reverse algorithm
// effects - i.e. when the text includes both Hebrew/Arabic and English/numbers then simply
// trimming characters from the end of the text (as done with LTR) won't do.
// Instead we simple reposition the text, and draw the 3 points, this is quite simple, but
// the downside is that a part of a letter may be shown here as well.
if (rtl) {
if ((!isTickerRunning) && (l.isEndsWith3Points())) {
String points = "...";
int pointsW = f.stringWidth(points);
g.drawString(points, l.getShiftText() + x, y,l.getStyle().getTextDecoration());
g.clipRect(pointsW+l.getShiftText() + x, y, textSpaceW - pointsW, f.getHeight());
}
x = x - txtW + textSpaceW;
} else {
if (l.isEndsWith3Points()) {
String points = "...";
int index = 1;
int widest = f.charWidth('W');
int pointsW = f.stringWidth(points);
while (fastCharWidthCheck(text, index, textSpaceW - pointsW, widest, f) && index < text.length()){
index++;
}
text = text.substring(0, Math.min(text.length(), Math.max(1, index-1))) + points;
txtW = f.stringWidth(text);
}
}
}
}
g.drawString(text, l.getShiftText() + x, y,style.getTextDecoration());
return Math.min(txtW, textSpaceW);
}
private boolean fastCharWidthCheck(String s, int length, int width, int charWidth, Font f) {
if(length * charWidth < width) {
return true;
}
length = Math.min(s.length(), length);
return f.substringWidth(s, 0, length) < width;
}
/**
* @inheritDoc
*/
public Dimension getComboBoxPreferredSize(List cb) {
Dimension d = getListPreferredSize(cb);
if(comboImage != null) {
d.setWidth(d.getWidth() + comboImage.getWidth());
d.setHeight(Math.max(d.getHeight(), comboImage.getHeight()));
}
return d;
}
/**
* Similar to getText() but works properly with password fields
*/
protected String getTextFieldString(TextArea ta) {
String txt = ta.getText();
String text;
if(ta.isSingleLineTextArea()){
text = txt;
}else{
text = (String) ta.getTextAt(ta.getCursorY());
if(ta.getCursorPosition() + text.length() < txt.length()){
char c = txt.charAt(ta.getCursorPosition() + text.length());
if(c == '\n'){
text += "\n";
}else if(c == ' '){
text += " ";
}
}
}
String displayText = "";
if ((ta.getConstraint() & TextArea.PASSWORD) != 0) {
// show the last character in a password field
if (ta.isPendingCommit()) {
if (text.length() > 0) {
for (int j = 0; j < text.length() - 1; j++) {
displayText += passwordChar;
}
displayText += text.charAt(text.length() - 1);
}
} else {
for (int j = 0; j < text.length(); j++) {
displayText += passwordChar;
}
}
} else {
displayText = text;
}
return displayText;
}
/**
* @inheritDoc
*/
public void drawTextField(Graphics g, TextArea ta) {
setFG(g, ta);
// display ******** if it is a password field
String displayText = getTextFieldString(ta);
Style style = ta.getStyle();
int x = 0;
int cursorCharPosition = ta.getCursorPosition();//ta.getCursorX();
Font f = ta.getStyle().getFont();
int cursorX = 0;
int xPos = 0;
int align = reverseAlignForBidi(ta);
int displayX = 0;
String inputMode = ta.getInputMode();
int inputModeWidth = f.stringWidth(inputMode);
// QWERTY devices don't quite have an input mode hide it also when we have a VK
if(ta.isQwertyInput() || Display.getInstance().isVirtualKeyboardShowing()) {
inputMode = "";
inputModeWidth = 0;
}
if (ta.isSingleLineTextArea()) {
// there is currently no support for CENTER aligned text fields
if (align == Component.LEFT) {
if (cursorCharPosition > 0) {
cursorCharPosition = Math.min(displayText.length(),
cursorCharPosition);
xPos = f.stringWidth(displayText.substring(0, cursorCharPosition));
cursorX = ta.getX() + style.getPadding(ta.isRTL(), Component.LEFT) + xPos;
// no point in showing the input mode when there is only one input mode...
if (inputModeWidth > 0 && ta.getInputModeOrder() != null && ta.getInputModeOrder().length == 1) {
inputModeWidth = 0;
}
if (ta.isEnableInputScroll()) {
if (ta.getWidth() > (f.getHeight() * 2) && cursorX >= ta.getWidth() - inputModeWidth - style.getPadding(ta.isRTL(), Component.LEFT)) {
if (x + xPos >= ta.getWidth() - inputModeWidth - style.getPadding(ta.isRTL(), Component.LEFT) * 2) {
x=ta.getWidth() - inputModeWidth - style.getPadding(ta.isRTL(), Component.LEFT) * 2 - xPos - 1;
}
}
}
}
displayX = ta.getX() + x + style.getPadding(ta.isRTL(), Component.LEFT);
} else {
x = 0;
cursorX = getTextFieldCursorX(ta);
int baseX = ta.getX() + style.getPadding(false, Component.LEFT) + inputModeWidth;
int endX = ta.getX() + ta.getWidth() - style.getPadding(false, Component.RIGHT);
if (cursorX < baseX) {
x = baseX - cursorX;
} else {
if (cursorX > endX) {
x = endX - cursorX;
}
}
displayX = ta.getX() + ta.getWidth() - style.getPadding(false, Component.RIGHT) - style.getPadding(false, Component.LEFT) - f.stringWidth(displayText) + x;
}
int cx = g.getClipX();
int cy = g.getClipY();
int cw = g.getClipWidth();
int ch = g.getClipHeight();
int clipx = ta.getX() + style.getPadding(ta.isRTL(), Component.LEFT);
int clipw = ta.getWidth() - style.getPadding(ta.isRTL(), Component.LEFT) - style.getPadding(ta.isRTL(), Component.RIGHT);
//g.pushClip();
g.clipRect(clipx, cy, clipw, ch);
switch(ta.getVerticalAlignment()) {
case Component.BOTTOM:
g.drawString(displayText, displayX, ta.getY() + ta.getHeight() - style.getPadding(false, Component.BOTTOM) - f.getHeight(), ta.getStyle().getTextDecoration());
break;
case Component.CENTER:
g.drawString(displayText, displayX, ta.getY() + ta.getHeight() / 2 - f.getHeight() / 2, ta.getStyle().getTextDecoration());
break;
default:
g.drawString(displayText, displayX, ta.getY() + style.getPadding(false, Component.TOP), ta.getStyle().getTextDecoration());
break;
}
g.setClip(cx, cy, cw, ch);
//g.popClip();
} else {
drawTextArea(g, ta);
}
// no point in showing the input mode when there is only one input mode...
if(inputModeWidth > 0 && ta.getInputModeOrder() != null && ta.getInputModeOrder().length > 1) {
if (ta.handlesInput() && ta.getWidth() / 2 > inputModeWidth) {
int drawXPos = ta.getX() + style.getPadding(ta.isRTL(), Component.LEFT);
if((!ta.isRTL() && ta.getStyle().getAlignment() == Component.LEFT) ||
(ta.isRTL() && ta.getStyle().getAlignment() == Component.RIGHT)) {
drawXPos = drawXPos + ta.getWidth() - inputModeWidth - style.getPadding(false, Component.RIGHT) - style.getPadding(false, Component.LEFT);
}
g.setColor(style.getFgColor());
int inputIndicatorY = ta.getY()+ ta.getScrollY() + ta.getHeight() -
style.getPadding(false, Component.BOTTOM) -
f.getHeight();
g.fillRect(drawXPos, inputIndicatorY, inputModeWidth,
f.getHeight(), (byte) 140);
g.setColor(style.getBgColor());
g.drawString(inputMode, drawXPos, inputIndicatorY);
}
}
}
/**
* Returns true if the given character is an RTL character or a space
* character
*
* @param c character to test
* @return true if bidi is active and this is a
*/
private boolean isRTLOrWhitespace(char c) {
return (Display.getInstance().isRTL(c)) || c == ' ';
}
/**
* Calculates the position of the text field cursor within the string
*/
private int getTextFieldCursorX(TextArea ta) {
Style style = ta.getStyle();
Font f = style.getFont();
// display ******** if it is a password field
String displayText = getTextFieldString(ta);
String inputMode = ta.getInputMode();
int inputModeWidth = f.stringWidth(inputMode);
// QWERTY devices don't quite have an input mode hide it also when we have a VK
if(ta.isQwertyInput() || Display.getInstance().isVirtualKeyboardShowing()) {
inputMode = "";
inputModeWidth = 0;
}
int xPos = 0;
int cursorCharPosition = ta.getCursorX();
int cursorX=0;
int x = 0;
if (reverseAlignForBidi(ta) == Component.RIGHT) {
if (Display.getInstance().isBidiAlgorithm()) {
//char[] dest = displayText.toCharArray();
cursorCharPosition = Display.getInstance().getCharLocation(displayText, cursorCharPosition-1);
if (cursorCharPosition==-1) {
xPos = f.stringWidth(displayText);
} else {
displayText = Display.getInstance().convertBidiLogicalToVisual(displayText);
if (!isRTLOrWhitespace((displayText.charAt(cursorCharPosition)))) {
cursorCharPosition++;
}
xPos = f.stringWidth(displayText.substring(0, cursorCharPosition));
}
}
int displayX = ta.getX() + ta.getWidth() - style.getPadding(ta.isRTL(), Component.LEFT) - f.stringWidth(displayText);
cursorX = displayX + xPos;
x=0;
} else {
if (cursorCharPosition > 0) {
cursorCharPosition = Math.min(displayText.length(),
cursorCharPosition);
xPos = f.stringWidth(displayText.substring(0, cursorCharPosition));
}
cursorX = ta.getX() + style.getPadding(ta.isRTL(), Component.LEFT) + xPos;
if (ta.isSingleLineTextArea() && ta.getWidth() > (f.getHeight() * 2) && cursorX >= ta.getWidth() - inputModeWidth -style.getPadding(ta.isRTL(), Component.LEFT)) {
if (x + xPos >= ta.getWidth() - inputModeWidth - style.getPadding(false, Component.LEFT) - style.getPadding(false, Component.RIGHT)) {
x = ta.getWidth() - inputModeWidth - style.getPadding(false, Component.LEFT) - style.getPadding(false, Component.RIGHT) - xPos -1;
}
}
}
return cursorX+x;
}
/**
* @inheritDoc
*/
public Dimension getTextFieldPreferredSize(TextArea ta) {
return getTextAreaSize(ta, true);
}
/**
* @inheritDoc
*/
public void drawTextFieldCursor(Graphics g, TextArea ta) {
Style style = ta.getStyle();
Font f = style.getFont();
int cursorY = ta.getY() + style.getPadding(false, Component.TOP) +
ta.getCursorY() * (ta.getRowsGap() + f.getHeight());
if(ta.isSingleLineTextArea()) {
switch(ta.getVerticalAlignment()) {
case Component.BOTTOM:
cursorY = ta.getY() + ta.getHeight() - f.getHeight();
break;
case Component.CENTER:
cursorY = ta.getY() + ta.getHeight() / 2 - f.getHeight() / 2;
break;
default:
cursorY = ta.getY() + style.getPadding(false, Component.TOP);
break;
}
} else {
cursorY = ta.getY() + style.getPadding(false, Component.TOP) + ta.getCursorY() * (ta.getRowsGap() + f.getHeight());
}
int cursorX = getTextFieldCursorX(ta);
int align = reverseAlignForBidi(ta);
int x=0;
if (align==Component.RIGHT) {
String inputMode = ta.getInputMode();
int inputModeWidth = f.stringWidth(inputMode);
int baseX=ta.getX()+style.getPadding(false, Component.LEFT)+inputModeWidth;
if (cursorX<baseX) {
x=baseX-cursorX;
}
}
int oldColor = g.getColor();
if(getTextFieldCursorColor() == 0) {
g.setColor(style.getFgColor());
} else {
g.setColor(getTextFieldCursorColor());
}
g.drawLine(cursorX + x, cursorY, cursorX + x, cursorY + f.getHeight());
g.setColor(oldColor);
}
/**
* @inheritDoc
*/
public void drawPullToRefresh(Graphics g, final Component cmp, boolean taskExecuted) {
final int scrollY = cmp.getScrollY();
Component cmpToDraw;
if (taskExecuted) {
cmpToDraw = updating;
} else {
if (-scrollY > getPullToRefreshHeight()) {
cmpToDraw = releaseToRefresh;
} else {
cmpToDraw = pullDown;
}
}
if (pull.getComponentAt(0) != updating && cmpToDraw != pull.getComponentAt(0)) {
cmp.getComponentForm().registerAnimated(new Animation() {
int counter = 0;
Image i;
{
i = UIManager.getInstance().getThemeImageConstant("pullToRefreshImage");
if(i == null) {
i = Resources.getSystemResource().getImage("refresh-icon.png");
}
}
public boolean animate() {
counter++;
if (pull.getComponentAt(0) == releaseToRefresh) {
((Label) releaseToRefresh).setIcon(i.rotate(180 - (180 / 6)*counter));
} else {
((Label) pullDown).setIcon(i.rotate(180 *counter/ 6));
}
if (counter == 6) {
((Label) releaseToRefresh).setIcon(i);
((Label) pullDown).setIcon(i.rotate(180));
cmp.getComponentForm().deregisterAnimated(this);
}
cmp.repaint(cmp.getAbsoluteX(), cmp.getAbsoluteY() - getPullToRefreshHeight(), cmp.getWidth(),
getPullToRefreshHeight());
return false;
}
public void paint(Graphics g) {
}
});
}
if(pull.getComponentAt(0) != cmpToDraw
&& cmpToDraw instanceof Label
&& (pull.getComponentAt(0) instanceof Label)){
((Label)cmpToDraw).setIcon(((Label)pull.getComponentAt(0)).getIcon());
}
pull.replace(pull.getComponentAt(0), cmpToDraw, null);
pull.setWidth(cmp.getWidth());
pull.setX(cmp.getAbsoluteX());
pull.setY(cmp.getY() -scrollY - getPullToRefreshHeight());
pull.layoutContainer();
pull.paintComponent(g);
}
/**
* @inheritDoc
*/
public int getPullToRefreshHeight() {
if (pull == null) {
BorderLayout bl = new BorderLayout();
bl.setCenterBehavior(BorderLayout.CENTER_BEHAVIOR_CENTER_ABSOLUTE);
pull = new Container(bl);
}
if (pullDown == null) {
pullDown = new Label(getUIManager().localize("pull.down", "Pull down do refresh..."));
pullDown.getStyle().setAlignment(Component.CENTER);
Image i = Resources.getSystemResource().getImage("refresh-icon.png");
i = i.rotate(180);
((Label) pullDown).setIcon(i);
}
if (releaseToRefresh == null) {
releaseToRefresh = new Label(getUIManager().localize("pull.release", "Release to refresh..."));
releaseToRefresh.getStyle().setAlignment(Component.CENTER);
((Label) releaseToRefresh).setIcon(Resources.getSystemResource().getImage("refresh-icon.png"));
}
if (updating == null) {
updating = new Container(new BoxLayout(BoxLayout.X_AXIS));
((Container) updating).addComponent(new InfiniteProgress());
((Container) updating).addComponent(new Label(getUIManager().localize("pull.refresh", "Updating...")));
pull.addComponent(BorderLayout.CENTER, updating);
pull.layoutContainer();
pull.setHeight(Math.max(pullDown.getPreferredH(), pull.getPreferredH()));
}
return pull.getHeight();
}
/**
* @inheritDoc
*/
public void focusGained(Component cmp) {
if(cmp instanceof Label) {
Label l = (Label) cmp;
if (l.isTickerEnabled() && l.shouldTickerStart() && Display.getInstance().shouldRenderSelection(cmp)) {
((Label) cmp).startTicker(getTickerSpeed(), true);
}
}
}
/**
* @inheritDoc
*/
public void focusLost(Component cmp) {
if(cmp instanceof Label) {
Label l = (Label) cmp;
if (l.isTickerRunning()) {
l.stopTicker();
}
}
}
/**
* @inheritDoc
*/
public void refreshTheme(boolean b) {
chkBoxImages = null;
comboImage = null;
rButtonImages = null;
chkBoxImagesFocus = null;
rButtonImagesFocus = null;
super.refreshTheme(b);
UIManager m = getUIManager();
Image combo = m.getThemeImageConstant("comboImage");
if(combo != null) {
setComboBoxImage(combo);
}
updateCheckBoxConstants(m, false, "");
updateCheckBoxConstants(m, true, "Focus");
updateRadioButtonConstants(m, false, "");
updateRadioButtonConstants(m, true, "Focus");
}
private void updateCheckBoxConstants(UIManager m, boolean focus, String append) {
Image checkSel = m.getThemeImageConstant("checkBoxChecked" + append + "Image");
if(checkSel != null) {
Image checkUnsel = m.getThemeImageConstant("checkBoxUnchecked" + append + "Image");
if(checkUnsel != null) {
Image disUnsel = m.getThemeImageConstant("checkBoxUncheckDis" + append + "Image");
Image disSel = m.getThemeImageConstant("checkBoxCheckDis" + append + "Image");
if(disSel == null) {
disSel = checkSel;
}
if(disUnsel == null) {
disUnsel = checkUnsel;
}
if(focus) {
setCheckBoxFocusImages(checkSel, checkUnsel, disSel, disUnsel);
} else {
setCheckBoxImages(checkSel, checkUnsel, disSel, disUnsel);
}
}
if(checkUnsel != null) {
if(focus) {
setCheckBoxFocusImages(checkSel, checkUnsel, checkSel, checkUnsel);
} else {
setCheckBoxImages(checkSel, checkUnsel);
}
}
}
}
private void updateRadioButtonConstants(UIManager m, boolean focus, String append) {
Image radioSel = m.getThemeImageConstant("radioSelected" + append + "Image");
if(radioSel != null) {
Image radioUnsel = m.getThemeImageConstant("radioUnselected" + append + "Image");
if(radioUnsel != null) {
Image disUnsel = m.getThemeImageConstant("radioUnselectedDis" + append + "Image");
Image disSel = m.getThemeImageConstant("radioSelectedDis" + append + "Image");
if(disUnsel == null) {
disUnsel = radioUnsel;
}
if(disSel == null) {
disSel = radioSel;
}
if(focus) {
setRadioButtonFocusImages(radioSel, radioUnsel, disSel, disUnsel);
} else {
setRadioButtonImages(radioSel, radioUnsel, disSel, disUnsel);
}
}
}
}
}
| gpl-2.0 |
edipdincer/abbc3 | tests/core/acp_base.php | 1014 | <?php
/**
*
* Advanced BBCode Box
*
* @copyright (c) 2014 Matt Friedman
* @license GNU General Public License, version 2 (GPL-2.0)
*
*/
namespace vse\abbc3\tests\core;
class acp_base extends \phpbb_database_test_case
{
static protected function setup_extensions()
{
return array('vse/abbc3');
}
/** @var \phpbb\db\driver\driver_interface */
protected $db;
/** @var \phpbb\request\request|\PHPUnit_Framework_MockObject_MockObject */
protected $request;
/** @var \phpbb\user */
protected $user;
public function getDataSet()
{
return $this->createXMLDataSet(dirname(__FILE__) . '/fixtures/bbcodes.xml');
}
public function setUp()
{
parent::setUp();
$this->db = $this->new_dbal();
$this->request = $this->getMock('\phpbb\request\request');
$this->user = new \phpbb\user('\phpbb\datetime');
}
protected function get_acp_manager()
{
global $phpbb_root_path, $phpEx;
return new \vse\abbc3\core\acp_manager($this->db, $this->request, $this->user, $phpbb_root_path, $phpEx);
}
}
| gpl-2.0 |
Johannes-Larsson/Minaret-Builder | core/src/menuScene/MenuScene.java | 1461 | package menuScene;
import gameScene.GameScene;
import ui.Button;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.larsson.johannes.minaretBuilder.framework.Game;
import com.larsson.johannes.minaretBuilder.framework.Scene;
import com.larsson.johannes.minaretBuilder.game.Assets;
import com.larsson.johannes.minaretBuilder.game.SceneManager;
public class MenuScene extends Scene {
private Button playButton, quitButton, aboutButton;
public MenuScene() {
super();
playButton = new Button(Assets.playButtonLight, Assets.playButtonDark, Game.UIWIDTH / 2 - 200, 1100, 400, 200);
quitButton = new Button(Assets.quitButtonLight, Assets.quitButtonDark, Game.UIWIDTH / 2 - 200, 600, 400, 200);
aboutButton = new Button(Assets.aboutButton, Assets.aboutButton, Game.UIWIDTH / 2 - 200, 850, 400, 200);
onResume();
}
public void onResume() {
Game.clearR = 3f / 255;
Game.clearG = 53f / 255;
Game.clearB = 56f / 255;
}
public void update() {
if (playButton.isPressed()) {
SceneManager.gameScene = new GameScene();
SceneManager.setScene(SceneManager.gameScene);
} else if (quitButton.isPressed()) {
Gdx.app.exit();
} else if (aboutButton.isPressed()) {
SceneManager.setScene(new AboutScene(this));
}
}
public void drawUi(SpriteBatch uiBatch) {
uiBatch.draw(Assets.menuBackground, 0, 0);
playButton.draw(uiBatch);
aboutButton.draw(uiBatch);
quitButton.draw(uiBatch);
}
}
| gpl-2.0 |
simian-lab/d3-playground | js/main.js | 4172 | var initialScreen = document.querySelector('.initial-screen');
var statsScreen = document.querySelector('.stats-screen');
var knowMoreButton = document.querySelector('.know-more');
var chartContainer = document.querySelector('.chart');
var doseInfo = document.querySelector('.dose-info');
var firstCicleButton = document.querySelector('.first-cicle');
var secondCicleButton = document.querySelector('.second-cicle');
var pie, path, arc, svg;
/*jshint multistr: true */
var tsvData = "apples oranges pears\n\
53245 200 200\n\
23245 100 50\n\
42245 600 1100";
var data = d3.tsv.parse(tsvData);
function change(value) {
pie.value(function(d) { return d[value]; }); // change the value function
path = path.data(pie); // compute the new angles
path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
}
function type(d) {
d.apples = +d.apples;
d.oranges = +d.oranges;
return d;
}
// Store the displayed angles in _current.
// Then, interpolate from _current to the new angles.
// During the transition, _current is updated in-place by d3.interpolate.
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function(t) {
return arc(i(t));
};
}
// D3 chart taken from http://jsbin.com/hegob/1/edit
function paintChart() {
var width = chartContainer.clientWidth,
height = chartContainer.clientHeight,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(colorbrewer.BuGn[3]);
pie = d3.layout.pie()
.value(function(d) { return d.apples; })
.sort(null);
arc = d3.svg.arc()
.innerRadius(radius - 100)
.outerRadius(radius - 20);
// Responsive behaviour taken from http://jsfiddle.net/BTfmH/12/
svg = d3.select(".chart").append("svg")
.attr("width", '100%')
.attr("height", '100%')
.attr('viewBox','0 0 ' + Math.min(width, height) + ' ' + Math.min(width, height))
.attr('preserveAspectRatio', 'xMinYMin')
.append("g")
.attr("transform", "translate(" + Math.min(width, height) / 2 + "," + Math.min(width, height) / 2 + ")");
path = svg.datum(data).selectAll("path")
.data(pie)
.enter().append("path")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc)
.each(function(d) { this._current = d; }); // store the initial angles
// show the chart
chartContainer.className = 'chart visible';
// Add button events
firstCicleButton.addEventListener('click', function(e) {
e.preventDefault();
doseInfo.className = 'dose-info invisible';
setTimeout(function(){
doseInfo.innerHTML = 'Despues de la primera dosis, se incrementa la movilidad de los pacientes en un <em>34.6%</em>.';
doseInfo.className = 'dose-info';
}, 500);
change('oranges');
});
secondCicleButton.addEventListener('click', function(e) {
e.preventDefault();
doseInfo.className = 'dose-info invisible';
setTimeout(function(){
doseInfo.innerHTML = 'Tras la segunda dosis hay una regresión completa de los síntomas en el <em>92.3%</em> de pacientes con condrosteositis nodular.';
doseInfo.className = 'dose-info';
}, 500);
change('pears');
});
// prevent further repaints
statsScreen.removeEventListener('transitionEnd', paintChart);
statsScreen.removeEventListener('webkitTransitionEnd', paintChart);
statsScreen.removeEventListener('oTransitionEnd', paintChart);
statsScreen.removeEventListener('MSTransitionEnd', paintChart);
}
document.onreadystatechange = function() {
if(document.readyState == 'complete') {
setTimeout(function(){
initialScreen.className = 'initial-screen visible';
}, 1000);
}
}
knowMoreButton.addEventListener('click', function(event) {
event.preventDefault();
initialScreen.className = 'initial-screen';
setTimeout(function(){
statsScreen.className = 'stats-screen visible';
statsScreen.addEventListener('transitionEnd', paintChart);
statsScreen.addEventListener('webkitTransitionEnd', paintChart);
statsScreen.addEventListener('oTransitionEnd', paintChart);
statsScreen.addEventListener('MSTransitionEnd', paintChart);
}, 700);
});
| gpl-2.0 |
ArrozAlba/SASv2 | default/app/controllers/principal_controller.php | 494 | <?php
/**
* Dailyscript - Web | App | Media
*
* Descripcion: Controlador principal (reemplaza al index_controller)
*
* @category
* @package Controllers
* @author Iván D. Meléndez (ivan.melendez@dailycript.com.co)
* @copyright Copyright (c) 2013 Dailyscript Team (http://www.dailyscript.com.co)
*/
class PrincipalController extends AppController {
public $page_title = 'Sistema Autogestionado de Salud';
public function index() {
}
}
| gpl-2.0 |
m-stein/genode_hdl_env | os/src/lib/dde_kit/thread.cc | 6345 | /*
* \brief Thread facility
* \author Christian Helmuth
* \date 2008-10-20
*
*/
/*
* Copyright (C) 2008-2012 Genode Labs GmbH
*
* This file is part of the Genode OS framework, which is distributed
* under the terms of the GNU General Public License version 2.
*/
#include <base/env.h>
#include <base/sleep.h>
#include <base/lock.h>
#include <base/printf.h>
extern "C" {
#include <dde_kit/thread.h>
#include <dde_kit/timer.h>
}
#include "thread.h"
using namespace Genode;
/***********+**************
** Thread info database **
**************************/
class Thread_info_database : public Avl_tree<Dde_kit::Thread_info>
{
private:
Lock _lock;
public:
Dde_kit::Thread_info *lookup(Thread_base *thread_base)
{
Lock::Guard lock_guard(_lock);
if (!first()) throw Dde_kit::Thread_info::Not_found();
return first()->lookup(thread_base);
}
void insert(Dde_kit::Thread_info *info)
{
Lock::Guard lock_guard(_lock);
Avl_tree<Dde_kit::Thread_info>::insert(info);
}
void remove(Dde_kit::Thread_info *info)
{
Lock::Guard lock_guard(_lock);
Avl_tree<Dde_kit::Thread_info>::remove(info);
}
};
static Thread_info_database *threads()
{
static Thread_info_database _threads;
return &_threads;
}
/********************************
** Generic thread information **
********************************/
unsigned Dde_kit::Thread_info::_id_counter = 0x1000;
bool Dde_kit::Thread_info::higher(Thread_info *info)
{
return (info->_thread_base >= _thread_base);
}
Dde_kit::Thread_info *Dde_kit::Thread_info::lookup(Thread_base *thread_base)
{
Dde_kit::Thread_info *info = this;
do {
if (thread_base == info->_thread_base) return info;
if (thread_base < info->_thread_base)
info = info->child(LEFT);
else
info = info->child(RIGHT);
} while (info);
/* thread not in AVL tree */
throw Not_found();
}
Dde_kit::Thread_info::Thread_info(Thread_base *thread_base, const char *name)
: _thread_base(thread_base), _name(name), _id(_id_counter++)
{ }
Dde_kit::Thread_info::~Thread_info()
{ }
/********************
** DDE Kit thread **
********************/
static Dde_kit::Thread_info *adopt_thread(Thread_base *thread, const char *name)
{
Dde_kit::Thread_info *info = 0;
try {
info = new (env()->heap()) Dde_kit::Thread_info(thread, name);
threads()->insert(info);
} catch (...) {
PERR("thread adoption failed");
return 0;
}
return info;
}
struct dde_kit_thread : public Dde_kit::Thread_info
{
/**
* Dummy constructor
*
* This constructor is never executed because we only use pointers to
* 'dde_kit_thread'. Even though, this constructor is never used, gcc-3.4
* (e.g., used for OKL4v2) would report an error if it did not exist.
*/
dde_kit_thread() : Dde_kit::Thread_info(0, 0) { }
};
class _Thread : public Dde_kit::Thread
{
private:
void (*_thread_fn)(void *);
void *_thread_arg;
Dde_kit::Thread_info *_thread_info;
public:
_Thread(const char *name, void (*thread_fn)(void *), void *thread_arg)
:
Dde_kit::Thread(name),
_thread_fn(thread_fn), _thread_arg(thread_arg),
_thread_info(adopt_thread(this, name))
{ start(); }
void entry() { _thread_fn(_thread_arg); }
Dde_kit::Thread_info *thread_info() { return _thread_info; }
};
extern "C" struct dde_kit_thread *dde_kit_thread_create(void (*fun)(void *),
void *arg, const char *name)
{
_Thread *thread;
try {
thread = new (env()->heap()) _Thread(name, fun, arg);
} catch (...) {
PERR("thread creation failed");
return 0;
}
return static_cast<struct dde_kit_thread *>(thread->thread_info());
}
extern "C" struct dde_kit_thread *dde_kit_thread_adopt_myself(const char *name)
{
try {
return static_cast<dde_kit_thread *>(adopt_thread(Thread_base::myself(), name));
} catch (...) {
PERR("thread adoption failed");
return 0;
}
}
extern "C" struct dde_kit_thread *dde_kit_thread_myself()
{
try {
return static_cast<struct dde_kit_thread *>
(threads()->lookup(Thread_base::myself()));
} catch (...) {
return 0;
}
}
extern "C" void * dde_kit_thread_get_data(struct dde_kit_thread *thread) {
return static_cast<Dde_kit::Thread_info *>(thread)->data(); }
extern "C" void * dde_kit_thread_get_my_data(void)
{
try {
return (threads()->lookup(Thread_base::myself()))->data();
} catch (...) {
PERR("current thread not in database");
return 0;
}
}
extern "C" void dde_kit_thread_set_data(struct dde_kit_thread *thread, void *data) {
reinterpret_cast<Dde_kit::Thread_info *>(thread)->data(data); }
extern "C" void dde_kit_thread_set_my_data(void *data)
{
try {
(threads()->lookup(Thread_base::myself()))->data(data);
} catch (...) {
PERR("current thread not in database");
}
}
extern "C" void dde_kit_thread_exit(void)
{
PERR("not implemented yet");
sleep_forever();
}
extern "C" const char *dde_kit_thread_get_name(struct dde_kit_thread *thread) {
return reinterpret_cast<Dde_kit::Thread_info *>(thread)->name(); }
extern "C" int dde_kit_thread_get_id(struct dde_kit_thread *thread) {
return reinterpret_cast<Dde_kit::Thread_info *>(thread)->id(); }
extern "C" void dde_kit_thread_schedule(void)
{
/* FIXME */
}
/*********************
** Sleep interface **
*********************/
static void _wake_up_msleep(void *lock)
{
reinterpret_cast<Lock *>(lock)->unlock();
}
extern "C" void dde_kit_thread_msleep(unsigned long msecs)
{
/*
* This simple msleep() registers a timer that fires after 'msecs' and
* blocks on 'lock'. The registered timer handler just unlocks 'lock' and
* the sleeping thread unblocks.
*/
Lock *lock;
struct dde_kit_timer *timer;
unsigned long timeout = jiffies + (msecs * DDE_KIT_HZ) / 1000;
lock = new (env()->heap()) Lock(Lock::LOCKED);
timer = dde_kit_timer_add(_wake_up_msleep, lock, timeout);
lock->lock();
dde_kit_timer_del(timer);
destroy((env()->heap()), lock);
}
extern "C" void dde_kit_thread_usleep(unsigned long usecs)
{
unsigned long msecs = usecs / 1000;
if (msecs > 1)
dde_kit_thread_msleep(msecs);
else
dde_kit_thread_schedule();
}
extern "C" void dde_kit_thread_nsleep(unsigned long nsecs)
{
unsigned long msecs = nsecs / 1000000;
if (msecs > 1)
dde_kit_thread_msleep(msecs);
else
dde_kit_thread_schedule();
}
| gpl-2.0 |
wyona/yulup | src/branches/ANNOTATION_BRANCH/yulup/src/chrome/content/editor/editorparams.js | 10780 | /*
* ***** BEGIN LICENSE BLOCK *****
* Copyright 2006 Wyona AG Zurich
*
* This file is part of Yulup.
*
* Yulup 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.
*
* Yulup 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 Yulup; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* ***** END LICENSE BLOCK *****
*/
/**
* @author Andreas Wuest
*
*/
/**
* EditorParameters constructor. Instantiates a new object of
* type EditorParameters.
*
* @constructor
* @param {nsIURI} aURI the URI of the document to load into the new editor
* @param {String} aContentType the content type of the document
* @param {Array} aSchemas the schmes
* @param {Array} aStyles the stylesheets
* @param {Object} aStyleTemplate the style templates
* @param {Array} aWidgets the widgets
* @param {String} aTemplate a template action parameter string
* @return {EditorParameters}
*/
function EditorParameters(aURI, aContentType, aSchemas, aStyles, aStyleTemplate, aWidgets) {
/* DEBUG */ YulupDebug.ASSERT(aURI != null && aURI.spec != null);
/* DEBUG */ YulupDebug.ASSERT(aContentType != null);
this.uri = aURI;
this.contentType = aContentType;
this.schemas = aSchemas;
this.styles = aStyles;
this.styleTemplate = aStyleTemplate;
this.widgets = aWidgets;
this.templates = true;
}
EditorParameters.prototype = {
type : "EditorParameters",
uri : null,
contentType : null,
schemas : null,
styles : null,
styleTemplate: null,
widgets : null,
templates : null,
mergeIntrospectionParams: function (aIntrospectionObject) {
/* DEBUG */ dump("Yulup:editorparams.js:EditorParameters.mergeIntrospectionParams() invoked\n");
/* DEBUG */ YulupDebug.ASSERT(aIntrospectionObject != null);
// check if content types are compatible
if (aIntrospectionObject && aIntrospectionObject.fragments[0] && (this.contentType == aIntrospectionObject.fragments[0].mimeType)) {
if (aIntrospectionObject.fragments[0].schemas) {
this.__mergeSchemas(aIntrospectionObject.fragments[0].schemas);
}
if (aIntrospectionObject.fragments[0].styles) {
this.__mergeStyles(aIntrospectionObject.fragments[0].styles);
}
if (aIntrospectionObject.fragments[0].styleTemplate) {
this.__mergeStyleTemplate(aIntrospectionObject.fragments[0].styleTemplate);
}
if (aIntrospectionObject.fragments[0].widgets && this.templates) {
this.__mergeWidgets(aIntrospectionObject.fragments[0].widgets);
}
}
},
__mergeSchemas: function (aSchemas) {
/* DEBUG */ dump("Yulup:editorparams.js:EditorParameters.__mergeSchemas() invoked\n");
if (!this.schemas) {
this.schemas = aSchemas;
} else {
for (var i = 0; i < aSchemas.length; i++) {
this.schemas.push(aSchemas[i]);
}
}
},
__mergeStyles: function(aStyles) {
/* DEBUG */ dump("Yulup:editorparams.js:EditorParameters.__mergeStyles() invoked\n");
if (!this.styles) {
this.styles = aStyles;
} else {
for (var i = 0; i < aStyles.length; i++) {
this.styles.push(aStyles[i]);
}
}
},
__mergeStyleTemplate: function(aStyleTemplate) {
/* DEBUG */ dump("Yulup:editorparams.js:EditorParameters.__mergeStyleTemplate() invoked\n");
if (!this.styleTemplate) {
this.styleTemplate = aStyleTemplate;
}
},
__mergeWidgets: function(aWidgets) {
/* DEBUG */ dump("Yulup:editorparams.js:EditorParameters.__mergeWidgets() invoked\n");
if (!this.widgets) {
this.widgets = aWidgets;
} else {
for (var i = 0; i < aWidgets.length; i++) {
this.widgets.push(aWidgets[i]);
}
}
}
};
/**
* NeutronEditorParameters constructor. Instantiates a new object of
* type NeutronEditorParameters.
*
* @constructor
* @param {nsIURI} aURI the URI of the document to load into the new editor
* @param {Introspection} aIntrospectionObject the introspection object associated with the document to load
* @param {Integer} aFragment the fragment identifier of the document to load
* @param {String} aLoadStyle the Neutron load style, either "open" or "checkout"
* @return {NeutronEditorParameters}
*/
function NeutronEditorParameters(aURI, aIntrospectionObject, aFragment, aLoadStyle) {
/* DEBUG */ YulupDebug.ASSERT(aURI != null && aURI.spec != null);
/* DEBUG */ YulupDebug.ASSERT(aIntrospectionObject != null);
/* DEBUG */ YulupDebug.ASSERT(aFragment != null);
/* DEBUG */ YulupDebug.ASSERT(aLoadStyle != null);
EditorParameters.call(this, aURI, aIntrospectionObject.queryFragmentMIMEType(aFragment), aIntrospectionObject.queryFragmentSchemas(aFragment), aIntrospectionObject.queryFragmentStyles(aFragment), aIntrospectionObject.queryFragmentStyleTemplate(aFragment), aIntrospectionObject.queryFragmentWidgets(aFragment));
this.openURI = aIntrospectionObject.queryFragmentOpenURI(aFragment);
this.openMethod = aIntrospectionObject.queryFragmentOpenMethod(aFragment);
this.saveURI = aIntrospectionObject.queryFragmentSaveURI(aFragment);
this.saveMethod = aIntrospectionObject.queryFragmentSaveMethod(aFragment);
this.checkoutURI = aIntrospectionObject.queryFragmentCheckoutURI(aFragment);
this.checkoutMethod = aIntrospectionObject.queryFragmentCheckoutMethod(aFragment);
this.checkinURI = aIntrospectionObject.queryFragmentCheckinURI(aFragment);
this.checkinMethod = aIntrospectionObject.queryFragmentCheckinMethod(aFragment);
this.screenName = aIntrospectionObject.queryFragmentName(aFragment);
this.loadStyle = aLoadStyle;
this.navigation = aIntrospectionObject.queryNavigation();
this.templates = aIntrospectionObject.queryTemplateWidgets(aFragment);
}
NeutronEditorParameters.prototype = {
__proto__: EditorParameters.prototype,
type : "NeutronEditorParameters",
openURI : null,
openMethod : null,
saveURI : null,
saveMethod : null,
checkoutURI : null,
checkoutMethod: null,
checkinURI : null,
checkinMethod : null,
screenName : null,
loadStyle : null,
/**
* Substitute the editor parameters by the parameters
* contained in the given Neutron introspection object.
*
* Note that this method is intended for updating the
* editor parameters after a NAR load. The NAR must
* contain exactly one fragment (everything else would not
* make sense).
*
* @param {Introspection} aIntrospectionObject a Neutron introspection object
* @return {Undefined} does not have a return value
*/
substituteIntrospectionParams: function (aIntrospectionObject) {
/* DEBUG */ dump("Yulup:editorparams.js:NeutronEditorParameters.substituteIntrospectionParams() invoked\n");
/* DEBUG */ YulupDebug.ASSERT(aIntrospectionObject != null);
this.openURI = aIntrospectionObject.queryFragmentOpenURI(0);
this.openMethod = aIntrospectionObject.queryFragmentOpenMethod(0);
this.saveURI = aIntrospectionObject.queryFragmentSaveURI(0);
this.saveMethod = aIntrospectionObject.queryFragmentSaveMethod(0);
this.checkoutURI = aIntrospectionObject.queryFragmentCheckoutURI(0);
this.checkoutMethod = aIntrospectionObject.queryFragmentCheckoutMethod(0);
this.checkinURI = aIntrospectionObject.queryFragmentCheckinURI(0);
this.checkinMethod = aIntrospectionObject.queryFragmentCheckinMethod(0);
this.screenName = aIntrospectionObject.queryFragmentName(0);
this.schemas = aIntrospectionObject.queryFragmentSchemas(0);
this.styles = aIntrospectionObject.queryFragmentStyles(0);
this.styleTemplate = aIntrospectionObject.queryFragmentStyleTemplate(0);
this.widgets = aIntrospectionObject.queryFragmentWidgets(0);
this.contentType = aIntrospectionObject.queryFragmentMIMEType(0);
},
mergeIntrospectionParams: function (aIntrospectionObject) {
/* DEBUG */ dump("Yulup:editorparams.js:NeutronEditorParameters.mergeIntrospectionParams() invoked\n");
/* DEBUG */ YulupDebug.ASSERT(aIntrospectionObject != null);
EditorParameters.prototype.mergeIntrospectionParams.call(this, aIntrospectionObject);
}
};
/**
* AtomEditorParameters constructor. Instantiates a new object of
* type AtomEditorParameters.
*
* @constructor
* @param {nsIURI} aURI the URI of the document to load into the new editor
* @param {nsIURI} aFeedURI the feed URI the document belongs to
* @param {String} aContentType the content type of the document
* @param {String} aTemplate a template action parameter string
* @return {AtomEditorParameters}
*/
function AtomEditorParameters(aURI, aFeedURI, aContentType) {
/* DEBUG */ YulupDebug.ASSERT(aURI != null && aURI.spec != null);
/* DEBUG */ YulupDebug.ASSERT(aContentType != null);
EditorParameters.call(this, aURI, aContentType, null, null, null, null);
this.feedURI = aFeedURI;
}
AtomEditorParameters.prototype = {
__proto__: EditorParameters.prototype,
type : "AtomEditorParameters",
mergeIntrospectionParams: function (aIntrospectionObject) {
/* DEBUG */ dump("Yulup:editorparams.js:AtomEditorParameters.mergeIntrospectionParams() invoked\n");
/* DEBUG */ YulupDebug.ASSERT(aIntrospectionObject != null);
EditorParameters.prototype.mergeIntrospectionParams.call(this, aIntrospectionObject);
}
};
| gpl-2.0 |
jamal-fuma/epic-food-frequency | include/license/GPL_License.hpp | 792 | #ifndef EPIC_LICENSE_HPP
#define EPIC_LICENSE_HPP
#define GPL_LICENSE_TEXT ( \
"\nThis is free software: you can redistribute it and/or modify" \
"\nit under the terms of the GNU General Public License as published by" \
"\nthe Free Software Foundation, either version 2 of the License, or" \
"\n(at your option) any later version." \
"\n" \
"\nThis software is distributed in the hope that it will be useful," \
"\nbut WITHOUT ANY WARRANTY; without even the implied warranty of" \
"\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the" \
"\nGNU General Public License for more details." \
"\n" \
"\nYou should have received a copy of the GNU General Public License" \
"\nalong with this program. If not, see <http://www.gnu.org/licenses/>.")
#endif /* ndef EPIC_LICENSE_HPP */
| gpl-2.0 |
iconmaster5326/AetherCraft2 | src/main/java/com/iconmaster/aec2/gui/AetherCraftContainer.java | 2696 | package com.iconmaster.aec2.gui;
import com.iconmaster.aec2.te.AetherCraftTE;
import java.util.ArrayList;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
/**
*
* @author iconmaster
* @param <T>
*/
public abstract class AetherCraftContainer<T extends AetherCraftTE> extends Container {
public T te;
public int pinv_x = 8;
public int pinv_y = 84;
InventoryPlayer inv;
public ArrayList<SlotGrid> grids = new ArrayList<SlotGrid>();
public AetherCraftContainer(InventoryPlayer player, T tileEntity) {
this.te = tileEntity;
this.inv = player;
regenerateSlots();
}
public void regenerateSlots() {
grids.clear();
inventoryItemStacks.clear();
inventorySlots.clear();
this.registerGrids();
int i=0;
for (SlotGrid g : grids) {
i=g.addSlots(this,i);
}
this.bindPlayerInventory(inv);
}
public Slot addSlot(Slot slot) {
return this.addSlotToContainer(slot);
}
@Override
public boolean canInteractWith(EntityPlayer player) {
return this.te.isUseableByPlayer(player);
}
public void bindPlayerInventory(InventoryPlayer player) {
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 9; x++) {
addSlotToContainer(new Slot(player, x + y * 9 + 9, pinv_x + x * 18,
pinv_y + y * 18));
}
}
for (int x = 0; x < 9; x++) {
addSlotToContainer(new Slot(player, x, pinv_x + x * 18, pinv_y + (142-84)));
}
}
public int getPublicSlots() {
return te.inventory.length;
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int slot) {
ItemStack stack = null;
Slot slotObject = (Slot) inventorySlots.get(slot);
// null checks and checks if the item can be stacked (maxStackSize > 1)
if (slotObject != null && slotObject.getHasStack()) {
ItemStack stackInSlot = slotObject.getStack();
stack = stackInSlot.copy();
// merges the item into player inventory since its in the te
if (slot < getPublicSlots()) {
if (!this.mergeItemStack(stackInSlot, getPublicSlots(), getPublicSlots()+26, false)) {
return null;
}
}
// places it into the te is possible since its in the player
// inventory
else if (!this.mergeItemStack(stackInSlot, 0, getPublicSlots(), false)) {
return null;
}
if (stackInSlot.stackSize == 0) {
slotObject.putStack(null);
} else {
slotObject.onSlotChanged();
}
if (stackInSlot.stackSize == stack.stackSize) {
return null;
}
slotObject.onPickupFromSlot(player, stackInSlot);
}
return stack;
}
public abstract void registerGrids();
}
| gpl-2.0 |
websideas/London | wp-content/themes/london/framework/extensions/ReduxCore/framework.php | 185687 | <?php
/**
* Redux Framework 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
* any later version.
* Redux Framework is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Redux Framework. If not, see <http://www.gnu.org/licenses/>.
*
* @package Redux_Framework
* @subpackage Core
* @author Redux Framework Team
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Fix for the GT3 page builder: http://www.gt3themes.com/wordpress-gt3-page-builder-plugin/
/** @global string $pagenow */
if ( has_action( 'ecpt_field_options_' ) ) {
global $pagenow;
if ( $pagenow === 'admin.php' ) {
/** @noinspection PhpUndefinedCallbackInspection */
remove_action( 'admin_init', 'pb_admin_init' );
}
}
if ( ! class_exists( 'ReduxFrameworkInstances' ) ) {
// Instance Container
require_once( dirname( __FILE__ ) . '/inc/class.redux_instances.php' );
require_once( dirname( __FILE__ ) . '/inc/lib.redux_instances.php' );
}
if ( class_exists( 'ReduxFrameworkInstances' ) ) {
add_action( 'redux/init', 'ReduxFrameworkInstances::get_instance' );
}
// Don't duplicate me!
if ( ! class_exists( 'ReduxFramework' ) ) {
// Redux CDN class
require_once( dirname( __FILE__ ) . '/inc/class.redux_cdn.php' );
// Redux API class :)
require_once( dirname( __FILE__ ) . '/inc/class.redux_api.php' );
// General helper functions
require_once( dirname( __FILE__ ) . '/inc/class.redux_helpers.php' );
// General functions
require_once( dirname( __FILE__ ) . '/inc/class.redux_functions.php' );
require_once( dirname( __FILE__ ) . '/inc/class.p.php' );
require_once( dirname( __FILE__ ) . '/inc/class.redux_filesystem.php' );
// ThemeCheck checks
require_once( dirname( __FILE__ ) . '/inc/class.redux_themecheck.php' );
// Welcome
require_once( dirname( __FILE__ ) . '/inc/welcome/welcome.php' );
//require_once( dirname( __FILE__ ) . '/inc/class.redux_sass.php' );
/**
* Main ReduxFramework class
*
* @since 1.0.0
*/
class ReduxFramework {
// ATTENTION DEVS
// Please update the build number with each push, no matter how small.
// This will make for easier support when we ask users what version they are using.
public static $_version = '3.5.4.8';
public static $_dir;
public static $_url;
public static $_upload_dir;
public static $_upload_url;
public static $wp_content_url;
public static $base_wp_content_url;
public static $_is_plugin = true;
public static $_as_plugin = false;
public static function init() {
$dir = Redux_Helpers::cleanFilePath( dirname( __FILE__ ) );
// Windows-proof constants: replace backward by forward slashes. Thanks to: @peterbouwmeester
self::$_dir = trailingslashit( $dir );
self::$wp_content_url = trailingslashit( Redux_Helpers::cleanFilePath( ( is_ssl() ? str_replace( 'http://', 'https://', WP_CONTENT_URL ) : WP_CONTENT_URL ) ) );
// See if Redux is a plugin or not
if ( strpos( Redux_Helpers::cleanFilePath( __FILE__ ), Redux_Helpers::cleanFilePath( get_stylesheet_directory() ) ) !== false || strpos( Redux_Helpers::cleanFilePath( __FILE__ ), Redux_Helpers::cleanFilePath( get_template_directory_uri() ) ) !== false || strpos( Redux_Helpers::cleanFilePath( __FILE__ ), Redux_Helpers::cleanFilePath( WP_CONTENT_DIR . '/themes/' ) ) !== false ) {
self::$_is_plugin = false;
} else {
// Check if plugin is a symbolic link, see if it's a plugin. If embedded, we can't do a thing.
if ( strpos( self::$_dir, ABSPATH ) === false ) {
if ( ! function_exists( 'get_plugins' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$is_plugin = false;
foreach ( get_plugins() as $key => $value ) {
if ( is_plugin_active( $key ) && strpos( $key, 'redux-framework.php' ) !== false ) {
self::$_dir = trailingslashit( Redux_Helpers::cleanFilePath( WP_CONTENT_DIR . '/plugins/' . plugin_dir_path( $key ) . 'ReduxCore/' ) );
$is_plugin = true;
}
}
if ( ! $is_plugin ) {
self::$_is_plugin = false;
}
}
}
if ( self::$_is_plugin == true || self::$_as_plugin == true ) {
self::$_url = plugin_dir_url( __FILE__ );
} else {
if ( strpos( Redux_Helpers::cleanFilePath( __FILE__ ), Redux_Helpers::cleanFilePath( get_template_directory() ) ) !== false ) {
$relative_url = str_replace( Redux_Helpers::cleanFilePath( get_template_directory() ), '', self::$_dir );
self::$_url = trailingslashit( get_template_directory_uri() . $relative_url );
} else if ( strpos( Redux_Helpers::cleanFilePath( __FILE__ ), Redux_Helpers::cleanFilePath( get_stylesheet_directory() ) ) !== false ) {
$relative_url = str_replace( Redux_Helpers::cleanFilePath( get_stylesheet_directory() ), '', self::$_dir );
self::$_url = trailingslashit( get_stylesheet_directory_uri() . $relative_url );
} else {
$wp_content_dir = trailingslashit( Redux_Helpers::cleanFilePath( WP_CONTENT_DIR ) );
$wp_content_dir = trailingslashit( str_replace( '//', '/', $wp_content_dir ) );
$relative_url = str_replace( $wp_content_dir, '', self::$_dir );
self::$_url = trailingslashit( self::$wp_content_url . $relative_url );
}
}
self::$_url = apply_filters( "redux/_url", self::$_url );
self::$_dir = apply_filters( "redux/_dir", self::$_dir );
self::$_is_plugin = apply_filters( "redux/_is_plugin", self::$_is_plugin );
}
// ::init()
public $framework_url = 'http://www.reduxframework.com/';
public static $instance = null;
public $admin_notices = array();
public $page = '';
public $saved = false;
public $fields = array(); // Fields by type used in the panel
public $field_sections = array(); // Section id's by field type, then field ID
public $current_tab = ''; // Current section to display, cookies
public $extensions = array(); // Extensions by type used in the panel
public $sections = array(); // Sections and fields
public $errors = array(); // Errors
public $warnings = array(); // Warnings
public $options = array(); // Option values
public $options_defaults = null; // Option defaults
public $notices = array(); // Option defaults
public $compiler_fields = array(); // Fields that trigger the compiler hook
public $required = array(); // Information that needs to be localized
public $required_child = array(); // Information that needs to be localized
public $localize_data = array(); // Information that needs to be localized
public $fonts = array(); // Information that needs to be localized
public $folds = array(); // The itms that need to fold.
public $path = '';
public $changed_values = array(); // Values that have been changed on save. Orig values.
public $output = array(); // Fields with CSS output selectors
public $outputCSS = null; // CSS that get auto-appended to the header
public $compilerCSS = null; // CSS that get sent to the compiler hook
public $customizerCSS = null; // CSS that goes to the customizer
public $fieldsValues = array(); //all fields values in an id=>value array so we can check dependencies
public $fieldsHidden = array(); //all fields that didn't pass the dependency test and are hidden
public $toHide = array(); // Values to hide on page load
public $typography = null; //values to generate google font CSS
public $import_export = null;
public $no_panel = array(); // Fields that are not visible in the panel
private $show_hints = false;
public $hidden_perm_fields = array(); // Hidden fields specified by 'permissions' arg.
public $hidden_perm_sections = array(); // Hidden sections specified by 'permissions' arg.
public $typography_preview = array();
public $args = array();
public $filesystem = null;
public $font_groups = array();
public $lang = "";
public $dev_mode_forced = false;
/**
* Class Constructor. Defines the args for the theme options class
*
* @since 1.0.0
*
* @param array $sections Panel sections.
* @param array $args Class constructor arguments.
* @param array $extra_tabs Extra panel tabs. // REMOVE
*
* @return \ReduxFramework
*/
public function __construct( $sections = array(), $args = array(), $extra_tabs = array() ) {
// Disregard WP AJAX 'heartbeat'call. Why waste resources?
if ( isset ( $_POST ) && isset ( $_POST['action'] ) && $_POST['action'] == 'heartbeat' ) {
// Hook, for purists.
if ( ! has_action( 'redux/ajax/heartbeat' ) ) {
do_action( 'redux/ajax/heartbeat', $this );
}
// Buh bye!
return;
}
// Pass parent pointer to function helper.
Redux_Functions::$_parent = $this;
Redux_CDN::$_parent = $this;
// Set values
$this->set_default_args();
$this->args = wp_parse_args( $args, $this->args );
if ( empty ( $this->args['transient_time'] ) ) {
$this->args['transient_time'] = 60 * MINUTE_IN_SECONDS;
}
if ( empty ( $this->args['footer_credit'] ) ) {
$this->args['footer_credit'] = '<span id="footer-thankyou">' . sprintf( __( 'Options panel created using %1$s', 'redux-framework' ), '<a href="' . esc_url( $this->framework_url ) . '" target="_blank">' . __( 'Redux Framework', 'redux-framework' ) . '</a> v' . self::$_version ) . '</span>';
}
if ( empty ( $this->args['menu_title'] ) ) {
$this->args['menu_title'] = __( 'Options', 'redux-framework' );
}
if ( empty ( $this->args['page_title'] ) ) {
$this->args['page_title'] = __( 'Options', 'redux-framework' );
}
/**
* filter 'redux/args/{opt_name}'
*
* @param array $args ReduxFramework configuration
*/
$this->args = apply_filters( "redux/args/{$this->args['opt_name']}", $this->args );
/**
* filter 'redux/options/{opt_name}/args'
*
* @param array $args ReduxFramework configuration
*/
$this->args = apply_filters( "redux/options/{$this->args['opt_name']}/args", $this->args );
// Do not save the defaults if we're on a live preview!
if ( $GLOBALS['pagenow'] == "customize" && isset( $_GET['theme'] ) && ! empty( $_GET['theme'] ) ) {
$this->args['save_defaults'] = false;
}
if ( ! empty ( $this->args['opt_name'] ) ) {
/**
* SHIM SECTION
* Old variables and ways of doing things that need correcting. ;)
* */
// Variable name change
if ( ! empty ( $this->args['page_cap'] ) ) {
$this->args['page_permissions'] = $this->args['page_cap'];
unset ( $this->args['page_cap'] );
}
if ( ! empty ( $this->args['page_position'] ) ) {
$this->args['page_priority'] = $this->args['page_position'];
unset ( $this->args['page_position'] );
}
if ( ! empty ( $this->args['page_type'] ) ) {
$this->args['menu_type'] = $this->args['page_type'];
unset ( $this->args['page_type'] );
}
// Get rid of extra_tabs! Not needed.
if ( is_array( $extra_tabs ) && ! empty ( $extra_tabs ) ) {
foreach ( $extra_tabs as $tab ) {
array_push( $this->sections, $tab );
}
}
// Move to the first loop area!
/**
* filter 'redux-sections'
*
* @deprecated
*
* @param array $sections field option sections
*/
$this->sections = apply_filters( 'redux-sections', $sections ); // REMOVE LATER
/**
* filter 'redux-sections-{opt_name}'
*
* @deprecated
*
* @param array $sections field option sections
*/
$this->sections = apply_filters( "redux-sections-{$this->args['opt_name']}", $this->sections ); // REMOVE LATER
/**
* filter 'redux/options/{opt_name}/sections'
*
* @param array $sections field option sections
*/
$this->sections = apply_filters( "redux/options/{$this->args['opt_name']}/sections", $this->sections );
/**
* Construct hook
* action 'redux/construct'
*
* @param object $this ReduxFramework
*/
do_action( 'redux/construct', $this );
// Set the default values
$this->_default_cleanup();
// Internataionalization
$this->_internationalization();
$this->filesystem = new Redux_Filesystem ( $this );
//set redux upload folder
$this->set_redux_content();
// Register extra extensions
$this->_register_extensions();
// Grab database values
$this->get_options();
// Tracking
if ( true != Redux_Helpers::isTheme( __FILE__ ) || ( true == Redux_Helpers::isTheme( __FILE__ ) && ! $this->args['disable_tracking'] ) ) {
$this->_tracking();
}
// Options page
add_action( 'admin_menu', array( $this, '_options_page' ) );
// Add a network menu
if ( $this->args['database'] == "network" && $this->args['network_admin'] ) {
add_action( 'network_admin_menu', array( $this, '_options_page' ) );
}
// Admin Bar menu
add_action( 'admin_bar_menu', array(
$this,
'_admin_bar_menu'
), $this->args['admin_bar_priority'] );
// Register setting
add_action( 'admin_init', array( $this, '_register_settings' ) );
// Display admin notices in dev_mode
if ( true == $this->args['dev_mode'] ) {
if ( true == $this->args['update_notice'] ) {
add_action( 'admin_init', array( $this, '_update_check' ) );
}
}
// Display admin notices
add_action( 'admin_notices', array( $this, '_admin_notices' ), 99 );
// Check for dismissed admin notices.
add_action( 'admin_init', array( $this, '_dismiss_admin_notice' ), 9 );
// Enqueue the admin page CSS and JS
if ( isset ( $_GET['page'] ) && $_GET['page'] == $this->args['page_slug'] ) {
add_action( 'admin_enqueue_scripts', array( $this, '_enqueue' ), 1 );
}
// Output dynamic CSS
// Frontend: Maybe enqueue dynamic CSS and Google fonts
if ( empty ( $this->args['output_location'] ) || in_array( 'frontend', $this->args['output_location'] ) ) {
add_action( 'wp_head', array( &$this, '_output_css' ), 150 );
add_action( 'wp_enqueue_scripts', array( &$this, '_enqueue_output' ), 150 );
}
// Login page: Maybe enqueue dynamic CSS and Google fonts
if ( in_array( 'login', $this->args['output_location'] ) ) {
add_action( 'login_head', array( &$this, '_output_css' ), 150 );
add_action( 'login_enqueue_scripts', array( &$this, '_enqueue_output' ), 150 );
}
// Admin area: Maybe enqueue dynamic CSS and Google fonts
if ( in_array( 'admin', $this->args['output_location'] ) ) {
add_action( 'admin_head', array( &$this, '_output_css' ), 150 );
add_action( 'admin_enqueue_scripts', array( &$this, '_enqueue_output' ), 150 );
}
add_action( 'wp_print_scripts', array( $this, 'vc_fixes' ), 100 );
add_action( 'admin_enqueue_scripts', array( $this, 'vc_fixes' ), 100 );
if ( $this->args['database'] == "network" && $this->args['network_admin'] ) {
add_action( 'network_admin_edit_redux_' . $this->args['opt_name'], array(
$this,
'save_network_page'
), 10, 0 );
add_action( 'admin_bar_menu', array( $this, 'network_admin_bar' ), 999 );
}
// Ajax saving!!!
add_action( "wp_ajax_" . $this->args['opt_name'] . '_ajax_save', array( $this, "ajax_save" ) );
if ( $this->args['dev_mode'] == true || Redux_Helpers::isLocalHost() == true ) {
include_once 'core/dashboard.php';
if ( ! isset ( $GLOBALS['redux_notice_check'] ) ) {
include_once 'core/newsflash.php';
$params = array(
'dir_name' => 'notice',
'server_file' => 'http://www.reduxframework.com/' . 'wp-content/uploads/redux/redux_notice.json',
'interval' => 3,
'cookie_id' => 'redux_blast',
);
new reduxNewsflash( $this, $params );
$GLOBALS['redux_notice_check'] = 1;
}
}
}
/**
* Loaded hook
* action 'redux/loaded'
*
* @param object $this ReduxFramework
*/
do_action( 'redux/loaded', $this );
}
// __construct()
private function set_redux_content() {
$upload_dir = wp_upload_dir();
self::$_upload_dir = $upload_dir['basedir'] . '/redux/';
self::$_upload_url = $upload_dir['baseurl'] . '/redux/';
if ( ! is_dir( self::$_upload_dir ) ) {
$this->filesystem->execute( 'mkdir', self::$_upload_dir );
}
}
private function set_default_args() {
$this->args = array(
'opt_name' => '',
// Must be defined by theme/plugin
'google_api_key' => '',
// Must be defined to update the google fonts cache for the typography module
'google_update_weekly' => false,
// Set to keep your google fonts updated weekly
'last_tab' => '',
// force a specific tab to always show on reload
'menu_icon' => '',
// menu icon
'menu_title' => '',
// menu title/text
'page_title' => '',
// option page title
'page_slug' => '',
'page_permissions' => 'manage_options',
'menu_type' => 'menu',
// ('menu'|'submenu')
'page_parent' => 'themes.php',
// requires menu_type = 'submenu
'page_priority' => null,
'allow_sub_menu' => true,
// allow submenus to be added if menu_type == menu
'save_defaults' => true,
// Save defaults to the DB on it if empty
'footer_credit' => '',
'async_typography' => false,
'disable_google_fonts_link' => false,
'class' => '',
// Class that gets appended to all redux-containers
'admin_bar' => true,
'admin_bar_priority' => 999,
// Show the panel pages on the admin bar
'admin_bar_icon' => '',
// admin bar icon
'help_tabs' => array(),
'help_sidebar' => '',
'database' => '',
// possible: options, theme_mods, theme_mods_expanded, transient, network
'customizer' => false,
// setting to true forces get_theme_mod_expanded
'global_variable' => '',
// Changes global variable from $GLOBALS['YOUR_OPT_NAME'] to whatever you set here. false disables the global variable
'output' => true,
// Dynamically generate CSS
'compiler' => true,
// Initiate the compiler hook
'output_tag' => true,
// Print Output Tag
'output_location' => array( 'frontend' ),
// Where the dynamic CSS will be added. Can be any combination from: 'frontend', 'login', 'admin'
'transient_time' => '',
'default_show' => false,
// If true, it shows the default value
'default_mark' => '',
// What to print by the field's title if the value shown is default
'update_notice' => true,
// Recieve an update notice of new commits when in dev mode
'disable_save_warn' => false,
// Disable the save warn
'open_expanded' => false,
'hide_expand' => false,
// Start the panel fully expanded to start with
'network_admin' => false,
// Enable network admin when using network database mode
'network_sites' => true,
// Enable sites as well as admin when using network database mode
'hide_reset' => false,
'hints' => array(
'icon' => 'el el-question-sign',
'icon_position' => 'right',
'icon_color' => 'lightgray',
'icon_size' => 'normal',
'tip_style' => array(
'color' => 'light',
'shadow' => true,
'rounded' => false,
'style' => '',
),
'tip_position' => array(
'my' => 'top_left',
'at' => 'bottom_right',
),
'tip_effect' => array(
'show' => array(
'effect' => 'slide',
'duration' => '500',
'event' => 'mouseover',
),
'hide' => array(
'effect' => 'fade',
'duration' => '500',
'event' => 'click mouseleave',
),
),
),
'show_import_export' => true,
'show_options_object' => false,
'dev_mode' => true,
'disable_tracking' => false,
'templates_path' => '',
// Path to the templates file for various Redux elements
'ajax_save' => true,
// Disable the use of ajax saving for the panel
'cdn_check_time' => 1440,
'options_api' => true,
);
}
// Fix conflicts with Visual Composer.
public function vc_fixes() {
if ( redux_helpers::isFieldInUse( $this, 'ace_editor' ) ) {
wp_dequeue_script( 'wpb_ace' );
wp_deregister_script( 'wpb_ace' );
}
}
public function network_admin_bar( $wp_admin_bar ) {
$args = array(
'id' => $this->args['opt_name'] . '_network_admin',
'title' => $this->args['menu_title'],
'parent' => 'network-admin',
'href' => network_admin_url( 'settings.php' ) . '?page=' . $this->args['page_slug'],
'meta' => array( 'class' => 'redux-network-admin' )
);
$wp_admin_bar->add_node( $args );
}
public function save_network_page() {
$data = $this->_validate_options( $_POST[ $this->args['opt_name'] ] );
if ( ! empty ( $data ) ) {
$this->set_options( $data );
}
wp_redirect( add_query_arg( array(
'page' => $this->args['page_slug'],
'updated' => 'true'
), network_admin_url( 'settings.php' ) ) );
exit ();
}
public function _update_check() {
// Only one notice per instance please
if ( ! isset ( $GLOBALS['redux_update_check'] ) ) {
Redux_Functions::updateCheck( self::$_version );
$GLOBALS['redux_update_check'] = 1;
}
}
public function _admin_notices() {
Redux_Functions::adminNotices( $this->admin_notices );
}
public function _dismiss_admin_notice() {
Redux_Functions::dismissAdminNotice();
}
/**
* Load the plugin text domain for translation.
*
* @since 3.0.5
*/
private function _internationalization() {
/**
* Locale for text domain
* filter 'redux/textdomain/{opt_name}'
*
* @param string The locale of the blog or from the 'locale' hook
* @param string 'redux-framework' text domain
*/
$locale = apply_filters( "redux/textdomain/{$this->args['opt_name']}", get_locale(), 'redux-framework' );
if ( strpos( $locale, '_' ) === false ) {
if ( file_exists( self::$_dir . 'languages/' . strtolower( $locale ) . '_' . strtoupper( $locale ) . '.mo' ) ) {
$locale = strtolower( $locale ) . '_' . strtoupper( $locale );
}
}
load_textdomain( 'redux-framework', self::$_dir . 'languages/' . $locale . '.mo' );
}
// _internationalization()
/**
* @return ReduxFramework
*/
public function get_instance() {
//self::$_instance = $this;
return self::$instance;
}
// get_instance()
private function _tracking() {
require_once( dirname( __FILE__ ) . '/inc/tracking.php' );
$tracking = Redux_Tracking::get_instance();
$tracking->load( $this );
}
// _tracking()
/**
* ->_get_default(); This is used to return the default value if default_show is set
*
* @since 1.0.1
* @access public
*
* @param string $opt_name The option name to return
* @param mixed $default (null) The value to return if default not set
*
* @return mixed $default
*/
public function _get_default( $opt_name, $default = null ) {
if ( $this->args['default_show'] == true ) {
if ( empty ( $this->options_defaults ) ) {
$this->_default_values(); // fill cache
}
$default = array_key_exists( $opt_name, $this->options_defaults ) ? $this->options_defaults[ $opt_name ] : $default;
}
return $default;
}
// _get_default()
/**
* ->get(); This is used to return and option value from the options array
*
* @since 1.0.0
* @access public
*
* @param string $opt_name The option name to return
* @param mixed $default (null) The value to return if option not set
*
* @return mixed
*/
public function get( $opt_name, $default = null ) {
return ( ! empty ( $this->options[ $opt_name ] ) ) ? $this->options[ $opt_name ] : $this->_get_default( $opt_name, $default );
}
// get()
/**
* ->set(); This is used to set an arbitrary option in the options array
*
* @since 1.0.0
* @access public
*
* @param string $opt_name The name of the option being added
* @param mixed $value The value of the option being added
*
* @return void
*/
public function set( $opt_name = '', $value = '' ) {
if ( $opt_name != '' ) {
$this->options[ $opt_name ] = $value;
$this->set_options( $this->options );
}
}
// set()
/**
* Set a global variable by the global_variable argument
*
* @since 3.1.5
* @return bool (global was set)
*/
private function set_global_variable() {
if ( $this->args['global_variable'] ) {
$option_global = $this->args['global_variable'];
/**
* filter 'redux/options/{opt_name}/global_variable'
*
* @param array $value option value to set global_variable with
*/
$GLOBALS[ $this->args['global_variable'] ] = apply_filters( "redux/options/{$this->args['opt_name']}/global_variable", $this->options );
if ( isset ( $this->transients['last_save'] ) ) {
// Deprecated
$GLOBALS[ $this->args['global_variable'] ]['REDUX_last_saved'] = $this->transients['last_save'];
// Last save key
$GLOBALS[ $this->args['global_variable'] ]['REDUX_LAST_SAVE'] = $this->transients['last_save'];
}
if ( isset ( $this->transients['last_compiler'] ) ) {
// Deprecated
$GLOBALS[ $this->args['global_variable'] ]['REDUX_COMPILER'] = $this->transients['last_compiler'];
// Last compiler hook key
$GLOBALS[ $this->args['global_variable'] ]['REDUX_LAST_COMPILER'] = $this->transients['last_compiler'];
}
return true;
}
return false;
}
// set_global_variable()
/**
* ->set_options(); This is used to set an arbitrary option in the options array
*
* @since ReduxFramework 3.0.0
*
* @param mixed $value the value of the option being added
*/
public function set_options( $value = '' ) {
$this->transients['last_save'] = time();
if ( ! empty ( $value ) ) {
$this->options = $value;
if ( $this->args['database'] === 'transient' ) {
set_transient( $this->args['opt_name'] . '-transient', $value, $this->args['transient_time'] );
} else if ( $this->args['database'] === 'theme_mods' ) {
set_theme_mod( $this->args['opt_name'] . '-mods', $value );
} else if ( $this->args['database'] === 'theme_mods_expanded' ) {
foreach ( $value as $k => $v ) {
set_theme_mod( $k, $v );
}
} else if ( $this->args['database'] === 'network' ) {
// Strip those slashes!
$value = json_decode( stripslashes( json_encode( $value ) ), true );
update_site_option( $this->args['opt_name'], $value );
} else {
update_option( $this->args['opt_name'], $value );
}
// Store the changed values in the transient
if ( $value != $this->options ) {
foreach ( $value as $k => $v ) {
if ( ! isset ( $this->options[ $k ] ) ) {
$this->options[ $k ] = "";
} else if ( $v == $this->options[ $k ] ) {
unset ( $this->options[ $k ] );
}
}
$this->transients['changed_values'] = $this->options;
}
$this->options = $value;
// Set a global variable by the global_variable argument.
$this->set_global_variable();
// Saving the transient values
$this->set_transients();
//do_action( "redux-saved-{$this->args['opt_name']}", $value ); // REMOVE
//do_action( "redux/options/{$this->args['opt_name']}/saved", $value, $this->transients['changed_values'] );
}
}
// set_options()
/**
* ->get_options(); This is used to get options from the database
*
* @since ReduxFramework 3.0.0
*/
public function get_options() {
$defaults = false;
if ( ! empty ( $this->defaults ) ) {
$defaults = $this->defaults;
}
if ( $this->args['database'] === "transient" ) {
$result = get_transient( $this->args['opt_name'] . '-transient' );
} else if ( $this->args['database'] === "theme_mods" ) {
$result = get_theme_mod( $this->args['opt_name'] . '-mods' );
} else if ( $this->args['database'] === 'theme_mods_expanded' ) {
$result = get_theme_mods();
} else if ( $this->args['database'] === 'network' ) {
$result = get_site_option( $this->args['opt_name'], array() );
$result = json_decode( stripslashes( json_encode( $result ) ), true );
} else {
$result = get_option( $this->args['opt_name'], array() );
}
if ( empty ( $result ) && ! empty ( $defaults ) ) {
$results = $defaults;
$this->set_options( $results );
} else {
$this->options = $result;
}
/**
* action 'redux/options/{opt_name}/options'
*
* @param mixed $value option values
*/
// echo "redux/options/{$this->args['opt_name']}/options";
$this->options = apply_filters( "redux/options/{$this->args['opt_name']}/options", $this->options );
// Get transient values
$this->get_transients();
// Set a global variable by the global_variable argument.
$this->set_global_variable();
}
// get_options()
/**
* ->get_wordpress_date() - Get Wordpress specific data from the DB and return in a usable array
*
* @since ReduxFramework 3.0.0
*/
public function get_wordpress_data( $type = false, $args = array() ) {
$data = "";
//return $data;
/**
* filter 'redux/options/{opt_name}/wordpress_data/{type}/'
*
* @deprecated
*
* @param string $data
*/
$data = apply_filters( "redux/options/{$this->args['opt_name']}/wordpress_data/$type/", $data ); // REMOVE LATER
/**
* filter 'redux/options/{opt_name}/data/{type}'
*
* @param string $data
*/
$data = apply_filters( "redux/options/{$this->args['opt_name']}/data/$type", $data );
$argsKey = "";
foreach ( $args as $key => $value ) {
if ( ! is_array( $value ) ) {
$argsKey .= $value . "-";
} else {
$argsKey .= implode( "-", $value );
}
}
if ( empty ( $data ) && isset ( $this->wp_data[ $type . $argsKey ] ) ) {
$data = $this->wp_data[ $type . $argsKey ];
}
if ( empty ( $data ) && ! empty ( $type ) ) {
/**
* Use data from Wordpress to populate options array
* */
if ( ! empty ( $type ) && empty ( $data ) ) {
if ( empty ( $args ) ) {
$args = array();
}
$data = array();
$args = wp_parse_args( $args, array() );
if ( $type == "categories" || $type == "category" ) {
$cats = get_categories( $args );
if ( ! empty ( $cats ) ) {
foreach ( $cats as $cat ) {
$data[ $cat->term_id ] = $cat->name;
}
//foreach
} // If
} else if ( $type == "menus" || $type == "menu" ) {
$menus = wp_get_nav_menus( $args );
if ( ! empty ( $menus ) ) {
foreach ( $menus as $item ) {
$data[ $item->term_id ] = $item->name;
}
//foreach
}
//if
} else if ( $type == "pages" || $type == "page" ) {
if ( ! isset ( $args['posts_per_page'] ) ) {
$args['posts_per_page'] = 20;
}
$pages = get_pages( $args );
if ( ! empty ( $pages ) ) {
foreach ( $pages as $page ) {
$data[ $page->ID ] = $page->post_title;
}
//foreach
}
//if
} else if ( $type == "terms" || $type == "term" ) {
$taxonomies = $args['taxonomies'];
unset ( $args['taxonomies'] );
$terms = get_terms( $taxonomies, $args ); // this will get nothing
if ( ! empty ( $terms ) ) {
foreach ( $terms as $term ) {
$data[ $term->term_id ] = $term->name;
}
//foreach
} // If
} else if ( $type == "taxonomy" || $type == "taxonomies" ) {
$taxonomies = get_taxonomies( $args );
if ( ! empty ( $taxonomies ) ) {
foreach ( $taxonomies as $key => $taxonomy ) {
$data[ $key ] = $taxonomy;
}
//foreach
} // If
} else if ( $type == "posts" || $type == "post" ) {
$posts = get_posts( $args );
if ( ! empty ( $posts ) ) {
foreach ( $posts as $post ) {
$data[ $post->ID ] = $post->post_title;
}
//foreach
}
//if
} else if ( $type == "post_type" || $type == "post_types" ) {
global $wp_post_types;
$defaults = array(
'public' => true,
'exclude_from_search' => false,
);
$args = wp_parse_args( $args, $defaults );
$output = 'names';
$operator = 'and';
$post_types = get_post_types( $args, $output, $operator );
ksort( $post_types );
foreach ( $post_types as $name => $title ) {
if ( isset ( $wp_post_types[ $name ]->labels->menu_name ) ) {
$data[ $name ] = $wp_post_types[ $name ]->labels->menu_name;
} else {
$data[ $name ] = ucfirst( $name );
}
}
} else if ( $type == "tags" || $type == "tag" ) { // NOT WORKING!
$tags = get_tags( $args );
if ( ! empty ( $tags ) ) {
foreach ( $tags as $tag ) {
$data[ $tag->term_id ] = $tag->name;
}
//foreach
}
//if
} else if ( $type == "menu_location" || $type == "menu_locations" ) {
global $_wp_registered_nav_menus;
foreach ( $_wp_registered_nav_menus as $k => $v ) {
$data[ $k ] = $v;
}
} else if ( $type == "image_size" || $type == "image_sizes" ) {
global $_wp_additional_image_sizes;
foreach ( $_wp_additional_image_sizes as $size_name => $size_attrs ) {
$data[ $size_name ] = $size_name . ' - ' . $size_attrs['width'] . ' x ' . $size_attrs['height'];
}
} else if ( $type == "elusive-icons" || $type == "elusive-icon" || $type == "elusive" ||
$type == "font-icon" || $type == "font-icons" || $type == "icons"
) {
/**
* filter 'redux-font-icons'
*
* @deprecated
*
* @param array $font_icons array of elusive icon classes
*/
$font_icons = apply_filters( 'redux-font-icons', array() ); // REMOVE LATER
/**
* filter 'redux/font-icons'
*
* @deprecated
*
* @param array $font_icons array of elusive icon classes
*/
$font_icons = apply_filters( 'redux/font-icons', $font_icons );
/**
* filter 'redux/{opt_name}/field/font/icons'
*
* @deprecated
*
* @param array $font_icons array of elusive icon classes
*/
$font_icons = apply_filters( "redux/{$this->args['opt_name']}/field/font/icons", $font_icons );
foreach ( $font_icons as $k ) {
$data[ $k ] = $k;
}
} else if ( $type == "roles" ) {
/** @global WP_Roles $wp_roles */
global $wp_roles;
$data = $wp_roles->get_names();
} else if ( $type == "sidebars" || $type == "sidebar" ) {
/** @global array $wp_registered_sidebars */
global $wp_registered_sidebars;
foreach ( $wp_registered_sidebars as $key => $value ) {
$data[ $key ] = $value['name'];
}
} else if ( $type == "capabilities" ) {
/** @global WP_Roles $wp_roles */
global $wp_roles;
foreach ( $wp_roles->roles as $role ) {
foreach ( $role['capabilities'] as $key => $cap ) {
$data[ $key ] = ucwords( str_replace( '_', ' ', $key ) );
}
}
} else if ( $type == "callback" ) {
if ( ! is_array( $args ) ) {
$args = array( $args );
}
$data = call_user_func( $args[0] );
}
//if
}
//if
$this->wp_data[ $type . $argsKey ] = $data;
}
//if
return $data;
}
// get_wordpress_data()
/**
* ->show(); This is used to echo and option value from the options array
*
* @since 1.0.0
* @access public
*
* @param string $opt_name The name of the option being shown
* @param mixed $default The value to show if $opt_name isn't set
*
* @return void
*/
public function show( $opt_name, $default = '' ) {
$option = $this->get( $opt_name );
if ( ! is_array( $option ) && $option != '' ) {
echo $option;
} elseif ( $default != '' ) {
echo $this->_get_default( $opt_name, $default );
}
}
// show()
/**
* Get the default value for an option
*
* @since 3.3.6
* @access public
*
* @param string $key The option's ID
* @param string $array_key The key of the default's array
*
* @return mixed
*/
public function get_default_value( $key, $array_key = false ) {
if ( empty ( $this->options_defaults ) ) {
$this->options_defaults = $this->_default_values();
}
$defaults = $this->options_defaults;
$value = '';
if ( isset ( $defaults[ $key ] ) ) {
if ( $array_key !== false && isset ( $defaults[ $key ][ $array_key ] ) ) {
$value = $defaults[ $key ][ $array_key ];
} else {
$value = $defaults[ $key ];
}
}
return $value;
}
public function field_default_values($field) {
// Detect what field types are being used
if ( ! isset ( $this->fields[ $field['type'] ][ $field['id'] ] ) ) {
$this->fields[ $field['type'] ][ $field['id'] ] = 1;
} else {
$this->fields[ $field['type'] ] = array( $field['id'] => 1 );
}
if ( isset ( $field['default'] ) ) {
$this->options_defaults[ $field['id'] ] = $field['default'];
} elseif ( ( $field['type'] != "ace_editor" ) ) {
// Sorter data filter
if ( isset( $field['data'] ) && !empty( $field['data'] ) ) {
if (!isset($field['args'])) {
$field['args'] = array();
}
if ( is_array( $field['data'] ) && !empty( $field['data'] ) ) {
foreach ( $field['data'] as $key => $data ) {
if (!empty($data)) {
if ( ! isset ( $this->field['args'][ $key ] ) ) {
$field['args'][ $key ] = array();
}
$field['options'][ $key ] = $this->get_wordpress_data( $data, $field['args'][ $key ] );
}
}
} else {
$field['options'] = $this->get_wordpress_data( $field['data'], $field['args'] );
}
}
if ( $field['type'] == "sorter" && isset ( $field['data'] ) && ! empty ( $field['data'] ) && is_array( $field['data'] ) ) {
if ( ! isset ( $field['args'] ) ) {
$field['args'] = array();
}
foreach ( $field['data'] as $key => $data ) {
if ( ! isset ( $field['args'][ $key ] ) ) {
$field['args'][ $key ] = array();
}
$field['options'][ $key ] = $this->get_wordpress_data( $data, $field['args'][ $key ] );
}
}
if (isset ( $field['options'] )) {
if ( $field['type'] == "sortable" ) {
$this->options_defaults[ $field['id'] ] = array();
} elseif ( $field['type'] == "image_select" ) {
$this->options_defaults[ $field['id'] ] = '';
} elseif ( $field['type'] == "select" ) {
$this->options_defaults[ $field['id'] ] = '';
} else {
$this->options_defaults[ $field['id'] ] = $field['options'];
}
}
}
}
/**
* Get default options into an array suitable for the settings API
*
* @since 1.0.0
* @access public
* @return array $this->options_defaults
*/
public function _default_values() {
if ( ! is_null( $this->sections ) && is_null( $this->options_defaults ) ) {
// fill the cache
foreach ( $this->sections as $sk => $section ) {
if ( ! isset ( $section['id'] ) ) {
if ( ! is_numeric( $sk ) || ! isset ( $section['title'] ) ) {
$section['id'] = $sk;
} else {
$section['id'] = sanitize_title( $section['title'], $sk );
}
$this->sections[ $sk ] = $section;
}
if ( isset ( $section['fields'] ) ) {
foreach ( $section['fields'] as $k => $field ) {
if ( empty ( $field['id'] ) && empty ( $field['type'] ) ) {
continue;
}
if ( in_array( $field['type'], array( 'ace_editor' ) ) && isset ( $field['options'] ) ) {
$this->sections[ $sk ]['fields'][ $k ]['args'] = $field['options'];
unset ( $this->sections[ $sk ]['fields'][ $k ]['options'] );
}
if ( $field['type'] == "section" && isset ( $field['indent'] ) && $field['indent'] == "true" ) {
$field['class'] = isset ( $field['class'] ) ? $field['class'] : '';
$field['class'] .= "redux-section-indent-start";
$this->sections[ $sk ]['fields'][ $k ] = $field;
}
$this->field_default_values($field);
}
}
}
}
/**
* filter 'redux/options/{opt_name}/defaults'
*
* @param array $defaults option default values
*/
$this->transients['changed_values'] = isset ( $this->transients['changed_values'] ) ? $this->transients['changed_values'] : array();
$this->options_defaults = apply_filters( "redux/options/{$this->args['opt_name']}/defaults", $this->options_defaults, $this->transients['changed_values'] );
return $this->options_defaults;
}
/**
* Set default options on admin_init if option doesn't exist
*
* @since 1.0.0
* @access public
* @return void
*/
private function _default_cleanup() {
// Fix the global variable name
if ( $this->args['global_variable'] == "" && $this->args['global_variable'] !== false ) {
$this->args['global_variable'] = str_replace( '-', '_', $this->args['opt_name'] );
}
// Force dev_mode on WP_DEBUG = true and if it's a local server
if ( Redux_Helpers::isLocalHost() || ( Redux_Helpers::isWpDebug() ) ) {
if ( $this->args['dev_mode'] != true ) {
$this->args['update_notice'] = false;
}
$this->dev_mode_forced = true;
$this->args['dev_mode'] = true;
}
if ($this->args['dev_mode']) {
$this->args['show_options_object'] = true;
}
// Auto create the page_slug appropriately
if ( empty( $this->args['page_slug'] ) ) {
if ( ! empty( $this->args['display_name'] ) ) {
$this->args['page_slug'] = sanitize_html_class( $this->args['display_name'] );
} else if ( ! empty( $this->args['page_title'] ) ) {
$this->args['page_slug'] = sanitize_html_class( $this->args['page_title'] );
} else if ( ! empty( $this->args['menu_title'] ) ) {
$this->args['page_slug'] = sanitize_html_class( $this->args['menu_title'] );
} else {
$this->args['page_slug'] = str_replace( '-', '_', $this->args['opt_name'] );
}
}
}
/**
* Class Add Sub Menu Function, creates options submenu in Wordpress admin area.
*
* @since 3.1.9
* @access private
* @return void
*/
private function add_submenu( $page_parent, $page_title, $menu_title, $page_permissions, $page_slug ) {
global $submenu;
// Just in case. One never knows.
$page_parent = strtolower( $page_parent );
$test = array(
'index.php' => 'dashboard',
'edit.php' => 'posts',
'upload.php' => 'media',
'link-manager.php' => 'links',
'edit.php?post_type=page' => 'pages',
'edit-comments.php' => 'comments',
'themes.php' => 'theme',
'plugins.php' => 'plugins',
'users.php' => 'users',
'tools.php' => 'management',
'options-general.php' => 'options',
);
if ( isset ( $test[ $page_parent ] ) ) {
$function = 'add_' . $test[ $page_parent ] . '_page';
$this->page = $function (
$page_title, $menu_title, $page_permissions, $page_slug, array( $this, 'generate_panel' )
);
} else {
// Network settings and Post type menus. These do not have
// wrappers and need to be appened to using add_submenu_page.
// Okay, since we've left the post type menu appending
// as default, we need to validate it, so anything that
// isn't post_type=<post_type> doesn't get through and mess
// things up.
$addMenu = false;
if ( 'settings.php' != $page_parent ) {
// Establish the needle
$needle = '?post_type=';
// Check if it exists in the page_parent (how I miss instr)
$needlePos = strrpos( $page_parent, $needle );
// It's there, so...
if ( $needlePos > 0 ) {
// Get the post type.
$postType = substr( $page_parent, $needlePos + strlen( $needle ) );
// Ensure it exists.
if ( post_type_exists( $postType ) ) {
// Set flag to add the menu page
$addMenu = true;
}
// custom menu
} elseif ( isset ( $submenu[ $this->args['page_parent'] ] ) ) {
$addMenu = true;
} else {
global $menu;
foreach ( $menu as $menupriority => $menuitem ) {
$needle_menu_slug = isset ( $menuitem ) ? $menuitem[2] : false;
if ( $needle_menu_slug != false ) {
// check if the current needle menu equals page_parent
if ( strcasecmp( $needle_menu_slug, $page_parent ) == 0 ) {
// found an empty parent menu
$addMenu = true;
}
}
}
}
} else {
// The page_parent was settings.php, so set menu add
// flag to true.
$addMenu = true;
}
// Add the submenu if it's permitted.
if ( true == $addMenu ) {
$this->page = add_submenu_page(
$page_parent, $page_title, $menu_title, $page_permissions, $page_slug, array(
&$this,
'generate_panel'
)
);
}
}
}
/**
* Class Options Page Function, creates main options page.
*
* @since 1.0.0
* @access public
* @return void
*/
public function _options_page() {
if ( $this->args['menu_type'] == 'hidden' ) {
// No menu to add!
} else if ( $this->args['menu_type'] == 'submenu' ) {
$this->add_submenu(
$this->args['page_parent'], $this->args['page_title'], $this->args['menu_title'], $this->args['page_permissions'], $this->args['page_slug']
);
} else {
$this->page = add_menu_page(
$this->args['page_title'], $this->args['menu_title'], $this->args['page_permissions'], $this->args['page_slug'], array(
&$this,
'generate_panel'
), $this->args['menu_icon'], $this->args['page_priority']
);
if ( true === $this->args['allow_sub_menu'] ) {
if ( ! isset ( $section['type'] ) || $section['type'] != 'divide' ) {
foreach ( $this->sections as $k => $section ) {
$canBeSubSection = ( $k > 0 && ( ! isset ( $this->sections[ ( $k ) ]['type'] ) || $this->sections[ ( $k ) ]['type'] != "divide" ) ) ? true : false;
if ( ! isset ( $section['title'] ) || ( $canBeSubSection && ( isset ( $section['subsection'] ) && $section['subsection'] == true ) ) ) {
continue;
}
if ( isset ( $section['submenu'] ) && $section['submenu'] == false ) {
continue;
}
if ( isset ( $section['customizer_only'] ) && $section['customizer_only'] == true ) {
continue;
}
if ( isset ( $section['hidden'] ) && $section['hidden'] == true ) {
continue;
}
if ( isset( $section['permissions'] ) && ! current_user_can( $section['permissions'] ) ) {
continue;
}
add_submenu_page(
$this->args['page_slug'], $section['title'], $section['title'], $this->args['page_permissions'], $this->args['page_slug'] . '&tab=' . $k,
//create_function( '$a', "return null;" )
'__return_null'
);
}
// Remove parent submenu item instead of adding null item.
remove_submenu_page( $this->args['page_slug'], $this->args['page_slug'] );
}
}
}
add_action( "load-{$this->page}", array( &$this, '_load_page' ) );
}
// _options_page()
/**
* Add admin bar menu
*
* @since 3.1.5.16
* @access public
* @global $menu , $submenu, $wp_admin_bar
* @return void
*/
public function _admin_bar_menu() {
global $menu, $submenu, $wp_admin_bar;
$ct = wp_get_theme();
$theme_data = $ct;
if ( ! is_super_admin() || ! is_admin_bar_showing() || ! $this->args['admin_bar'] || $this->args['menu_type'] == 'hidden' ) {
return;
}
if ( $menu ) {
foreach ( $menu as $menu_item ) {
if ( isset ( $menu_item[2] ) && $menu_item[2] === $this->args["page_slug"] ) {
// Fetch the title
$title = empty ( $this->args['admin_bar_icon'] ) ? $menu_item[0] : '<span class="ab-icon ' . $this->args['admin_bar_icon'] . '"></span>' . $menu_item[0];
$nodeargs = array(
'id' => $menu_item[2],
'title' => $title,
'href' => admin_url( 'admin.php?page=' . $menu_item[2] ),
'meta' => array()
);
$wp_admin_bar->add_node( $nodeargs );
break;
}
}
if ( isset ( $submenu[ $this->args["page_slug"] ] ) && is_array( $submenu[ $this->args["page_slug"] ] ) ) {
foreach ( $submenu[ $this->args["page_slug"] ] as $index => $redux_options_submenu ) {
$subnodeargs = array(
'id' => $this->args["page_slug"] . '_' . $index,
'title' => $redux_options_submenu[0],
'parent' => $this->args["page_slug"],
'href' => admin_url( 'admin.php?page=' . $redux_options_submenu[2] ),
);
$wp_admin_bar->add_node( $subnodeargs );
}
}
// Let's deal with external links
if ( isset ( $this->args['admin_bar_links'] ) ) {
// Group for Main Root Menu (External Group)
$wp_admin_bar->add_node( array(
'id' => $this->args["page_slug"] . '-external',
'parent' => $this->args["page_slug"],
'group' => true,
'meta' => array( 'class' => 'ab-sub-secondary' )
) );
// Add Child Menus to External Group Menu
foreach ( $this->args['admin_bar_links'] as $link ) {
if ( ! isset ( $link['id'] ) ) {
$link['id'] = $this->args["page_slug"] . '-sub-' . sanitize_html_class( $link['title'] );
}
$externalnodeargs = array(
'id' => $link['id'],
'title' => $link['title'],
'parent' => $this->args["page_slug"] . '-external',
'href' => $link['href'],
'meta' => array( 'target' => '_blank' )
);
$wp_admin_bar->add_node( $externalnodeargs );
}
}
} else {
// Fetch the title
$title = empty ( $this->args['admin_bar_icon'] ) ? $this->args['menu_title'] : '<span class="ab-icon ' . $this->args['admin_bar_icon'] . '"></span>' . $this->args['menu_title'];
$nodeargs = array(
'id' => $this->args["page_slug"],
'title' => $title,
// $theme_data->get( 'Name' ) . " " . __( 'Options', 'redux-framework-demo' ),
'href' => admin_url( 'admin.php?page=' . $this->args["page_slug"] ),
'meta' => array()
);
$wp_admin_bar->add_node( $nodeargs );
}
}
// _admin_bar_menu()
/**
* Output dynamic CSS at bottom of HEAD
*
* @since 3.2.8
* @access public
* @return void
*/
public function _output_css() {
if ( $this->args['output'] == false && $this->args['compiler'] == false ) {
return;
}
if ( isset ( $this->no_output ) ) {
return;
}
if ( ! empty ( $this->outputCSS ) && ( $this->args['output_tag'] == true || ( isset ( $_POST['customized'] ) ) ) ) {
echo '<style type="text/css" title="dynamic-css" class="options-output">' . $this->outputCSS . '</style>';
}
}
/**
* Enqueue CSS and Google fonts for front end
*
* @since 1.0.0
* @access public
* @return void
*/
public function _enqueue_output() {
if ( $this->args['output'] == false && $this->args['compiler'] == false ) {
return;
}
/** @noinspection PhpUnusedLocalVariableInspection */
foreach ( $this->sections as $k => $section ) {
if ( isset ( $section['type'] ) && ( $section['type'] == 'divide' ) ) {
continue;
}
if ( isset ( $section['fields'] ) ) {
/** @noinspection PhpUnusedLocalVariableInspection */
foreach ( $section['fields'] as $fieldk => $field ) {
if ( isset ( $field['type'] ) && $field['type'] != "callback" ) {
$field_class = "ReduxFramework_{$field['type']}";
if ( ! class_exists( $field_class ) ) {
if ( ! isset ( $field['compiler'] ) ) {
$field['compiler'] = "";
}
/**
* Field class file
* filter 'redux/{opt_name}/field/class/{field.type}
*
* @param string field class file
* @param array $field field config data
*/
$class_file = apply_filters( "redux/{$this->args['opt_name']}/field/class/{$field['type']}", self::$_dir . "inc/fields/{$field['type']}/field_{$field['type']}.php", $field );
if ( $class_file && file_exists( $class_file ) && ! class_exists( $field_class ) ) {
/** @noinspection PhpIncludeInspection */
require_once( $class_file );
}
}
if ( ! empty ( $this->options[ $field['id'] ] ) && class_exists( $field_class ) && method_exists( $field_class, 'output' ) && $this->_can_output_css( $field ) ) {
$field = apply_filters( "redux/field/{$this->args['opt_name']}/output_css", $field );
if ( ! empty ( $field['output'] ) && ! is_array( $field['output'] ) ) {
$field['output'] = array( $field['output'] );
}
$value = isset ( $this->options[ $field['id'] ] ) ? $this->options[ $field['id'] ] : '';
$enqueue = new $field_class ( $field, $value, $this );
if ( ( ( isset ( $field['output'] ) && ! empty ( $field['output'] ) ) || ( isset ( $field['compiler'] ) && ! empty ( $field['compiler'] ) ) || $field['type'] == "typography" || $field['type'] == "icon_select" ) ) {
$enqueue->output();
}
}
}
}
}
}
// For use like in the customizer. Stops the output, but passes the CSS in the variable for the compiler
if ( isset ( $this->no_output ) ) {
return;
}
if ( ! empty ( $this->typography ) && ! empty ( $this->typography ) && filter_var( $this->args['output'], FILTER_VALIDATE_BOOLEAN ) ) {
$version = ! empty ( $this->transients['last_save'] ) ? $this->transients['last_save'] : '';
$typography = new ReduxFramework_typography ( null, null, $this );
if ( $this->args['async_typography'] && ! empty ( $this->typography ) ) {
$families = array();
foreach ( $this->typography as $key => $value ) {
$families[] = $key;
}
?>
<script>
/* You can add more configuration options to webfontloader by previously defining the WebFontConfig with your options */
if ( typeof WebFontConfig === "undefined" ) {
WebFontConfig = new Object();
}
WebFontConfig['google'] = {families: [<?php echo $typography->makeGoogleWebfontString ( $this->typography ) ?>]};
(function() {
var wf = document.createElement( 'script' );
wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1.5.3/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName( 'script' )[0];
s.parentNode.insertBefore( wf, s );
})();
</script>
<?php
} elseif ( ! $this->args['disable_google_fonts_link'] ) {
$protocol = ( ! empty ( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ) ? "https:" : "http:";
//echo '<link rel="stylesheet" id="options-google-fonts" title="" href="'.$protocol.$typography->makeGoogleWebfontLink( $this->typography ).'&v='.$version.'" type="text/css" media="all" />';
wp_register_style( 'redux-google-fonts-' . $this->args['opt_name'], $protocol . $typography->makeGoogleWebfontLink( $this->typography ), '', $version );
wp_enqueue_style( 'redux-google-fonts-' . $this->args['opt_name'] );
}
}
}
// _enqueue_output()
/**
* Enqueue CSS/JS for options page
*
* @since 1.0.0
* @access public
* @global $wp_styles
* @return void
*/
public function _enqueue() {
include_once( 'core/enqueue.php' );
$enqueue = new reduxCoreEnqueue ( $this );
$enqueue->init();
// if ($this->args['sass']['enabled']) {
// $ret = reduxSassCompiler::compile_sass($this);
//
// if ($ret == reduxSassCompiler::SASS_FILE_COMPILE || $ret == reduxSassCompiler::SASS_NO_COMPILE) {
// if (file_exists(ReduxFramework::$_upload_dir . $this->args['opt_name'] . '-redux.css')) {
// wp_enqueue_style(
// 'redux-fields-css',
// ReduxFramework::$_upload_url . $this->args['opt_name'] . '-redux.css',
// array(),
// $timestamp,
// 'all'
// );
// }
// }
// }
}
// _enqueue()
/**
* Show page help
*
* @since 1.0.0
* @access public
* @return void
*/
public function _load_page() {
// Do admin head action for this page
add_action( 'admin_head', array( &$this, 'admin_head' ) );
// Do admin footer text hook
add_filter( 'admin_footer_text', array( &$this, 'admin_footer_text' ) );
$screen = get_current_screen();
if ( is_array( $this->args['help_tabs'] ) ) {
foreach ( $this->args['help_tabs'] as $tab ) {
$screen->add_help_tab( $tab );
}
}
// If hint argument is set, display hint tab
if ( true == $this->show_hints ) {
global $current_user;
// Users enable/disable hint choice
$hint_status = get_user_meta( $current_user->ID, 'ignore_hints' ) ? get_user_meta( $current_user->ID, 'ignore_hints', true ) : 'true';
// current page parameters
$curPage = $_GET['page'];
$curTab = '0';
if ( isset ( $_GET['tab'] ) ) {
$curTab = $_GET['tab'];
}
// Default url values for enabling hints.
$dismiss = 'true';
$s = __( 'Enable', 'redux-framework' );
// Values for disabling hints.
if ( 'true' == $hint_status ) {
$dismiss = 'false';
$s = __( 'Disable', 'redux-framework' );
}
// Make URL
$url = '<a class="redux_hint_status" href="?dismiss=' . $dismiss . '&id=hints&page=' . $curPage . '&tab=' . $curTab . '">' . $s . ' hints</a>';
$event = __( 'moving the mouse over', 'redux-framework' );
if ( 'click' == $this->args['hints']['tip_effect']['show']['event'] ) {
$event = __( 'clicking', 'redux-framework' );
}
// Construct message
$msg = sprintf( __( 'Hints are tooltips that popup when %d the hint icon, offering addition information about the field in which they appear. They can be %d d by using the link below.', 'redux-framework' ), $event, strtolower( $s ) ) . '<br/><br/>' . $url;
// Construct hint tab
$tab = array(
'id' => 'redux-hint-tab',
'title' => __( 'Hints', 'redux-framework' ),
'content' => '<p>' . $msg . '</p>'
);
$screen->add_help_tab( $tab );
}
// Sidebar text
if ( $this->args['help_sidebar'] != '' ) {
// Specify users text from arguments
$screen->set_help_sidebar( $this->args['help_sidebar'] );
} else {
// If sidebar text is empty and hints are active, display text
// about hints.
if ( true == $this->show_hints ) {
$screen->set_help_sidebar( '<p><strong>Redux Framework</strong><br/><br/>Hint Tooltip Preferences</p>' );
}
}
/**
* action 'redux-load-page-{opt_name}'
*
* @deprecated
*
* @param object $screen WP_Screen
*/
do_action( "redux-load-page-{$this->args['opt_name']}", $screen ); // REMOVE
/**
* action 'redux/page/{opt_name}/load'
*
* @param object $screen WP_Screen
*/
do_action( "redux/page/{$this->args['opt_name']}/load", $screen );
}
// _load_page()
/**
* Do action redux-admin-head for options page
*
* @since 1.0.0
* @access public
* @return void
*/
public function admin_head() {
/**
* action 'redux-admin-head-{opt_name}'
*
* @deprecated
*
* @param object $this ReduxFramework
*/
do_action( "redux-admin-head-{$this->args['opt_name']}", $this ); // REMOVE
/**
* action 'redux/page/{opt_name}/header'
*
* @param object $this ReduxFramework
*/
do_action( "redux/page/{$this->args['opt_name']}/header", $this );
}
// admin_head()
/**
* Return footer text
*
* @since 2.0.0
* @access public
* @return string $this->args['footer_credit']
*/
public function admin_footer_text() {
return $this->args['footer_credit'];
}
// admin_footer_text()
/**
* Return default output string for use in panel
*
* @since 3.1.5
* @access public
* @return string default_output
*/
private function get_default_output_string( $field ) {
$default_output = "";
if ( ! isset ( $field['default'] ) ) {
$field['default'] = "";
}
if ( ! is_array( $field['default'] ) ) {
if ( ! empty ( $field['options'][ $field['default'] ] ) ) {
if ( ! empty ( $field['options'][ $field['default'] ]['alt'] ) ) {
$default_output .= $field['options'][ $field['default'] ]['alt'] . ', ';
} else {
// TODO: This serialize fix may not be the best solution. Look into it. PHP 5.4 error without serialize
if ( ! is_array( $field['options'][ $field['default'] ] ) ) {
$default_output .= $field['options'][ $field['default'] ] . ", ";
} else {
$default_output .= serialize( $field['options'][ $field['default'] ] ) . ", ";
}
}
} else if ( ! empty ( $field['options'][ $field['default'] ] ) ) {
$default_output .= $field['options'][ $field['default'] ] . ", ";
} else if ( ! empty ( $field['default'] ) ) {
if ( $field['type'] == 'switch' && isset ( $field['on'] ) && isset ( $field['off'] ) ) {
$default_output .= ( $field['default'] == 1 ? $field['on'] : $field['off'] ) . ', ';
} else {
$default_output .= $field['default'] . ', ';
}
}
} else {
foreach ( $field['default'] as $defaultk => $defaultv ) {
if ( ! empty ( $field['options'][ $defaultv ]['alt'] ) ) {
$default_output .= $field['options'][ $defaultv ]['alt'] . ', ';
} else if ( ! empty ( $field['options'][ $defaultv ] ) ) {
$default_output .= $field['options'][ $defaultv ] . ", ";
} else if ( ! empty ( $field['options'][ $defaultk ] ) ) {
$default_output .= $field['options'][ $defaultk ] . ", ";
} else if ( ! empty ( $defaultv ) ) {
$default_output .= $defaultv . ', ';
}
}
}
if ( ! empty ( $default_output ) ) {
$default_output = __( 'Default', 'redux-framework' ) . ": " . substr( $default_output, 0, - 2 );
}
if ( ! empty ( $default_output ) ) {
$default_output = '<span class="showDefaults">' . $default_output . '</span><br class="default_br" />';
}
return $default_output;
}
// get_default_output_string()
public function get_header_html( $field ) {
global $current_user;
// Set to empty string to avoid wanrings.
$hint = '';
$th = "";
if ( isset ( $field['title'] ) && isset ( $field['type'] ) && $field['type'] !== "info" && $field['type'] !== "section" ) {
$default_mark = ( ! empty ( $field['default'] ) && isset ( $this->options[ $field['id'] ] ) && $this->options[ $field['id'] ] == $field['default'] && ! empty ( $this->args['default_mark'] ) && isset ( $field['default'] ) ) ? $this->args['default_mark'] : '';
// If a hint is specified in the field, process it.
if ( isset ( $field['hint'] ) && ! '' == $field['hint'] ) {
// Set show_hints flag to true, so helptab will be displayed.
$this->show_hints = true;
// Get user pref for displaying hints.
$metaVal = get_user_meta( $current_user->ID, 'ignore_hints', true );
if ( 'true' == $metaVal || empty ( $metaVal ) ) {
// Set hand cursor for clickable hints
$pointer = '';
if ( isset ( $this->args['hints']['tip_effect']['show']['event'] ) && 'click' == $this->args['hints']['tip_effect']['show']['event'] ) {
$pointer = 'pointer';
}
$size = '16px';
if ( 'large' == $this->args['hints']['icon_size'] ) {
$size = '18px';
}
// In case docs are ignored.
$titleParam = isset ( $field['hint']['title'] ) ? $field['hint']['title'] : '';
$contentParam = isset ( $field['hint']['content'] ) ? $field['hint']['content'] : '';
$hint_color = isset ( $this->args['hints']['icon_color'] ) ? $this->args['hints']['icon_color'] : '#d3d3d3';
// Set hint html with appropriate position css
$hint = '<div class="redux-hint-qtip" style="float:' . $this->args['hints']['icon_position'] . '; font-size: ' . $size . '; color:' . $hint_color . '; cursor: ' . $pointer . ';" qtip-title="' . $titleParam . '" qtip-content="' . $contentParam . '"><i class="' . $this->args['hints']['icon'] . '"></i>  </div>';
}
}
if ( ! empty ( $field['title'] ) ) {
if ( 'left' == $this->args['hints']['icon_position'] ) {
$th = $hint . $field['title'] . $default_mark . "";
} else {
$th = $field['title'] . $default_mark . "" . $hint;
}
}
if ( isset ( $field['subtitle'] ) ) {
$th .= '<span class="description">' . $field['subtitle'] . '</span>';
}
}
if ( ! empty ( $th ) ) {
$th = '<div class="redux_field_th">' . $th . '</div>';
}
$filter_arr = array(
'editor',
'ace_editor',
'info',
'section',
'repeater',
'color_scheme',
'social_profiles',
'css_layout'
);
if ( $this->args['default_show'] == true && isset ( $field['default'] ) && isset ( $this->options[ $field['id'] ] ) && $this->options[ $field['id'] ] != $field['default'] && ! in_array( $field['type'], $filter_arr ) ) {
$th .= $this->get_default_output_string( $field );
}
return $th;
}
/**
* Register Option for use
*
* @since 1.0.0
* @access public
* @return void
*/
public function _register_settings() {
// TODO - REMOVE
// Not used by new sample-config, but in here for legacy builds
// This is bad and can break things. Hehe.
if ( ! function_exists( 'wp_get_current_user' ) ) {
include( ABSPATH . "wp-includes/pluggable.php" );
}
if ($this->args['options_api'] == true) {
register_setting( $this->args['opt_name'] . '_group', $this->args['opt_name'], array(
$this,
'_validate_options'
) );
}
if ( is_null( $this->sections ) ) {
return;
}
if ( empty( $this->options_defaults ) ) {
$this->options_defaults = $this->_default_values();
}
$runUpdate = false;
foreach ( $this->sections as $k => $section ) {
if ( isset ( $section['type'] ) && $section['type'] == 'divide' ) {
continue;
}
$display = true;
if ( isset ( $_GET['page'] ) && $_GET['page'] == $this->args['page_slug'] ) {
if ( isset ( $section['panel'] ) && $section['panel'] == false ) {
$display = false;
}
}
// DOVY! Replace $k with $section['id'] when ready
/**
* filter 'redux-section-{index}-modifier-{opt_name}'
*
* @param array $section section configuration
*/
$section = apply_filters( "redux-section-{$k}-modifier-{$this->args['opt_name']}", $section );
/**
* filter 'redux/options/{opt_name}/section/{section.id}'
*
* @param array $section section configuration
*/
if ( isset ( $section['id'] ) ) {
$section = apply_filters( "redux/options/{$this->args['opt_name']}/section/{$section['id']}", $section );
}
if ( empty ( $section ) ) {
unset ( $this->sections[ $k ] );
continue;
}
if ( ! isset ( $section['title'] ) ) {
$section['title'] = "";
}
$heading = isset ( $section['heading'] ) ? $section['heading'] : $section['title'];
if ( isset ( $section['permissions'] ) ) {
if ( ! current_user_can( $section['permissions'] ) ) {
$this->hidden_perm_sections[] = $section['title'];
foreach ( $section['fields'] as $num => $field_data ) {
$field_type = $field_data['type'];
if ( $field_type != 'section' || $field_type != 'divide' || $field_type != 'info' || $field_type != 'raw' ) {
$field_id = $field_data['id'];
$default = isset ( $this->options_defaults[ $field_id ] ) ? $this->options_defaults[ $field_id ] : '';
$data = isset ( $this->options[ $field_id ] ) ? $this->options[ $field_id ] : $default;
$this->hidden_perm_fields[ $field_id ] = $data;
}
}
continue;
}
}
if ( ! $display ) {
$this->no_panel_section[ $k ] = $section;
} else {
add_settings_section( $this->args['opt_name'] . $k . '_section', $heading, array(
&$this,
'_section_desc'
), $this->args['opt_name'] . $k . '_section_group' );
}
$sectionIndent = false;
if ( isset ( $section['fields'] ) ) {
foreach ( $section['fields'] as $fieldk => $field ) {
if ( ! isset ( $field['type'] ) ) {
continue; // You need a type!
}
if ( $field['type'] == "info" && isset( $field['raw_html'] ) && $field['raw_html'] == true ) {
$field['type'] = "raw";
$field['content'] = $field['desc'];
$field['desc'] = "";
$this->sections[ $k ]['fields'][ $fieldk ] = $field;
} else if ( $field['type'] == "info" ) {
if ( ! isset( $field['full_width'] ) ) {
$field['full_width'] = true;
$this->sections[ $k ]['fields'][ $fieldk ] = $field;
}
}
if ( $field['type'] == "raw" ) {
if ( isset( $field['align'] ) ) {
$field['full_width'] = $field['align'] ? false : true;
unset( $field['align'] );
} else if ( ! isset( $field['full_width'] ) ) {
$field['full_width'] = true;
}
$this->sections[ $k ]['fields'][ $fieldk ] = $field;
}
/**
* filter 'redux/options/{opt_name}/field/{field.id}'
*
* @param array $field field config
*/
$field = apply_filters( "redux/options/{$this->args['opt_name']}/field/{$field['id']}/register", $field );
$this->field_types[ $field['type'] ] = isset ( $this->field_types[ $field['type'] ] ) ? $this->field_types[ $field['type'] ] : array();
$this->field_sections[ $field['type'] ][ $field['id'] ] = $k;
$display = true;
if ( isset ( $_GET['page'] ) && $_GET['page'] == $this->args['page_slug'] ) {
if ( isset ( $field['panel'] ) && $field['panel'] == false ) {
$display = false;
}
}
if ( isset ( $field['customizer_only'] ) && $field['customizer_only'] == true ) {
$display = false;
}
if ( isset ( $field['permissions'] ) ) {
if ( ! current_user_can( $field['permissions'] ) ) {
$data = isset ( $this->options[ $field['id'] ] ) ? $this->options[ $field['id'] ] : $this->options_defaults[ $field['id'] ];
$this->hidden_perm_fields[ $field['id'] ] = $data;
continue;
}
}
if ( ! isset ( $field['id'] ) ) {
echo '<br /><h3>No field ID is set.</h3><pre>';
print_r( $field );
echo "</pre><br />";
continue;
}
if ( isset ( $field['type'] ) && $field['type'] == "section" ) {
if ( isset ( $field['indent'] ) && $field['indent'] == true ) {
$sectionIndent = true;
} else {
$sectionIndent = false;
}
}
if ( isset ( $field['type'] ) && $field['type'] == "info" && $sectionIndent ) {
$field['indent'] = $sectionIndent;
}
$th = $this->get_header_html( $field );
$field['name'] = $this->args['opt_name'] . '[' . $field['id'] . ']';
// Set the default value if present
$this->options_defaults[ $field['id'] ] = isset ( $this->options_defaults[ $field['id'] ] ) ? $this->options_defaults[ $field['id'] ] : '';
// Set the defaults to the value if not present
$doUpdate = false;
// Check fields for values in the default parameter
if ( ! isset ( $this->options[ $field['id'] ] ) && isset ( $field['default'] ) ) {
$this->options_defaults[ $field['id'] ] = $this->options[ $field['id'] ] = $field['default'];
$doUpdate = true;
// Check fields that hae no default value, but an options value with settings to
// be saved by default
} elseif ( ! isset ( $this->options[ $field['id'] ] ) && isset ( $field['options'] ) ) {
// If sorter field, check for options as save them as defaults
if ( $field['type'] == 'sorter' || $field['type'] == 'sortable' ) {
$this->options_defaults[ $field['id'] ] = $this->options[ $field['id'] ] = $field['options'];
$doUpdate = true;
}
}
// CORRECT URLS if media URLs are wrong, but attachment IDs are present.
if ( $field['type'] == "media" ) {
if ( isset ( $this->options[ $field['id'] ]['id'] ) && isset ( $this->options[ $field['id'] ]['url'] ) && ! empty ( $this->options[ $field['id'] ]['url'] ) && strpos( $this->options[ $field['id'] ]['url'], str_replace( 'http://', '', WP_CONTENT_URL ) ) === false ) {
$data = wp_get_attachment_url( $this->options[ $field['id'] ]['id'] );
if ( isset ( $data ) && ! empty ( $data ) ) {
$this->options[ $field['id'] ]['url'] = $data;
$data = wp_get_attachment_image_src( $this->options[ $field['id'] ]['id'], array(
150,
150
) );
$this->options[ $field['id'] ]['thumbnail'] = $data[0];
$doUpdate = true;
}
}
}
if ( $field['type'] == "background" ) {
if ( isset ( $this->options[ $field['id'] ]['media']['id'] ) && isset ( $this->options[ $field['id'] ]['background-image'] ) && ! empty ( $this->options[ $field['id'] ]['background-image'] ) && strpos( $this->options[ $field['id'] ]['background-image'], str_replace( 'http://', '', WP_CONTENT_URL ) ) === false ) {
$data = wp_get_attachment_url( $this->options[ $field['id'] ]['media']['id'] );
if ( isset ( $data ) && ! empty ( $data ) ) {
$this->options[ $field['id'] ]['background-image'] = $data;
$data = wp_get_attachment_image_src( $this->options[ $field['id'] ]['media']['id'], array(
150,
150
) );
$this->options[ $field['id'] ]['media']['thumbnail'] = $data[0];
$doUpdate = true;
}
}
}
if ( $field['type'] == "slides" ) {
if ( isset ( $this->options[ $field['id'] ] ) && is_array( $this->options[ $field['id'] ] ) && isset ( $this->options[ $field['id'] ][0]['attachment_id'] ) && isset ( $this->options[ $field['id'] ][0]['image'] ) && ! empty ( $this->options[ $field['id'] ][0]['image'] ) && strpos( $this->options[ $field['id'] ][0]['image'], str_replace( 'http://', '', WP_CONTENT_URL ) ) === false ) {
foreach ( $this->options[ $field['id'] ] as $key => $val ) {
$data = wp_get_attachment_url( $val['attachment_id'] );
if ( isset ( $data ) && ! empty ( $data ) ) {
$this->options[ $field['id'] ][ $key ]['image'] = $data;
$data = wp_get_attachment_image_src( $val['attachment_id'], array(
150,
150
) );
$this->options[ $field['id'] ][ $key ]['thumb'] = $data[0];
$doUpdate = true;
}
}
}
}
// END -> CORRECT URLS if media URLs are wrong, but attachment IDs are present.
if ( true == $doUpdate && ! isset ( $this->never_save_to_db ) ) {
if ( $this->args['save_defaults'] ) { // Only save that to the DB if allowed to
$runUpdate = true;
}
// elseif($this->saved != '' && $this->saved != false) {
// $runUpdate = true;
//}
}
if ( ! isset ( $field['class'] ) ) { // No errors please
$field['class'] = "";
}
$id = $field['id'];
/**
* filter 'redux-field-{field.id}modifier-{opt_name}'
*
* @deprecated
*
* @param array $field field config
*/
$field = apply_filters( "redux-field-{$field['id']}modifier-{$this->args['opt_name']}", $field ); // REMOVE LATER
/**
* filter 'redux/options/{opt_name}/field/{field.id}'
*
* @param array $field field config
*/
$field = apply_filters( "redux/options/{$this->args['opt_name']}/field/{$field['id']}", $field );
if ( empty ( $field ) || ! $field || $field == false ) {
unset ( $this->sections[ $k ]['fields'][ $fieldk ] );
continue;
}
if ( ! empty ( $this->folds[ $field['id'] ]['parent'] ) ) { // This has some fold items, hide it by default
$field['class'] .= " fold";
}
if ( ! empty ( $this->folds[ $field['id'] ]['children'] ) ) { // Sets the values you shoe fold children on
$field['class'] .= " foldParent";
}
if ( ! empty ( $field['compiler'] ) ) {
$field['class'] .= " compiler";
$this->compiler_fields[ $field['id'] ] = 1;
}
if ( isset ( $field['unit'] ) && ! isset ( $field['units'] ) ) {
$field['units'] = $field['unit'];
unset ( $field['unit'] );
}
$this->sections[ $k ]['fields'][ $fieldk ] = $field;
if ( isset ( $this->args['display_source'] ) ) {
$th .= '<div id="' . $field['id'] . '-settings" style="display:none;"><pre>' . var_export( $this->sections[ $k ]['fields'][ $fieldk ], true ) . '</pre></div>';
$th .= '<br /><a href="#TB_inline?width=600&height=800&inlineId=' . $field['id'] . '-settings" class="thickbox"><small>View Source</small></a>';
}
/**
* action 'redux/options/{opt_name}/field/field.type}/register'
*/
do_action( "redux/options/{$this->args['opt_name']}/field/{$field['type']}/register", $field );
$this->check_dependencies( $field );
if ( ! $display || isset ( $this->no_panel_section[ $k ] ) ) {
$this->no_panel[] = $field['id'];
} else {
if ( isset ( $field['hidden'] ) && $field['hidden'] ) {
$field['label_for'] = 'redux_hide_field';
}
if ($this->args['options_api'] == true) {
add_settings_field(
"{$fieldk}_field", $th, array(
&$this,
'_field_input'
), "{$this->args['opt_name']}{$k}_section_group", "{$this->args['opt_name']}{$k}_section", $field
);
} else {
$this->field_head[$field['id']] = $th;
}
}
}
}
}
/**
* action 'redux-register-settings-{opt_name}'
*
* @deprecated
*/
do_action( "redux-register-settings-{$this->args['opt_name']}" ); // REMOVE
/**
* action 'redux/options/{opt_name}/register'
*
* @param array option sections
*/
do_action( "redux/options/{$this->args['opt_name']}/register", $this->sections );
if ( $runUpdate && ! isset ( $this->never_save_to_db ) ) { // Always update the DB with new fields
$this->set_options( $this->options );
}
if ( isset ( $this->transients['run_compiler'] ) && $this->transients['run_compiler'] ) {
$this->no_output = true;
$this->_enqueue_output();
/**
* action 'redux-compiler-{opt_name}'
*
* @deprecated
*
* @param array options
* @param string CSS that get sent to the compiler hook
*/
do_action( "redux-compiler-{$this->args['opt_name']}", $this->options, $this->compilerCSS, $this->transients['changed_values'] ); // REMOVE
/**
* action 'redux/options/{opt_name}a'
*
* @param array options
* @param string CSS that get sent to the compiler hook
*/
do_action( "redux/options/{$this->args['opt_name']}/compiler", $this->options, $this->compilerCSS, $this->transients['changed_values'] );
/**
* action 'redux/options/{opt_name}/compiler/advanced'
*
* @param array options
* @param string CSS that get sent to the compiler hook, which sends the full Redux object
*/
do_action( "redux/options/{$this->args['opt_name']}/compiler/advanced", $this );
unset ( $this->transients['run_compiler'] );
$this->set_transients();
}
}
// _register_settings()
/**
* Register Extensions for use
*
* @since 3.0.0
* @access public
* @return void
*/
private function _register_extensions() {
$path = dirname( __FILE__ ) . '/inc/extensions/';
$folders = scandir( $path, 1 );
/**
* action 'redux/extensions/{opt_name}/before'
*
* @param object $this ReduxFramework
*/
do_action( "redux/extensions/{$this->args['opt_name']}/before", $this );
foreach ( $folders as $folder ) {
if ( $folder === '.' || $folder === '..' || ! is_dir( $path . $folder ) || substr( $folder, 0, 1 ) === '.' || substr( $folder, 0, 1 ) === '@' || substr( $folder, 0, 4 ) === '_vti' ) {
continue;
}
$extension_class = 'ReduxFramework_Extension_' . $folder;
/**
* filter 'redux-extensionclass-load'
*
* @deprecated
*
* @param string extension class file path
* @param string $extension_class extension class name
*/
$class_file = apply_filters( "redux-extensionclass-load", "$path/$folder/extension_{$folder}.php", $extension_class ); // REMOVE LATER
/**
* filter 'redux/extension/{opt_name}/{folder}'
*
* @param string extension class file path
* @param string $extension_class extension class name
*/
$class_file = apply_filters( "redux/extension/{$this->args['opt_name']}/$folder", "$path/$folder/extension_{$folder}.php", $class_file );
if ( $class_file ) {
if ( file_exists( $class_file ) ) {
require_once( $class_file );
}
$this->extensions[ $folder ] = new $extension_class ( $this );
}
}
/**
* action 'redux-register-extensions-{opt_name}'
*
* @deprecated
*
* @param object $this ReduxFramework
*/
do_action( "redux-register-extensions-{$this->args['opt_name']}", $this ); // REMOVE
/**
* action 'redux/extensions/{opt_name}'
*
* @param object $this ReduxFramework
*/
do_action( "redux/extensions/{$this->args['opt_name']}", $this );
}
private function get_transients() {
if ( ! isset ( $this->transients ) ) {
$this->transients = get_option( $this->args['opt_name'] . '-transients', array() );
$this->transients_check = $this->transients;
}
}
public function set_transients() {
if ( ! isset ( $this->transients ) || ! isset ( $this->transients_check ) || $this->transients != $this->transients_check ) {
update_option( $this->args['opt_name'] . '-transients', $this->transients );
$this->transients_check = $this->transients;
}
}
/**
* Validate the Options options before insertion
*
* @since 3.0.0
* @access public
*
* @param array $plugin_options The options array
*
* @return array|mixed|string|void
*/
public function _validate_options( $plugin_options ) {
//print_r($plugin_options);
// exit();
if ( isset ( $this->validation_ran ) ) {
return $plugin_options;
}
$this->validation_ran = 1;
// Save the values not in the panel
if ( isset ( $plugin_options['redux-no_panel'] ) ) {
$keys = explode( '|', $plugin_options['redux-no_panel'] );
foreach ( $keys as $key ) {
$plugin_options[ $key ] = $this->options[ $key ];
}
if ( isset ( $plugin_options['redux-no_panel'] ) ) {
unset ( $plugin_options['redux-no_panel'] );
}
}
if ( ! empty ( $this->hidden_perm_fields ) && is_array( $this->hidden_perm_fields ) ) {
foreach ( $this->hidden_perm_fields as $id => $data ) {
$plugin_options[ $id ] = $data;
}
}
if ( $plugin_options == $this->options ) {
return $plugin_options;
}
$time = time();
// Sets last saved time
$this->transients['last_save'] = $time;
// Import
if ( ( isset( $plugin_options['import_code'] ) && ! empty( $plugin_options['import_code'] ) ) || ( isset( $plugin_options['import_link'] ) && ! empty( $plugin_options['import_link'] ) ) ) {
$this->transients['last_save_mode'] = "import"; // Last save mode
$this->transients['last_compiler'] = $time;
$this->transients['last_import'] = $time;
$this->transients['run_compiler'] = 1;
if ( $plugin_options['import_code'] != '' ) {
$import = $plugin_options['import_code'];
} elseif ( $plugin_options['import_link'] != '' ) {
$import = wp_remote_retrieve_body( wp_remote_get( $plugin_options['import_link'] ) );
}
if ( ! empty ( $import ) ) {
$imported_options = json_decode( $import, true );
}
if ( ! empty ( $imported_options ) && is_array( $imported_options ) && isset ( $imported_options['redux-backup'] ) && $imported_options['redux-backup'] == '1' ) {
$this->transients['changed_values'] = array();
foreach ( $plugin_options as $key => $value ) {
if ( isset ( $imported_options[ $key ] ) && $imported_options[ $key ] != $value ) {
$this->transients['changed_values'][ $key ] = $value;
$plugin_options[ $key ] = $value;
}
}
/**
* action 'redux/options/{opt_name}/import'
*
* @param &array [&$plugin_options, redux_options]
*/
do_action_ref_array( "redux/options/{$this->args['opt_name']}/import", array(
&$plugin_options,
$imported_options,
$this->transients['changed_values']
) );
setcookie( 'redux_current_tab', '', 1, '/', $time + 1000, "/" );
$_COOKIE['redux_current_tab'] = 1;
unset ( $plugin_options['defaults'], $plugin_options['compiler'], $plugin_options['import'], $plugin_options['import_code'] );
if ( $this->args['database'] == 'transient' || $this->args['database'] == 'theme_mods' || $this->args['database'] == 'theme_mods_expanded' || $this->args['database'] == 'network' ) {
$this->set_options( $plugin_options );
return;
}
$plugin_options = wp_parse_args( $imported_options, $plugin_options );
$this->set_transients(); // Update the transients
return $plugin_options;
}
}
// Reset all to defaults
if ( ! empty ( $plugin_options['defaults'] ) ) {
if ( empty ( $this->options_defaults ) ) {
$this->options_defaults = $this->_default_values();
}
/**
* apply_filters 'redux/validate/{opt_name}/defaults'
*
* @param &array [ $this->options_defaults, $plugin_options]
*/
$plugin_options = apply_filters( "redux/validate/{$this->args['opt_name']}/defaults", $this->options_defaults );
// Section reset
//setcookie('redux-compiler-' . $this->args['opt_name'], 1, time() + 3000, '/');
$this->transients['changed_values'] = array();
if ( empty ( $this->options ) ) {
$this->options = $this->options_defaults;
}
foreach ( $this->options as $key => $value ) {
if ( isset ( $plugin_options[ $key ] ) && $value != $plugin_options[ $key ] ) {
$this->transients['changed_values'][ $key ] = $value;
}
}
$this->transients['run_compiler'] = 1;
$this->transients['last_save_mode'] = "defaults"; // Last save mode
//setcookie('redux-compiler-' . $this->args['opt_name'], 1, time() + 1000, "/");
//setcookie("redux-saved-{$this->args['opt_name']}", 'defaults', time() + 1000, "/");
$this->set_transients(); // Update the transients
return $plugin_options;
}
// Section reset to defaults
if ( ! empty ( $plugin_options['defaults-section'] ) ) {
if ( isset ( $plugin_options['redux-section'] ) && isset ( $this->sections[ $plugin_options['redux-section'] ]['fields'] ) ) {
/**
* apply_filters 'redux/validate/{opt_name}/defaults_section'
*
* @param &array [ $this->options_defaults, $plugin_options]
*/
foreach ( $this->sections[ $plugin_options['redux-section'] ]['fields'] as $field ) {
if ( isset ( $this->options_defaults[ $field['id'] ] ) ) {
$plugin_options[ $field['id'] ] = $this->options_defaults[ $field['id'] ];
} else {
$plugin_options[ $field['id'] ] = "";
}
if ( isset ( $field['compiler'] ) ) {
$compiler = true;
}
}
$plugin_options = apply_filters( "redux/validate/{$this->args['opt_name']}/defaults_section", $plugin_options );
}
$this->transients['changed_values'] = array();
foreach ( $this->options as $key => $value ) {
if ( isset ( $plugin_options[ $key ] ) && $value != $plugin_options[ $key ] ) {
$this->transients['changed_values'][ $key ] = $value;
}
}
if ( isset ( $compiler ) ) {
//$this->run_compiler = true;
//setcookie('redux-compiler-' . $this->args['opt_name'], 1, time()+1000, '/');
//$plugin_options['REDUX_COMPILER'] = time();
$this->transients['last_compiler'] = $time;
$this->transients['run_compiler'] = 1;
}
$this->transients['last_save_mode'] = "defaults_section"; // Last save mode
//setcookie("redux-saved-{$this->args['opt_name']}", 'defaults_section', time() + 1000, "/");
unset ( $plugin_options['defaults'], $plugin_options['defaults_section'], $plugin_options['import'], $plugin_options['import_code'], $plugin_options['import_link'], $plugin_options['compiler'], $plugin_options['redux-section'] );
$this->set_transients();
return $plugin_options;
}
// if ($this->transients['last_save_mode'] != 'remove') {
$this->transients['last_save_mode'] = "normal"; // Last save mode
// } else {
// $this->transients['last_save_mode'] = '';
// }
/**
* apply_filters 'redux/validate/{opt_name}/before_validation'
*
* @param &array [&$plugin_options, redux_options]
*/
$plugin_options = apply_filters( "redux/validate/{$this->args['opt_name']}/before_validation", $plugin_options, $this->options );
// Validate fields (if needed)
$plugin_options = $this->_validate_values( $plugin_options, $this->options, $this->sections );
if ( ! empty ( $this->errors ) || ! empty ( $this->warnings ) ) {
$this->transients['notices'] = array( 'errors' => $this->errors, 'warnings' => $this->warnings );
}
/**
* action 'redux-validate-{opt_name}'
*
* @deprecated
*
* @param &array [&$plugin_options, redux_options]
*/
do_action_ref_array( "redux-validate-{$this->args['opt_name']}", array(
&$plugin_options,
$this->options
) ); // REMOVE
if ( ! isset ( $this->transients['changed_values'] ) ) {
$this->transients['changed_values'] = array();
}
/**
* action 'redux/options/{opt_name}/validate'
*
* @param &array [&$plugin_options, redux_options]
*/
do_action_ref_array( "redux/options/{$this->args['opt_name']}/validate", array(
&$plugin_options,
$this->options,
$this->transients['changed_values']
) );
if ( ! empty ( $plugin_options['compiler'] ) ) {
unset ( $plugin_options['compiler'] );
$this->transients['last_compiler'] = $time;
$this->transients['run_compiler'] = 1;
}
$this->transients['changed_values'] = array(); // Changed values since last save
foreach ( $this->options as $key => $value ) {
if ( isset ( $plugin_options[ $key ] ) && $value != $plugin_options[ $key ] ) {
$this->transients['changed_values'][ $key ] = $value;
}
}
unset ( $plugin_options['defaults'], $plugin_options['defaults_section'], $plugin_options['import'], $plugin_options['import_code'], $plugin_options['import_link'], $plugin_options['compiler'], $plugin_options['redux-section'] );
if ( $this->args['database'] == 'transient' || $this->args['database'] == 'theme_mods' || $this->args['database'] == 'theme_mods_expanded' ) {
$this->set_options( $plugin_options );
return;
}
if ( defined( 'WP_CACHE' ) && WP_CACHE && class_exists( 'W3_ObjectCache' ) && function_exists ( 'w3_instance' ) ) {
//echo "here";
$w3_inst = w3_instance('W3_ObjectCache');
$w3 = $w3_inst->instance();
$key = $w3->_get_cache_key( $this->args['opt_name'] . '-transients', 'transient' );
//echo $key;
$w3->delete( $key, 'transient', true );
//set_transient($this->args['opt_name'].'-transients', $this->transients);
//exit();
}
$this->set_transients( $this->transients );
return $plugin_options;
}
public function ajax_save() {
if ( ! wp_verify_nonce( $_REQUEST['nonce'], "redux_ajax_nonce" ) ) {
json_encode( array(
'status' => __( 'Invalid security credential, please reload the page and try again.', 'redux-framework' ),
'action' => 'reload'
) );
die();
}
$redux = ReduxFrameworkInstances::get_instance( $_POST['opt_name'] );
if ( ! empty ( $_POST['data'] ) && ! empty ( $redux->args['opt_name'] ) ) {
$values = array();
//if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
// $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
// while (list($key, $val) = each($process)) {
// foreach ($val as $k => $v) {
// unset($process[$key][$k]);
// if (is_array($v)) {
// $process[$key][stripslashes($k)] = $v;
// $process[] = &$process[$key][stripslashes($k)];
// } else {
// $process[$key][stripslashes($k)] = stripslashes($v);
// }
// }
// }
// unset($process);
//}
$_POST['data'] = stripslashes( $_POST['data'] );
parse_str( $_POST['data'], $values );
$values = $values[ $redux->args['opt_name'] ];
if ( function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc() ) {
$values = array_map( 'stripslashes_deep', $values );
}
//$beforeDeep = $values;
//// Ace editor hack for < PHP 5.4. Oy
//if ( isset( $this->fields['ace_editor'] ) ) {
// if ( function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc() ) {
// foreach ( $this->fields['ace_editor'] as $id => $v ) {
// if ( version_compare( phpversion(), '5.4', '<' ) ) {
// $values[ $id ] = stripslashes( $beforeDeep[ $id ] );
// } else {
// $values[ $id ] = $beforeDeep[ $id ];
// }
// }
// }
//}
if ( ! empty ( $values ) ) {
try {
if ( isset ( $redux->validation_ran ) ) {
unset ( $redux->validation_ran );
}
$redux->set_options( $redux->_validate_options( $values ) );
if ( ( isset ( $values['defaults'] ) && ! empty ( $values['defaults'] ) ) || ( isset ( $values['defaults-section'] ) && ! empty ( $values['defaults-section'] ) ) ) {
echo json_encode( array( 'status' => 'success', 'action' => 'reload' ) );
die ();
}
include_once( 'core/enqueue.php' );
$enqueue = new reduxCoreEnqueue ( $redux );
$enqueue->get_warnings_and_errors_array();
include_once( 'core/panel.php' );
$panel = new reduxCorePanel ( $redux );
ob_start();
$panel->notification_bar();
$notification_bar = ob_get_contents();
ob_end_clean();
$success = array(
'status' => 'success',
'options' => $redux->options,
'errors' => isset ( $redux->localize_data['errors'] ) ? $redux->localize_data['errors'] : null,
'warnings' => isset ( $redux->localize_data['warnings'] ) ? $redux->localize_data['warnings'] : null,
'notification_bar' => $notification_bar
);
echo json_encode( $success );
} catch ( Exception $e ) {
echo json_encode( array( 'status' => $e->getMessage() ) );
}
} else {
echo json_encode( array( 'status' => __( 'Your panel has no fields. Nothing to save.', 'redux-framework' ) ) );
}
}
if ( isset ( $this->transients['run_compiler'] ) && $this->transients['run_compiler'] ) {
$this->no_output = true;
$this->_enqueue_output();
/**
* action 'redux-compiler-{opt_name}'
*
* @deprecated
*
* @param array options
* @param string CSS that get sent to the compiler hook
*/
do_action( "redux-compiler-{$this->args['opt_name']}", $this->options, $this->compilerCSS, $this->transients['changed_values'] ); // REMOVE
/**
* action 'redux/options/{opt_name}/compiler'
*
* @param array options
* @param string CSS that get sent to the compiler hook
*/
do_action( "redux/options/{$this->args['opt_name']}/compiler", $this->options, $this->compilerCSS, $this->transients['changed_values'] );
/**
* action 'redux/options/{opt_name}/compiler/advanced'
*
* @param array options
* @param string CSS that get sent to the compiler hook, which sends the full Redux object
*/
do_action( "redux/options/{$this->args['opt_name']}/compiler/advanced", $this );
unset ( $this->transients['run_compiler'] );
$this->set_transients();
}
die ();
}
/**
* Validate values from options form (used in settings api validate function)
* calls the custom validation class for the field so authors can override with custom classes
*
* @since 1.0.0
* @access public
*
* @param array $plugin_options
* @param array $options
*
* @return array $plugin_options
*/
public function _validate_values( $plugin_options, $options, $sections ) {
foreach ( $sections as $k => $section ) {
if ( isset ( $section['fields'] ) ) {
foreach ( $section['fields'] as $fkey => $field ) {
if ( is_array( $field ) ) {
$field['section_id'] = $k;
}
if ( isset ( $field['type'] ) && ( $field['type'] == 'checkbox' || $field['type'] == 'checkbox_hide_below' || $field['type'] == 'checkbox_hide_all' ) ) {
if ( ! isset ( $plugin_options[ $field['id'] ] ) ) {
$plugin_options[ $field['id'] ] = 0;
}
}
// Default 'not_empty 'flag to false.
$isNotEmpty = false;
// Make sure 'validate' field is set.
if ( isset ( $field['validate'] ) ) {
// Make sure 'validate field' is set to 'not_empty' or 'email_not_empty'
if ( $field['validate'] == 'not_empty' || $field['validate'] == 'email_not_empty' || $field['validate'] == 'numeric_not_empty' ) {
// Set the flag.
$isNotEmpty = true;
}
}
// Check for empty id value
if ( ! isset ( $field['id'] ) || ! isset ( $plugin_options[ $field['id'] ] ) || ( isset ( $plugin_options[ $field['id'] ] ) && $plugin_options[ $field['id'] ] == '' ) ) {
// If we are looking for an empty value, in the case of 'not_empty'
// then we need to keep processing.
if ( ! $isNotEmpty ) {
// Empty id and not checking for 'not_empty. Bail out...
continue;
}
}
// Force validate of custom field types
if ( isset ( $field['type'] ) && ! isset ( $field['validate'] ) ) {
if ( $field['type'] == 'color' || $field['type'] == 'color_gradient' ) {
$field['validate'] = 'color';
} elseif ( $field['type'] == 'date' ) {
$field['validate'] = 'date';
}
}
if ( isset ( $field['validate'] ) ) {
$validate = 'Redux_Validation_' . $field['validate'];
if ( ! class_exists( $validate ) ) {
/**
* filter 'redux-validateclass-load'
*
* @deprecated
*
* @param string validation class file path
* @param string $validate validation class name
*/
$class_file = apply_filters( "redux-validateclass-load", self::$_dir . "inc/validation/{$field['validate']}/validation_{$field['validate']}.php", $validate ); // REMOVE LATER
/**
* filter 'redux/validate/{opt_name}/class/{field.validate}'
*
* @param string validation class file path
* @param string $class_file validation class file path
*/
$class_file = apply_filters( "redux/validate/{$this->args['opt_name']}/class/{$field['validate']}", self::$_dir . "inc/validation/{$field['validate']}/validation_{$field['validate']}.php", $class_file );
if ( $class_file ) {
if ( file_exists( $class_file ) ) {
require_once( $class_file );
}
}
}
if ( class_exists( $validate ) ) {
//!DOVY - DB saving stuff. Is this right?
if ( empty ( $options[ $field['id'] ] ) ) {
$options[ $field['id'] ] = '';
}
if ( isset ( $plugin_options[ $field['id'] ] ) && is_array( $plugin_options[ $field['id'] ] ) && ! empty ( $plugin_options[ $field['id'] ] ) ) {
foreach ( $plugin_options[ $field['id'] ] as $key => $value ) {
$before = $after = null;
if ( isset ( $plugin_options[ $field['id'] ][ $key ] ) && ( ! empty ( $plugin_options[ $field['id'] ][ $key ] ) || $plugin_options[ $field['id'] ][ $key ] == '0' ) ) {
if ( is_array( $plugin_options[ $field['id'] ][ $key ] ) ) {
$before = $plugin_options[ $field['id'] ][ $key ];
} else {
$before = trim( $plugin_options[ $field['id'] ][ $key ] );
}
}
if ( isset ( $options[ $field['id'] ][ $key ] ) && ( ! empty ( $plugin_options[ $field['id'] ][ $key ] ) || $plugin_options[ $field['id'] ][ $key ] == '0' ) ) {
$after = $options[ $field['id'] ][ $key ];
}
$validation = new $validate ( $this, $field, $before, $after );
if ( ! empty ( $validation->value ) || $validation->value == '0' ) {
$plugin_options[ $field['id'] ][ $key ] = $validation->value;
} else {
unset ( $plugin_options[ $field['id'] ][ $key ] );
}
if ( isset ( $validation->error ) ) {
$this->errors[] = $validation->error;
}
if ( isset ( $validation->warning ) ) {
$this->warnings[] = $validation->warning;
}
}
} else {
if ( is_array( $plugin_options[ $field['id'] ] ) ) {
$pofi = $plugin_options[ $field['id'] ];
} else {
$pofi = trim( $plugin_options[ $field['id'] ] );
}
$validation = new $validate ( $this, $field, $pofi, $options[ $field['id'] ] );
$plugin_options[ $field['id'] ] = $validation->value;
if ( isset ( $validation->error ) ) {
$this->errors[] = $validation->error;
}
if ( isset ( $validation->warning ) ) {
$this->warnings[] = $validation->warning;
}
}
continue;
}
}
if ( isset ( $field['validate_callback'] ) && ( is_callable( $field['validate_callback'] ) || ( is_string( $field['validate_callback'] ) && function_exists( $field['validate_callback'] ) ) ) ) {
$callback = $field['validate_callback'];
unset ( $field['validate_callback'] );
$callbackvalues = call_user_func( $callback, $field, $plugin_options[ $field['id'] ], $options[ $field['id'] ] );
$plugin_options[ $field['id'] ] = $callbackvalues['value'];
if ( isset ( $callbackvalues['error'] ) ) {
$this->errors[] = $callbackvalues['error'];
}
// TODO - This warning message is failing. Hmm.
if ( isset ( $callbackvalues['warning'] ) ) {
$this->warnings[] = $callbackvalues['warning'];
}
}
}
}
}
return $plugin_options;
}
/**
* Return Section Menu HTML
*
* @since 3.1.5
* @access public
* @return void
*/
public function section_menu( $k, $section, $suffix = "", $sections = array() ) {
$display = true;
$section['class'] = isset ( $section['class'] ) ? ' ' . $section['class'] : '';
if ( isset ( $_GET['page'] ) && $_GET['page'] == $this->args['page_slug'] ) {
if ( isset ( $section['panel'] ) && $section['panel'] == false ) {
$display = false;
}
}
if ( ! $display ) {
return "";
}
if ( empty ( $sections ) ) {
$sections = $this->sections;
}
$string = "";
if ( ( isset ( $this->args['icon_type'] ) && $this->args['icon_type'] == 'image' ) || ( isset ( $section['icon_type'] ) && $section['icon_type'] == 'image' ) ) {
//if( !empty( $this->args['icon_type'] ) && $this->args['icon_type'] == 'image' ) {
$icon = ( ! isset ( $section['icon'] ) ) ? '' : '<img class="image_icon_type" src="' . $section['icon'] . '" /> ';
} else {
if ( ! empty ( $section['icon_class'] ) ) {
$icon_class = ' ' . $section['icon_class'];
} elseif ( ! empty ( $this->args['default_icon_class'] ) ) {
$icon_class = ' ' . $this->args['default_icon_class'];
} else {
$icon_class = '';
}
$icon = ( ! isset ( $section['icon'] ) ) ? '<i class="el el-cog' . $icon_class . '"></i> ' : '<i class="' . $section['icon'] . $icon_class . '"></i> ';
}
if ( strpos( $icon, 'el-icon-' ) !== false ) {
$icon = str_replace( 'el-icon-', 'el el-', $icon );
}
$hide_section = '';
if ( isset ( $section['hidden'] ) ) {
$hide_section = ( $section['hidden'] == true ) ? ' hidden ' : '';
}
$canBeSubSection = ( $k > 0 && ( ! isset ( $sections[ ( $k ) ]['type'] ) || $sections[ ( $k ) ]['type'] != "divide" ) ) ? true : false;
if ( ! $canBeSubSection && isset ( $section['subsection'] ) && $section['subsection'] == true ) {
unset ( $section['subsection'] );
}
if ( isset ( $section['type'] ) && $section['type'] == "divide" ) {
$string .= '<li class="divide' . $section['class'] . '"> </li>';
} else if ( ! isset ( $section['subsection'] ) || $section['subsection'] != true ) {
// DOVY! REPLACE $k with $section['ID'] when used properly.
//$active = ( ( is_numeric($this->current_tab) && $this->current_tab == $k ) || ( !is_numeric($this->current_tab) && $this->current_tab === $k ) ) ? ' active' : '';
$subsections = ( isset ( $sections[ ( $k + 1 ) ] ) && isset ( $sections[ ( $k + 1 ) ]['subsection'] ) && $sections[ ( $k + 1 ) ]['subsection'] == true ) ? true : false;
$subsectionsClass = $subsections ? ' hasSubSections' : '';
$subsectionsClass .= ( ! isset ( $section['fields'] ) || empty ( $section['fields'] ) ) ? ' empty_section' : '';
$extra_icon = $subsections ? '<span class="extraIconSubsections"><i class="el el-chevron-down"> </i></span>' : '';
$string .= '<li id="' . $k . $suffix . '_section_group_li" class="redux-group-tab-link-li' . $hide_section . $section['class'] . $subsectionsClass . '">';
$string .= '<a href="javascript:void(0);" id="' . $k . $suffix . '_section_group_li_a" class="redux-group-tab-link-a" data-key="' . $k . '" data-rel="' . $k . $suffix . '">' . $extra_icon . $icon . '<span class="group_title">' . $section['title'] . '</span></a>';
$nextK = $k;
// Make sure you can make this a subsection
if ( $subsections ) {
$string .= '<ul id="' . $nextK . $suffix . '_section_group_li_subsections" class="subsection">';
$doLoop = true;
while ( $doLoop ) {
$nextK += 1;
$display = true;
if ( isset ( $_GET['page'] ) && $_GET['page'] == $this->args['page_slug'] ) {
if ( isset ( $sections[ $nextK ]['panel'] ) && $sections[ $nextK ]['panel'] == false ) {
$display = false;
}
}
if ( count( $sections ) < $nextK || ! isset ( $sections[ $nextK ] ) || ! isset ( $sections[ $nextK ]['subsection'] ) || $sections[ $nextK ]['subsection'] != true ) {
$doLoop = false;
} else {
if ( ! $display ) {
continue;
}
$hide_sub = '';
if ( isset ( $sections[ $nextK ]['hidden'] ) ) {
$hide_sub = ( $sections[ $nextK ]['hidden'] == true ) ? ' hidden ' : '';
}
if ( ( isset ( $this->args['icon_type'] ) && $this->args['icon_type'] == 'image' ) || ( isset ( $sections[ $nextK ]['icon_type'] ) && $sections[ $nextK ]['icon_type'] == 'image' ) ) {
//if( !empty( $this->args['icon_type'] ) && $this->args['icon_type'] == 'image' ) {
$icon = ( ! isset ( $sections[ $nextK ]['icon'] ) ) ? '' : '<img class="image_icon_type" src="' . $sections[ $nextK ]['icon'] . '" /> ';
} else {
if ( ! empty ( $sections[ $nextK ]['icon_class'] ) ) {
$icon_class = ' ' . $sections[ $nextK ]['icon_class'];
} elseif ( ! empty ( $this->args['default_icon_class'] ) ) {
$icon_class = ' ' . $this->args['default_icon_class'];
} else {
$icon_class = '';
}
$icon = ( ! isset ( $sections[ $nextK ]['icon'] ) ) ? '' : '<i class="' . $sections[ $nextK ]['icon'] . $icon_class . '"></i> ';
}
if ( strpos( $icon, 'el-icon-' ) !== false ) {
$icon = str_replace( 'el-icon-', 'el el-', $icon );
}
$section[ $nextK ]['class'] = isset ( $section[ $nextK ]['class'] ) ? $section[ $nextK ]['class'] : '';
$string .= '<li id="' . $nextK . $suffix . '_section_group_li" class="redux-group-tab-link-li ' . $hide_sub . $section[ $nextK ]['class'] . ( $icon ? ' hasIcon' : '' ) . '">';
$string .= '<a href="javascript:void(0);" id="' . $nextK . $suffix . '_section_group_li_a" class="redux-group-tab-link-a" data-key="' . $nextK . '" data-rel="' . $nextK . $suffix . '">' . $icon . '<span class="group_title">' . $sections[ $nextK ]['title'] . '</span></a>';
$string .= '</li>';
}
}
$string .= '</ul>';
}
$string .= '</li>';
}
return $string;
}
// section_menu()
/**
* HTML OUTPUT.
*
* @since 1.0.0
* @access public
* @return void
*/
public function generate_panel() {
include_once( 'core/panel.php' );
$panel = new reduxCorePanel ( $this );
$panel->init();
$this->set_transients();
}
/**
* Section HTML OUTPUT.
*
* @since 1.0.0
* @access public
*
* @param array $section
*
* @return void
*/
public function _section_desc( $section ) {
$id = trim( rtrim( $section['id'], '_section' ), $this->args['opt_name'] );
if ( isset ( $this->sections[ $id ]['desc'] ) && ! empty ( $this->sections[ $id ]['desc'] ) ) {
echo '<div class="redux-section-desc">' . $this->sections[ $id ]['desc'] . '</div>';
}
}
/**
* Field HTML OUTPUT.
* Gets option from options array, then calls the specific field type class - allows extending by other devs
*
* @since 1.0.0
*
* @param array $field
* @param string $v
*
* @return void
*/
public function _field_input( $field, $v = null ) {
if ( isset ( $field['callback'] ) && ( is_callable( $field['callback'] ) || ( is_string( $field['callback'] ) && function_exists( $field['callback'] ) ) ) ) {
$value = ( isset ( $this->options[ $field['id'] ] ) ) ? $this->options[ $field['id'] ] : '';
/**
* action 'redux-before-field-{opt_name}'
*
* @deprecated
*
* @param array $field field data
* @param string $value field.id
*/
do_action( "redux-before-field-{$this->args['opt_name']}", $field, $value ); // REMOVE
/**
* action 'redux/field/{opt_name}/{field.type}/callback/before'
*
* @param array $field field data
* @param string $value field.id
*/
do_action( "redux/field/{$this->args['opt_name']}/{$field['type']}/callback/before", $field, $value );
/**
* action 'redux/field/{opt_name}/callback/before'
*
* @param array $field field data
* @param string $value field.id
*/
do_action( "redux/field/{$this->args['opt_name']}/callback/before", $field, $value );
call_user_func( $field['callback'], $field, $value );
/**
* action 'redux-after-field-{opt_name}'
*
* @deprecated
*
* @param array $field field data
* @param string $value field.id
*/
do_action( "redux-after-field-{$this->args['opt_name']}", $field, $value ); // REMOVE
/**
* action 'redux/field/{opt_name}/{field.type}/callback/after'
*
* @param array $field field data
* @param string $value field.id
*/
do_action( "redux/field/{$this->args['opt_name']}/{$field['type']}/callback/after", $field, $value );
/**
* action 'redux/field/{opt_name}/callback/after'
*
* @param array $field field data
* @param string $value field.id
*/
do_action( "redux/field/{$this->args['opt_name']}/callback/after", $field, $value );
return;
}
if ( isset ( $field['type'] ) ) {
// If the field is set not to display in the panel
$display = true;
if ( isset ( $_GET['page'] ) && $_GET['page'] == $this->args['page_slug'] ) {
if ( isset ( $field['panel'] ) && $field['panel'] == false ) {
$display = false;
}
}
if ( ! $display ) {
return;
}
$field_class = "ReduxFramework_{$field['type']}";
if ( ! class_exists( $field_class ) ) {
// $class_file = apply_filters( 'redux/field/class/'.$field['type'], self::$_dir . 'inc/fields/' . $field['type'] . '/field_' . $field['type'] . '.php', $field ); // REMOVE
/**
* filter 'redux/{opt_name}/field/class/{field.type}'
*
* @param string field class file path
* @param array $field field data
*/
$class_file = apply_filters( "redux/{$this->args['opt_name']}/field/class/{$field['type']}", self::$_dir . "inc/fields/{$field['type']}/field_{$field['type']}.php", $field );
if ( $class_file ) {
if ( file_exists( $class_file ) ) {
require_once( $class_file );
}
}
}
if ( class_exists( $field_class ) ) {
$value = isset ( $this->options[ $field['id'] ] ) ? $this->options[ $field['id'] ] : '';
if ( $v !== null ) {
$value = $v;
}
/**
* action 'redux-before-field-{opt_name}'
*
* @deprecated
*
* @param array $field field data
* @param string $value field id
*/
do_action( "redux-before-field-{$this->args['opt_name']}", $field, $value ); // REMOVE
/**
* action 'redux/field/{opt_name}/{field.type}/render/before'
*
* @param array $field field data
* @param string $value field id
*/
do_action( "redux/field/{$this->args['opt_name']}/{$field['type']}/render/before", $field, $value );
/**
* action 'redux/field/{$this->args['opt_name']}/render/before'
*
* @param array $field field data
* @param string $value field id
*/
do_action( "redux/field/{$this->args['opt_name']}/render/before", $field, $value );
if ( ! isset ( $field['name_suffix'] ) ) {
$field['name_suffix'] = "";
}
$render = new $field_class ( $field, $value, $this );
ob_start();
$render->render();
/*
echo "<pre>";
print_r($value);
echo "</pre>";
*/
/**
* filter 'redux-field-{opt_name}'
*
* @deprecated
*
* @param string rendered field markup
* @param array $field field data
*/
$_render = apply_filters( "redux-field-{$this->args['opt_name']}", ob_get_contents(), $field ); // REMOVE
/**
* filter 'redux/field/{opt_name}/{field.type}/render/after'
*
* @param string rendered field markup
* @param array $field field data
*/
$_render = apply_filters( "redux/field/{$this->args['opt_name']}/{$field['type']}/render/after", $_render, $field );
/**
* filter 'redux/field/{opt_name}/render/after'
*
* @param string rendered field markup
* @param array $field field data
*/
$_render = apply_filters( "redux/field/{$this->args['opt_name']}/render/after", $_render, $field );
ob_end_clean();
//save the values into a unique array in case we need it for dependencies
$this->fieldsValues[ $field['id'] ] = ( isset ( $value['url'] ) && is_array( $value ) ) ? $value['url'] : $value;
//create default data und class string and checks the dependencies of an object
$class_string = '';
$data_string = '';
$this->check_dependencies( $field );
/**
* action 'redux/field/{opt_name}/{field.type}/fieldset/before/{opt_name}'
*
* @param array $field field data
* @param string $value field id
*/
do_action( "redux/field/{$this->args['opt_name']}/{$field['type']}/fieldset/before/{$this->args['opt_name']}", $field, $value );
/**
* action 'redux/field/{opt_name}/fieldset/before/{opt_name}'
*
* @param array $field field data
* @param string $value field id
*/
do_action( "redux/field/{$this->args['opt_name']}/fieldset/before/{$this->args['opt_name']}", $field, $value );
//if ( ! isset( $field['fields'] ) || empty( $field['fields'] ) ) {
$hidden = '';
if ( isset ( $field['hidden'] ) && $field['hidden'] ) {
$hidden = 'hidden ';
}
if ( isset( $field['full_width'] ) && $field['full_width'] == true ) {
$class_string .= "redux_remove_th";
}
echo '<fieldset id="' . $this->args['opt_name'] . '-' . $field['id'] . '" class="' . $hidden . 'redux-field-container redux-field redux-field-init redux-container-' . $field['type'] . ' ' . $class_string . '" data-id="' . $field['id'] . '" ' . $data_string . ' data-type="' . $field['type'] . '">';
//}
echo $_render;
if ( ! empty ( $field['desc'] ) ) {
$field['description'] = $field['desc'];
}
echo ( isset ( $field['description'] ) && $field['type'] != "info" && $field['type'] !== "section" && ! empty ( $field['description'] ) ) ? '<div class="description field-desc">' . $field['description'] . '</div>' : '';
//if ( ! isset( $field['fields'] ) || empty( $field['fields'] ) ) {
echo '</fieldset>';
//}
/**
* action 'redux-after-field-{opt_name}'
*
* @deprecated
*
* @param array $field field data
* @param string $value field id
*/
do_action( "redux-after-field-{$this->args['opt_name']}", $field, $value ); // REMOVE
/**
* action 'redux/field/{opt_name}/{field.type}/fieldset/after/{opt_name}'
*
* @param array $field field data
* @param string $value field id
*/
do_action( "redux/field/{$this->args['opt_name']}/{$field['type']}/fieldset/after/{$this->args['opt_name']}", $field, $value );
/**
* action 'redux/field/{opt_name}/fieldset/after/{opt_name}'
*
* @param array $field field data
* @param string $value field id
*/
do_action( "redux/field/{$this->args['opt_name']}/fieldset/after/{$this->args['opt_name']}", $field, $value );
}
}
}
// _field_input()
/**
* Can Output CSS
* Check if a field meets its requirements before outputting to CSS
*
* @param $field
*
* @return bool
*/
public function _can_output_css( $field ) {
$return = true;
$field = apply_filters( "redux/field/{$this->args['opt_name']}/_can_output_css", $field );
if ( isset ( $field['force_output'] ) && $field['force_output'] == true ) {
return $return;
}
if ( ! empty ( $field['required'] ) ) {
if ( isset ( $field['required'][0] ) ) {
if ( ! is_array( $field['required'][0] ) && count( $field['required'] ) == 3 ) {
$parentValue = $GLOBALS[ $this->args['global_variable'] ][ $field['required'][0] ];
$checkValue = $field['required'][2];
$operation = $field['required'][1];
$return = $this->compareValueDependencies( $parentValue, $checkValue, $operation );
} else if ( is_array( $field['required'][0] ) ) {
foreach ( $field['required'] as $required ) {
if ( ! is_array( $required[0] ) && count( $required ) == 3 ) {
$parentValue = $GLOBALS[ $this->args['global_variable'] ][ $required[0] ];
$checkValue = $required[2];
$operation = $required[1];
$return = $this->compareValueDependencies( $parentValue, $checkValue, $operation );
}
if ( ! $return ) {
return $return;
}
}
}
}
}
return $return;
}
// _can_output_css
/**
* Checks dependencies between objects based on the $field['required'] array
* If the array is set it needs to have exactly 3 entries.
* The first entry describes which field should be monitored by the current field. eg: "content"
* The second entry describes the comparison parameter. eg: "equals, not, is_larger, is_smaller ,contains"
* The third entry describes the value that we are comparing against.
* Example: if the required array is set to array('content','equals','Hello World'); then the current
* field will only be displayed if the field with id "content" has exactly the value "Hello World"
*
* @param array $field
*
* @return array $params
*/
public function check_dependencies( $field ) {
//$params = array('data_string' => "", 'class_string' => "");
if ( ! empty ( $field['required'] ) ) {
//$this->folds[$field['id']] = $this->folds[$field['id']] ? $this->folds[$field['id']] : array();
if ( ! isset ( $this->required_child[ $field['id'] ] ) ) {
$this->required_child[ $field['id'] ] = array();
}
if ( ! isset ( $this->required[ $field['id'] ] ) ) {
$this->required[ $field['id'] ] = array();
}
if ( is_array( $field['required'][0] ) ) {
foreach ( $field['required'] as $value ) {
if ( is_array( $value ) && count( $value ) == 3 ) {
$data = array();
$data['parent'] = $value[0];
$data['operation'] = $value[1];
$data['checkValue'] = $value[2];
$this->required[ $data['parent'] ][ $field['id'] ][] = $data;
if ( ! in_array( $data['parent'], $this->required_child[ $field['id'] ] ) ) {
$this->required_child[ $field['id'] ][] = $data;
}
$this->checkRequiredDependencies( $field, $data );
}
}
} else {
$data = array();
$data['parent'] = $field['required'][0];
$data['operation'] = $field['required'][1];
$data['checkValue'] = $field['required'][2];
$this->required[ $data['parent'] ][ $field['id'] ][] = $data;
if ( ! in_array( $data['parent'], $this->required_child[ $field['id'] ] ) ) {
$this->required_child[ $field['id'] ][] = $data;
}
$this->checkRequiredDependencies( $field, $data );
}
}
//return $params;
}
// Compare data for required field
private function compareValueDependencies( $parentValue, $checkValue, $operation ) {
$return = false;
switch ( $operation ) {
case '=':
case 'equals':
$data['operation'] = "=";
if ( is_array( $parentValue ) ) {
foreach ( $parentValue as $idx => $val ) {
if ( is_array( $checkValue ) ) {
foreach ( $checkValue as $i => $v ) {
if ( $val == $v ) {
$return = true;
}
}
} else {
if ( $val == $checkValue ) {
$return = true;
}
}
}
} else {
if ( is_array( $checkValue ) ) {
foreach ( $checkValue as $i => $v ) {
if ( $parentValue == $v ) {
$return = true;
}
}
} else {
if ( $parentValue == $checkValue ) {
$return = true;
}
}
}
break;
case '!=':
case 'not':
$data['operation'] = "!==";
if ( is_array( $parentValue ) ) {
foreach ( $parentValue as $idx => $val ) {
if ( is_array( $checkValue ) ) {
foreach ( $checkValue as $i => $v ) {
if ( $val != $v ) {
$return = true;
}
}
} else {
if ( $val != $checkValue ) {
$return = true;
}
}
}
} else {
if ( is_array( $checkValue ) ) {
foreach ( $checkValue as $i => $v ) {
if ( $parentValue != $v ) {
$return = true;
}
}
} else {
if ( $parentValue != $checkValue ) {
$return = true;
}
}
}
// if ( is_array( $checkValue ) ) {
// if ( ! in_array( $parentValue, $checkValue ) ) {
// $return = true;
// }
// } else {
// if ( $parentValue != $checkValue ) {
// $return = true;
// } else if ( is_array( $parentValue ) ) {
// if ( ! in_array( $checkValue, $parentValue ) ) {
// $return = true;
// }
// }
// }
break;
case '>':
case 'greater':
case 'is_larger':
$data['operation'] = ">";
if ( $parentValue > $checkValue ) {
$return = true;
}
break;
case '>=':
case 'greater_equal':
case 'is_larger_equal':
$data['operation'] = ">=";
if ( $parentValue >= $checkValue ) {
$return = true;
}
break;
case '<':
case 'less':
case 'is_smaller':
$data['operation'] = "<";
if ( $parentValue < $checkValue ) {
$return = true;
}
break;
case '<=':
case 'less_equal':
case 'is_smaller_equal':
$data['operation'] = "<=";
if ( $parentValue <= $checkValue ) {
$return = true;
}
break;
case 'contains':
if ( is_array( $parentValue ) ) {
$parentValue = implode( ',', $parentValue );
}
if ( is_array( $checkValue ) ) {
foreach ( $checkValue as $idx => $opt ) {
if ( strpos( $parentValue, $opt ) !== false ) {
$return = true;
}
}
} else {
if ( strpos( $parentValue, $checkValue ) !== false ) {
$return = true;
}
}
break;
case 'doesnt_contain':
case 'not_contain':
if ( is_array( $parentValue ) ) {
$parentValue = implode( ',', $parentValue );
}
if ( is_array( $checkValue ) ) {
foreach ( $checkValue as $idx => $opt ) {
if ( strpos( $parentValue, $opt ) === false ) {
$return = true;
}
}
} else {
if ( strpos( $parentValue, $checkValue ) === false ) {
$return = true;
}
}
break;
case 'is_empty_or':
if ( empty ( $parentValue ) || $parentValue == $checkValue ) {
$return = true;
}
break;
case 'not_empty_and':
if ( ! empty ( $parentValue ) && $parentValue != $checkValue ) {
$return = true;
}
break;
case 'is_empty':
case 'empty':
case '!isset':
if ( empty ( $parentValue ) || $parentValue == "" || $parentValue == null ) {
$return = true;
}
break;
case 'not_empty':
case '!empty':
case 'isset':
if ( ! empty ( $parentValue ) && $parentValue != "" && $parentValue != null ) {
$return = true;
}
break;
}
return $return;
}
private function checkRequiredDependencies( $field, $data ) {
//required field must not be hidden. otherwise hide this one by default
if ( ! in_array( $data['parent'], $this->fieldsHidden ) && ( ! isset ( $this->folds[ $field['id'] ] ) || $this->folds[ $field['id'] ] != "hide" ) ) {
if ( isset ( $this->options[ $data['parent'] ] ) ) {
//echo $data['parent'];
$return = $this->compareValueDependencies( $this->options[ $data['parent'] ], $data['checkValue'], $data['operation'] );
//$return = $this->compareValueDependencies( $data['parent'], $data['checkValue'], $data['operation'] );
}
}
if ( ( isset ( $return ) && $return ) && ( ! isset ( $this->folds[ $field['id'] ] ) || $this->folds[ $field['id'] ] != "hide" ) ) {
$this->folds[ $field['id'] ] = "show";
} else {
$this->folds[ $field['id'] ] = "hide";
if ( ! in_array( $field['id'], $this->fieldsHidden ) ) {
$this->fieldsHidden[] = $field['id'];
}
}
}
/**
* converts an array into a html data string
*
* @param array $data example input: array('id'=>'true')
*
* @return string $data_string example output: data-id='true'
*/
public function create_data_string( $data = array() ) {
$data_string = "";
foreach ( $data as $key => $value ) {
if ( is_array( $value ) ) {
$value = implode( "|", $value );
}
$data_string .= " data-$key='$value' ";
}
return $data_string;
}
}
// ReduxFramework
/**
* action 'redux/init'
*
* @param null
*/
do_action( 'redux/init', ReduxFramework::init() );
} // class_exists('ReduxFramework')
| gpl-2.0 |
mmendoza000/freekore | app/plugins/Comments/js/comments.js | 3660 | // JavaScript Document
/*
* Function: fkComments
* Purpose: Comments Object
* Returns: -
* Inputs: object:oInit - initalisation options
*/
var Lang = {
leaveAComment : 'Deja un comentario...',
nameRequired : '<div>-El nombre es requerido</div>',
emailRequired : '<div>-El correo no es válido</div>',
commentRequired : '<div>-El comentario es requerido</div>',
deleteComment : 'Desea eliminar comentario?'
};
function fkComments(idObj, pUrl, Code, idTabVal) {
$('#leave-comment-' + idObj).val(Lang.leaveAComment);
$('#leave-comment-' + idObj).focus(function() {
// Limpiar
if ($(this).val() == Lang.leaveAComment) {
$(this).val("");
}
$('#li-lv-' + idObj).addClass('on');
if ($('#name-user-' + idObj).val() == '' ) {
$('#name-user-' + idObj).focus();
} else {
if ($('#email-user-' + idObj).val() == '') {
$('#email-user-' + idObj).focus();
}else{
$('#leave-comment-' + idObj).focus();
}
}
});
$('#leave-comment-' + idObj).blur(function(){
val_cmt = $('#leave-comment-' + idObj).val();
if(val_cmt==''){$('#li-lv-' + idObj).removeClass('on');}
});
$('#leave-comment-btn-' + idObj)
.click(
function() {
// <?=$this->id_obj?>
var cmt = $('#leave-comment-' + idObj).val();
var name = $('#name-user-' + idObj).val();
var email = $('#email-user-' + idObj).val();
var web = $('#web-user-' + idObj).val();
var err = 0;
var errMsg = '';
if (name != undefined) {
if (name == '') {
$('#name-user-' + idObj).addClass('alert');
errMsg += Lang.nameRequired;
err++;
}
} else {
name = '';
}
if (email != undefined) {
if (isEmail('#email-user-' + idObj) == false) {
$('#email-user-' + idObj).addClass('alert');
errMsg += Lang.emailRequired;
err++;
}
} else {
email = '';
}
if (web == undefined) {
web = '';
}
if (cmt == '') {
$('#leave-comment-' + idObj).addClass('alert');
errMsg += Lang.commentRequired;
err++;
}
if (err == 0) {
var pArgs = {
pDiv : 'comments-' + idObj,
pUrl : pUrl,
pArgs : 'op=save&code=' + Code + '&id-t-val='
+ idTabVal + '&comment=' + cmt
+ '&name=' + name + '&email=' + email
+ '&web=' + web,
pUrlAfter : '',
insertMode : 'bottom'
};
fk_ajax_exec(pArgs);
// Limpiar
$('#leave-comment-' + idObj).val("");
if (name != '') {
$('#name-user-' + idObj).val("");
}
if (email != '') {
$('#email-user-' + idObj).val("");
}
if (web != '') {
$('#web-user-' + idObj).val("");
}
$('.leave-comment').removeClass('on');
$('#message-err-' + idObj).hide();
if(name!=""){$('#name-user-' + idObj).removeClass('alert');}
if(email!=""){$('#email-user-' + idObj).removeClass('alert');}
if(web!=""){$('#web-user-' + idObj).removeClass('alert');}
$('#leave-comment-' + idObj).removeClass('alert');
$('#leave-comment-' + idObj).val(Lang.leaveAComment);
} else {
//$('#message-err-' + idObj).html('<h3>Error:</h3>' + errMsg);
//$('#message-err-' + idObj).show('slow');
}
});
}
function del_coment(args){
if(confirm(Lang.deleteComment)){
$('#com-'+args.i +'-'+ args.o).hide();
var pArgs = {
pDiv : 'oper-comments-' + args.o,
pUrl : args.u,
pArgs : 'op=del&i=' + args.i+'&id-t-val='+args.it ,
pUrlAfter : '',
insertMode : ''
};
fk_ajax_exec(pArgs);
}
} | gpl-2.0 |
Planigle/planigle | src/app/main/services/statuses.service.spec.ts | 426 | /* tslint:disable:no-unused-variable */
import { TestBed, async, inject } from '@angular/core/testing';
import { StatusesService } from './statuses.service';
describe('StatusesService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [StatusesService]
});
});
it('should ...', inject([StatusesService], (service: StatusesService) => {
expect(service).toBeTruthy();
}));
});
| gpl-2.0 |
ppizarror/korektor | test/accentsTest.py | 1313 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
bin/accents TEST
Test del manejo de acentos de la aplicación.
Autor: PABLO PIZARRO @ github.com/ppizarror
Fecha: AGOSTO 2016
Licencia: GPLv2
"""
__author__ = "ppizarror"
# Importación de librerías
# noinspection PyUnresolvedReferences
from _testpath import * # @UnusedWildImport
# noinspection PyUnresolvedReferences
from bin.accents import * # @UnusedWildImport
import unittest
# Constantes de los test
DISABLE_HEAVY_TESTS = True
DISABLE_HEAVY_TESTS_MSG = "Se desactivaron los tests pesados"
VERBOSE = False
# Se cargan argumentos desde la consola
if __name__ == '__main__':
from bin.arguments import argument_parser_factory
argparser = argument_parser_factory("Accents Test", verbose=True, version=True, enable_skipped_test=True).parse_args()
DISABLE_HEAVY_TESTS = argparser.enableHeavyTest
VERBOSE = argparser.verbose
# Clase UnitTest
class AccentsTest(unittest.TestCase):
def setUp(self):
"""
Inicio de los test.
:return: void
:rtype: None
"""
pass
# Main test
if __name__ == '__main__':
runner = unittest.TextTestRunner()
itersuite = unittest.TestLoader().loadTestsFromTestCase(AccentsTest)
runner.run(itersuite)
| gpl-2.0 |
alucard263096/AMK | Doctor.Android/AMKDoctor/app/src/main/java/com/helpfooter/steve/amkdoctor/Loader/BannerLoader.java | 5679 | package com.helpfooter.steve.amkdoctor.Loader;
import android.content.Context;
import com.helpfooter.steve.amkdoctor.DAO.BannerDao;
import com.helpfooter.steve.amkdoctor.DAO.ParamsDao;
import com.helpfooter.steve.amkdoctor.DataObjs.AbstractObj;
import com.helpfooter.steve.amkdoctor.DataObjs.BannerObj;
import com.helpfooter.steve.amkdoctor.Interfaces.IWebLoaderCallBack;
import com.helpfooter.steve.amkdoctor.Utils.StaticVar;
import java.util.ArrayList;
import java.util.HashMap;
public class BannerLoader extends WebXmlLoader {
public BannerLoader(Context ctx) {
super(ctx, "");
}
@Override
public void doXml(ArrayList<HashMap<String,String>> lstRows) {
String updatedate="";
ArrayList<AbstractObj> lsObj=new ArrayList<AbstractObj>();
for(HashMap<String,String> cols:lstRows){
BannerObj obj=new BannerObj();
obj.parseXmlDataTable(cols);
lsObj.add(obj);
}
if(lsObj.size()>0){
BannerDao dao=new BannerDao(ctx);
dao.batchUpdate(lsObj);
if(callBack!=null){
callBack.CallBack(lsObj);
}
ParamsDao paramdao=new ParamsDao(this.ctx);
paramdao.updateParam(this.callApi,StaticVar.GetSystemTimeString());
}
}
// EventListFragment eventListFragment;
//
// public EventListLoader(EventListFragment _eventListFragment){
// this.eventListFragment=_eventListFragment;
// }
//
// Handler mThirdHandler = new Handler(){
// @Override
// public void handleMessage(android.os.Message msg) {
// super.handleMessage(msg);
// switch(msg.what){
// case 0:
// Log.i("doit", "1");
// eventListFragment.initCommonList();
// Log.i("doit", "2");
// eventListFragment.init();
// Log.i("doit", "3");
// break;
// }
// };
// };
//
//
// @Override
// public String getCallUrl() {
// // TODO Auto-generated method stub
// ParamsDao dao=new ParamsDao(eventListFragment.getActivity());
// String update_date=dao.getParam("last_event_update_time", "1991-1-1");
// String url= StaticVar.CMSURL+"event_interface.aspx?type=geteventlist&request_date="+update_date.replace(" ", "%20");
// Log.i("callurl", url);
// return url;
// }
//
// @Override
// public void doXml(InputStream is) {
// // TODO Auto-generated method stub
// try
// {
// String updatedate="";
// List<EventObj> lsEvent=new ArrayList<EventObj>();
//
//
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// DocumentBuilder db = factory.newDocumentBuilder();
// Document doc = db.parse(is);
// Element elmtInfo = doc.getDocumentElement();
// NodeList StartNode = elmtInfo.getChildNodes();
// //XmlReader.ShowLog(StartNode);
// for (int i = 0; i < StartNode.getLength(); i++)
// {
// Node result = StartNode.item(i);
//
// if(result.getNodeName().equals("request_date")){
// updatedate=result.getTextContent();
// }else if(result.getNodeName().equals("events")){
// NodeList nsEvent = result.getChildNodes();
// for (int j = 0; j < nsEvent.getLength(); j++)
// {
// Node nodeEvent = nsEvent.item(j);
// NodeList potEvent = nodeEvent.getChildNodes();
//
// int eventId=0;
// String title="";
// String summary="";
// String imageurl="";
// String content="";
// String publisheddate="";
// int status=0;
// for (int k = 0; k < potEvent.getLength(); k++){
// Node eventpot = potEvent.item(k);
// Log.i(eventpot.getNodeName(),eventpot.getTextContent());
//
// if(eventpot.getNodeName().equals("eventid")){
// eventId=Integer.valueOf(eventpot.getTextContent());
// }else if(eventpot.getNodeName().equals("title")){
// title=eventpot.getTextContent();
// }else if(eventpot.getNodeName().equals("summary")){
// summary=eventpot.getTextContent();
// }else if(eventpot.getNodeName().equals("imageurl")){
// imageurl=eventpot.getTextContent();
// }else if(eventpot.getNodeName().equals("content")){
// content=eventpot.getTextContent();
// }else if(eventpot.getNodeName().equals("publisheddate")){
// publisheddate=eventpot.getTextContent();
// }else if(eventpot.getNodeName().equals("status")){
// status=Integer.valueOf(eventpot.getTextContent());
// }
// }
//
// EventObj event=new EventObj(eventId,title,summary,publisheddate);
// event.setContent(content);
// event.setImageUrl(StaticVar.CMSURL+imageurl);
// event.setStatus(status);
//
// lsEvent.add(event);
//
// }
// }
//// if (result.getNodeType() == Node.ELEMENT_NODE){
//// NodeList ns = result.getChildNodes();
//// XmlReader xml=new XmlReader(ns);
//// XmlReader.ShowLog(ns);
//// }
// }
// if(lsEvent.size()>0){
//
// EventDao dao=new EventDao(this.eventListFragment.getActivity());
// dao.batchUpdateEvent(lsEvent);
//
// mThirdHandler.sendEmptyMessage(0);
// }
//
// Log.i("updatedate", updatedate);
// if(updatedate.equals("")==false){
// ParamsDao paramdao=new ParamsDao(eventListFragment.getActivity());
// paramdao.updatefield("last_event_update_time",updatedate);
// }
//
//
// }
// catch (ParserConfigurationException e)
// {
// e.printStackTrace();
// }
// catch (SAXException e)
// {
// e.printStackTrace();
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
// }
}
| gpl-2.0 |
NaikSoftware/Chars | src/ua/naiksoftware/chars/GameView.java | 3431 | /**
* Game create for competition on http://annimon.com
*
* Copyright (C) 2012, 2013 NaikSoftware
*
* 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.
*/
package ua.naiksoftware.chars;
import android.content.Context;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
// TODO: заменить родителя на View чтобы зря не гонять процессор, а обновлять экран по надобности?
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
private static final String tag = "GameView";
private GameManager gameManThread;
private Context context;
private SizeListener sizeListener;
public GameView(Context context) {
super(context);
init(context);
}
public GameView(Context context, AttributeSet attr) {
super(context, attr);
init(context);
}
public GameView(Context context, AttributeSet attr, int style) {
super(context, attr, style);
init(context);
}
public void setArea(char[][] gameArea) {
if (gameManThread != null) {
gameManThread.setArea(gameArea);
}
}
private void init(Context context) {
//Log.d(tag, "init");
getHolder().addCallback(this);
this.context = context;
}
public void surfaceCreated(SurfaceHolder mHolder) {
//Log.d(tag, "surfaceCreated");
if (sizeListener != null) {
//L.write(tag, "onSizeChanged started interface not null");
final int w = getWidth();
final int h = getHeight();
int znam = 20;
final int min = Math.min(w, h);
final int max = Math.max(w, h);
int size = min / znam;
final int diff = (max % size > size / 2) ? 1 : -1;
while (max % size > 3) {
znam += diff;
size = min / znam;
}
int inRow = w / size;
int inColumn = h / size;
if (sizeListener.getState() == EngineActivity.STATE_NOT_INIT) {
sizeListener.onSizeChanged(inRow, inColumn);
}
gameManThread = new GameManager(mHolder, w, h, inRow, inColumn, size);
gameManThread.setRunning(true);
gameManThread.start();
}
}
public void surfaceChanged(SurfaceHolder mHolder, int p2, int p3, int p4) {
//Log.d(tag, "surfaceChanged");
}
public void surfaceDestroyed(SurfaceHolder p1) {
//Log.d(tag, "surfaceDestroyed");
gameManThread.setRunning(false);
}
public void setOnSizeListener(SizeListener sizeListener) {
this.sizeListener = sizeListener;
}
}
| gpl-2.0 |
reumia/wp-exhibition | wp-content/themes/wp-exhibition/functions.php | 7822 | <?php
/**
* 모든 함수의 접두어는 mbt을 붙인다. mytory basic theme의 약자다.
*/
function mbt_setup() {
// Adds RSS feed links to <head> for posts and comments.
add_theme_support( 'automatic-feed-links' );
// This theme uses wp_nav_menu() in one location.
register_nav_menu( 'main-nav', '메인 내비게이션' );
}
add_action( 'after_setup_theme', 'mbt_setup' );
function mbt_register_sidebar(){
register_sidebar(array(
'name' => '좌측',
'id' => 'sidebar-left',
'description' => '제일 왼쪽',
'before_title' => '<h3 class="sidebar-title">',
'after_title' => '</h3>'
));
register_sidebar(array(
'name' => '가운데',
'id' => 'sidebar-center',
'description' => '가운데 위치',
'before_title' => '<h3 class="sidebar-title">',
'after_title' => '</h3>'
));
register_sidebar(array(
'name' => '우측',
'id' => 'sidebar-right',
'description' => '제일 오른쪽',
'before_title' => '<h3 class="sidebar-title">',
'after_title' => '</h3>'
));
}
add_action('widgets_init', 'mbt_register_sidebar');
/**
* initialize style and script
*/
function mbt_scripts_styles() {
global $wp_styles;
/*
* Adds JavaScript to pages with the comment form to support
* sites with threaded comments (when in use).
*/
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) )
wp_enqueue_script( 'comment-reply' );
/*
* Loads main stylesheet.
*/
wp_enqueue_style( 'mbt-style', get_stylesheet_uri() );
/*
* Loads the Internet Explorer specific stylesheet.
*/
wp_enqueue_style( 'mbt-ie', get_template_directory_uri() . '/style-ie.css', array( 'mbt-style' ) );
$wp_styles->add_data( 'mbt-ie', 'conditional', 'lt IE 9' );
/*
* common.js
*/
wp_enqueue_script('mbt-common', get_template_directory_uri() . '/js/common.js', array('jquery'), '', TRUE);
}
add_action( 'wp_enqueue_scripts', 'mbt_scripts_styles' );
if( ! function_exists('getPrintr')){
/**
* 변수의 구성요소를 리턴받는다.
*/
function getPrintr($var, $title = NULL){
$dump = '';
$dump .= '<div align="left">';
$dump .= '<pre style="background-color:#000; color:#00ff00; padding:5px; font-size:14px;">';
if( $title )
{
$dump .= "<strong style='color:#fff'>{$title} :</strong> \n";
}
$dump .= print_r($var, TRUE);
$dump .= '</pre>';
$dump .= '</div>';
$dump .= '<br />';
return $dump;
}
}
if( ! function_exists('printr')){
/**
* 변수의 구성요소를 출력한다.
*/
function printr($var, $title = NULL)
{
$dump = getPrintr($var, $title);
echo $dump;
}
}
if( ! function_exists('printr2')){
/**
* 변수의 구성요소를 출력하고 멈춘다.
*/
function printr2($var, $title = NULL)
{
printr($var, $title);
exit;
}
}
function mbt_paging_nav() {
global $wp_query;
// Don't print empty markup if there's only one page.
if ( $wp_query->max_num_pages < 2 )
return;
?>
<nav class="paging-nav cf" role="navigation">
<?php if ( get_next_posts_link() ) { ?>
<div class="paging-nav__next"><?php next_posts_link('다음 ▷'); ?></div>
<?php } ?>
<?php if ( get_previous_posts_link() ) { ?>
<div class="paging-nav__prev"><?php previous_posts_link('◁ 이전'); ?></div>
<?php } ?>
</nav><!-- .navigation -->
<?php
}
function mbt_is_there_sidebar($name_arr){
$widgets = wp_get_sidebars_widgets();
foreach ($name_arr as $sidebar_name) {
if( ! empty($widgets[$sidebar_name])){
return true;
}
}
return false;
}
function mbt_print_header_others(){
?>
<div class="others-wrapper cf">
<ul class="others nav">
<li>
<a href="<?php bloginfo('rss_url')?>" title="RSS">
<img src="<?php echo get_template_directory_uri()?>/images/icon-rss.svg" alt="RSS">
</a>
</li>
<li>
<a href="<?php echo home_url('%ec%9d%b4%eb%a9%94%ec%9d%bc%eb%a1%9c-%ea%b5%ac%eb%8f%85%ed%95%98%ea%b8%b0')?>" title="Newsletter">
<img src="<?php echo get_template_directory_uri()?>/images/icon-newsletter.svg" alt="Newsletter">
</a>
</li>
<li>
<a href="https://twitter.com/mytory" title="Twitter">
<img src="<?php echo get_template_directory_uri()?>/images/icon-twitter.svg" alt="Twitter">
</a>
</li>
<li>
<a href="https://facebook.com/mytorydev" title="Facebook Page">
<img src="<?php echo get_template_directory_uri()?>/images/icon-facebook.svg" alt="Facebook Page">
</a>
</li>
<li>
<a href="https://plus.google.com/112373772451309371763" title="Google+ Page">
<img src="<?php echo get_template_directory_uri()?>/images/icon-g+.svg" alt="Google+ Page">
</a>
</li>
<li>
<a href="https://github.com/mytory" title="GitHub">
<img src="<?php echo get_template_directory_uri()?>/images/icon-github.svg" alt="GitHub">
</a>
</li>
<li>
<a href="<?php echo home_url('paypal-donation')?>" title="PayPal Donation">
<img src="<?php echo get_template_directory_uri()?>/images/icon-paypal.svg" alt="PayPal Donation">
</a>
</li>
</ul>
</div>
<?
}
function mbt_print_header_others_ie(){
?>
<div class="others-wrapper cf">
<ul class="others nav">
<li>
<a href="<?php bloginfo('rss_url')?>" title="RSS">
<img src="<?php echo get_template_directory_uri()?>/images/icon-rss.png" alt="RSS">
</a>
</li>
<li>
<a href="<?php echo home_url('%ec%9d%b4%eb%a9%94%ec%9d%bc%eb%a1%9c-%ea%b5%ac%eb%8f%85%ed%95%98%ea%b8%b0')?>" title="Newsletter">
<img src="<?php echo get_template_directory_uri()?>/images/icon-newsletter.png" alt="Newsletter">
</a>
</li>
<li>
<a href="https://twitter.com/mytory" title="Twitter">
<img src="<?php echo get_template_directory_uri()?>/images/icon-twitter.png" alt="Twitter">
</a>
</li>
<li>
<a href="https://facebook.com/mytorydev" title="Facebook Page">
<img src="<?php echo get_template_directory_uri()?>/images/icon-facebook.png" alt="Facebook Page">
</a>
</li>
<li>
<a href="https://plus.google.com/112373772451309371763" title="Google+ Page">
<img src="<?php echo get_template_directory_uri()?>/images/icon-g+.png" alt="Google+ Page">
</a>
</li>
<li>
<a href="https://github.com/mytory" title="GitHub">
<img src="<?php echo get_template_directory_uri()?>/images/icon-github.png" alt="GitHub">
</a>
</li>
<li>
<a href="<?php echo home_url('paypal-donation')?>" title="PayPal Donation">
<img src="<?php echo get_template_directory_uri()?>/images/icon-paypal.png" alt="PayPal Donation">
</a>
</li>
</ul>
</div>
<?
}
include 'functions-custom-post-type.php';
include 'functions-nav.php'; | gpl-2.0 |
twister65/joomla-cms | administrator/components/com_privacy/tmpl/request/default.php | 3133 | <?php
/**
* @package Joomla.Administrator
* @subpackage com_privacy
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Router\Route;
use Joomla\Component\Actionlogs\Administrator\Helper\ActionlogsHelper;
/** @var \Joomla\Component\Privacy\Administrator\View\Request\HtmlView $this */
HTMLHelper::_('behavior.formvalidator');
HTMLHelper::_('behavior.keepalive');
?>
<form action="<?php echo Route::_('index.php?option=com_privacy&view=request&id=' . (int) $this->item->id); ?>" method="post" name="adminForm" id="item-form" class="form-validate">
<div class="row mt-3">
<div class="col-12 col-md-4 mb-3">
<div class="card">
<h3 class="card-header"><?php echo Text::_('COM_PRIVACY_HEADING_REQUEST_INFORMATION'); ?></h3>
<div class="card-body">
<dl class="dl-horizontal">
<dt><?php echo Text::_('JGLOBAL_EMAIL'); ?>:</dt>
<dd><?php echo $this->item->email; ?></dd>
<dt><?php echo Text::_('JSTATUS'); ?>:</dt>
<dd><?php echo HTMLHelper::_('privacy.statusLabel', $this->item->status); ?></dd>
<dt><?php echo Text::_('COM_PRIVACY_FIELD_REQUEST_TYPE_LABEL'); ?>:</dt>
<dd><?php echo Text::_('COM_PRIVACY_HEADING_REQUEST_TYPE_TYPE_' . $this->item->request_type); ?></dd>
<dt><?php echo Text::_('COM_PRIVACY_FIELD_REQUESTED_AT_LABEL'); ?>:</dt>
<dd><?php echo HTMLHelper::_('date', $this->item->requested_at, Text::_('DATE_FORMAT_LC6')); ?></dd>
</dl>
</div>
</div>
</div>
<div class="col-12 col-md-8 mb-3">
<div class="card">
<h3 class="card-header"><?php echo Text::_('COM_PRIVACY_HEADING_ACTION_LOG'); ?></h3>
<div class="card-body">
<?php if (empty($this->actionlogs)) : ?>
<div class="alert alert-info">
<span class="fas fa-info-circle" aria-hidden="true"></span><span class="sr-only"><?php echo Text::_('INFO'); ?></span>
<?php echo Text::_('JGLOBAL_NO_MATCHING_RESULTS'); ?>
</div>
<?php else : ?>
<table class="table">
<thead>
<th>
<?php echo Text::_('COM_ACTIONLOGS_ACTION'); ?>
</th>
<th>
<?php echo Text::_('COM_ACTIONLOGS_DATE'); ?>
</th>
<th>
<?php echo Text::_('COM_ACTIONLOGS_NAME'); ?>
</th>
</thead>
<tbody>
<?php foreach ($this->actionlogs as $i => $item) : ?>
<tr class="row<?php echo $i % 2; ?>">
<td>
<?php echo ActionlogsHelper::getHumanReadableLogMessage($item); ?>
</td>
<td>
<?php echo HTMLHelper::_('date', $item->log_date, Text::_('DATE_FORMAT_LC6')); ?>
</td>
<td>
<?php echo $item->name; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif;?>
</div>
</div>
</div>
</div>
<input type="hidden" name="task" value="" />
<?php echo HTMLHelper::_('form.token'); ?>
</form>
| gpl-2.0 |
Viper9x/istore | administrator/components/com_virtuemart_allinone/plugins/vmpayment/amazon/assets/js/amazon.js | 10920 | /**
*
* Amazon payment plugin
*
* @author Valérie Isaksen
* @version $Id$
* @package VirtueMart
* @subpackage payment
* Copyright (C) 2004-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.
* See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details.
*
* http://virtuemart.net
*/
var amazonPayment = {
showAmazonButton: function (sellerId, redirect_page, useAmazonAddressBook) {
// window.onError = null; // some of the amazon scripts can load in error handlers to report back errors to amazon. helps them, but keeps you in the dark.
console.log("amazonShowButton called: useAmazonAddressBook=" + useAmazonAddressBook);
new OffAmazonPayments.Widgets.Button({
sellerId: sellerId,
useAmazonAddressBook: useAmazonAddressBook,
onSignIn: function (orderReference) {
var amazonOrderReferenceId = orderReference.getAmazonOrderReferenceId();
window.location = redirect_page + '&session=' + amazonOrderReferenceId;
console.log('onSignIn() ' + amazonOrderReferenceId);
},
onError: function (error) {
console.log('Amazon onSignIn()' + error);
alert('AMAZON onSignIn(): ' + error.getErrorCode() + ": " + error.getErrorMessage());
}
}).bind('payWithAmazonDiv');
},
initPayment: function (sellerId, amazonOrderReferenceId, width, height, isMobile, virtuemart_paymentmethod_id, displayMode) {
amazonPayment.sellerId = sellerId;
amazonPayment.amazonOrderReferenceId = amazonOrderReferenceId;
amazonPayment.width = width;
amazonPayment.height = height;
amazonPayment.isMobile = isMobile;
amazonPayment.virtuemart_paymentmethod_id = virtuemart_paymentmethod_id;
amazonPayment.displayMode = displayMode;
},
showAmazonWallet: function () {
window.onError = null;
console.log("amazonShowWallet: " + amazonPayment.amazonOrderReferenceId);
var checkoutFormSubmit = document.getElementById("checkoutFormSubmit");
checkoutFormSubmit.className = 'vm-button-correct';
checkoutFormSubmit.className = 'vm-button';
checkoutFormSubmit.setAttribute('disabled', 'true');
new OffAmazonPayments.Widgets.Wallet({
sellerId: amazonPayment.sellerId,
amazonOrderReferenceId: amazonPayment.amazonOrderReferenceId, // amazonOrderReferenceId obtained from Button widget
displayMode: amazonPayment.displayMode,
design: {
size: {width: amazonPayment.width, height: amazonPayment.height}
},
onPaymentSelect: function (orderReference) {
haveWallet = true;
checkoutFormSubmit.className = 'vm-button-correct';
checkoutFormSubmit.removeAttribute('disabled');
},
onError: function (error) {
amazonPayment.onErrorAmazon('amazonShowWallet', error);
}
}).bind("amazonWalletWidgetDiv");
},
showAmazonAddress: function () {
console.log("amazonShowAddress: " + amazonPayment.amazonOrderReferenceId);
new OffAmazonPayments.Widgets.AddressBook({
sellerId: amazonPayment.sellerId,
amazonOrderReferenceId: amazonPayment.amazonOrderReferenceId, // amazonOrderReferenceId obtained from Button widget
onAddressSelect: function (orderReference) {
var url = vmSiteurl + 'index.php?option=com_virtuemart&view=plugin&type=vmpayment&name=amazon&action=updateCartWithAmazonAddress&virtuemart_paymentmethod_id=' + amazonPayment.virtuemart_paymentmethod_id + vmLang;
//document.id('amazonShipmentNotFoundDiv').set('html', '');
amazonPayment.startLoading();
jQuery.getJSON(url,
function (datas, textStatus) {
var errormsg = '';
var checkoutFormSubmit = document.getElementById("checkoutFormSubmit");
checkoutFormSubmit.className = 'vm-button-correct';
checkoutFormSubmit.removeAttribute('disabled');
amazonPayment.updateCart();
amazonPayment.showAmazonWallet();
if (typeof datas.error_msg != 'undefined' && datas.error_msg != '') {
errormsg = datas.error_msg;
checkoutFormSubmit.className = 'vm-button';
checkoutFormSubmit.setAttribute('disabled', 'true');
document.id('amazonShipmentsDiv').style.display = 'none';
amazonPayment.stopLoading();
}
document.id('amazonErrorDiv').set('html', errormsg);
}
);
amazonPayment.stopLoading();
},
displayMode: amazonPayment.displayMode,
design: {
size: {width:amazonPayment.width, height: amazonPayment.height}
},
onError: function (error) {
amazonPayment.onErrorAmazon('amazonShowAddress', error, amazonPayment.virtuemart_paymentmethod_id);
},
}).bind("amazonAddressBookWidgetDiv");
},
startLoading: function () {
//document.getElementsByTagName('body')[0].className += " vmLoading";
//document.body.innerHTML += "<div class=\"vmLoadingDiv\"></div>";
},
stopLoading: function () {
//document.getElementsByTagName('body')[0].className = document.getElementsByTagName('body')[0].className.replace("vmLoading","");
},
onAmazonAddressSelect: function () {
console.log('onAddressSelect');
amazonPayment.updateCartWithAmazonAddress();
},
updateCart: function () {
var url = vmSiteurl + 'index.php?option=com_virtuemart&nosef=1&view=cart&task=checkoutJS&virtuemart_paymentmethod_id=' + amazonPayment.virtuemart_paymentmethod_id + vmLang;
jQuery.getJSON(url,
function (datas, textStatus) {
var cartview = "";
console.log('updateCart:' + datas.msg.length);
if (datas.msg) {
datas.msg = datas.msg.replace('amazonHeader', 'amazonHeaderHide');
datas.msg = datas.msg.replace('amazonShipmentNotFoundDiv', 'amazonShipmentNotFoundDivHide');
for (var i = 0; i < datas.msg.length; i++) {
cartview += datas.msg[i].toString();
}
document.id('amazonCartDiv').set('html', cartview);
document.id('amazonHeaderHide').set('html', '');
document.id('amazonShipmentNotFoundDivHide').set('html', '');
amazonPayment.stopLoading();
}
}
);
},
onErrorAmazon: function (from, error) {
console.log('onErrorAmazon:' + from +' '+ error.getErrorCode());
var sessionExpired = "BuyerSessionExpired";
if (error.getErrorCode() == sessionExpired) {
var url = vmSiteurl + 'index.php?option=com_virtuemart&view=plugin&type=vmpayment&name=amazon&action=resetAmazonReferenceId&virtuemart_paymentmethod_id=' + amazonPayment.virtuemart_paymentmethod_id;
console.log('resetAmazonReferenceId');
jQuery.getJSON(url, function (data) {
var reloadurl = 'index.php?option=com_virtuemart&view=cart';
window.location.href = reloadurl;
});
}
},
/**
* used in cart_shipment tmpl
*/
setShipmentReloadWallet: function() {
amazonPayment.startLoading();
var virtuemart_shipmentmethod_ids = document.getElementsByName('virtuemart_shipmentmethod_id');
var virtuemart_shipmentmethod_id = '';
for (var i = 0, length = virtuemart_shipmentmethod_ids.length; i < length; i++) {
if (virtuemart_shipmentmethod_ids[i].checked) {
virtuemart_shipmentmethod_id = virtuemart_shipmentmethod_ids[i].value;
break;
}
}
var url = vmSiteurl + 'index.php?option=com_virtuemart&nosef=1&view=cart&task=checkoutJS&virtuemart_shipmentmethod_id=' + virtuemart_shipmentmethod_id + vmLang;
jQuery.getJSON(url,
function (datas, textStatus) {
var cartview = '';
console.log('updateCart:' + datas.msg.length);
if (datas.msg) {
datas.msg = datas.msg.replace('amazonHeader', 'amazonHeaderHide');
for (var i = 0; i < datas.msg.length; i++) {
cartview += datas.msg[i].toString();
}
document.id('amazonCartDiv').set('html', cartview);
document.id('amazonHeaderHide').set('html', '');
amazonPayment.stopLoading();
amazonPayment.showAmazonWallet();
}
}
);
},
/**
* used in addressbook_wallet tmpl
* @param warning
*/
displayCaptureNowWarning: function(warning) {
document.id('amazonChargeNowWarning').set('html',warning);
},
leaveAmazonCheckout: function() {
var url = vmSiteurl + 'index.php?option=com_virtuemart&view=plugin&type=vmpayment&name=amazon&action=leaveAmazonCheckout&virtuemart_paymentmethod_id=' + amazonPayment.virtuemart_paymentmethod_id + vmLang ;
console.log('leaveAmazonCheckout');
jQuery.getJSON(url, function(data) {
var reloadurl = vmSiteurl +'index.php?option=com_virtuemart&view=cart' + vmLang;
window.location.href = reloadurl;
});
}
}
;
| gpl-2.0 |
dekmidia/openbalada | wp-content/plugins/loginradius-for-wordpress/lr-social-sharing/admin/views/horizontal-settings/horizontal-view.php | 25609 | <?php
// Exit if called directly
if ( !defined( 'ABSPATH' ) ) {
exit();
}
/**
* The main class and initialization point of the plugin settings page.
*/
if ( ! class_exists( 'LR_Social_Share_Horizontal_Settings' ) ) {
class LR_Social_Share_Horizontal_Settings {
public function render_options_page() {
global $loginradius_share_settings;
?>
<!-- Horizontal Sharing -->
<div id="lr_options_tab-1" class="lr-tab-frame lr-active">
<!-- Horizontal Options -->
<div class="lr_options_container">
<!-- Horizontal Switch -->
<div id="lr_horizontal_switch" class="lr-row">
<label for="lr-enable-horizontal" class="lr-toggle">
<input type="checkbox" class="lr-toggle" id="lr-enable-horizontal" name="LoginRadius_share_settings[horizontal_enable]" value="1" <?php echo ( isset($loginradius_share_settings['horizontal_enable']) && $loginradius_share_settings['horizontal_enable'] == '1') ? 'checked' : ''; ?> />
<span class="lr-toggle-name">Enable Horizontal Widget</span>
</label>
</div>
<div class="lr-option-disabled-hr"></div>
<div class="lr_horizontal_interface lr-row">
<h3>Select the sharing theme</h3>
<div>
<input type="radio" id="lr-horizontal-lrg" name="LoginRadius_share_settings[horizontal_share_interface]" value="32-h" <?php echo ( !isset( $loginradius_share_settings['horizontal_share_interface'] ) || $loginradius_share_settings['horizontal_share_interface'] == '32-h' ) ? 'checked' : ''; ?> />
<label class="lr_horizontal_interface_img" for="lr-horizontal-lrg"><img src="<?php echo LR_SHARE_PLUGIN_URL . "/assets/images/sharing/32-h.png" ?>" /></label>
</div>
<div>
<input type="radio" id="lr-horizontal-sml" name="LoginRadius_share_settings[horizontal_share_interface]" value="16-h" <?php echo ( $loginradius_share_settings['horizontal_share_interface'] == '16-h' ) ? 'checked' : ''; ?> />
<label class="lr_horizontal_interface_img" for="lr-horizontal-sml"><img src="<?php echo LR_SHARE_PLUGIN_URL . "/assets/images/sharing/16-h.png" ?>" /></label>
</div>
<div>
<input type="radio" id="lr-single-lg-h" name="LoginRadius_share_settings[horizontal_share_interface]" value="single-lg-h" <?php echo ( $loginradius_share_settings['horizontal_share_interface'] == 'single-lg-h' ) ? 'checked' : ''; ?> />
<label class="lr_horizontal_interface_img" for="lr-single-lg-h"><img src="<?php echo LR_SHARE_PLUGIN_URL . "/assets/images/sharing/single-lg-h.png" ?>" /></label>
</div>
<div>
<input type="radio" id="lr-single-sm-h" name="LoginRadius_share_settings[horizontal_share_interface]" value="single-sm-h" <?php echo ( $loginradius_share_settings['horizontal_share_interface'] == 'single-sm-h' ) ? 'checked' : ''; ?> />
<label class="lr_horizontal_interface_img" for="lr-single-sm-h"><img src="<?php echo LR_SHARE_PLUGIN_URL . "/assets/images/sharing/single-sm-h.png" ?>" /></label>
</div>
<div>
<input type="radio" id="lr-sharing/hybrid-h-h" name="LoginRadius_share_settings[horizontal_share_interface]" value="hybrid-h-h" <?php echo ( $loginradius_share_settings['horizontal_share_interface'] == 'hybrid-h-h' ) ? 'checked' : ''; ?> />
<label class="lr_horizontal_interface_img" for="lr-sharing/hybrid-h-h"><img src="<?php echo LR_SHARE_PLUGIN_URL . "/assets/images/sharing/hybrid-h-h.png" ?>" /></label>
</div>
<div>
<input type="radio" id="lr-hybrid-h-v" name="LoginRadius_share_settings[horizontal_share_interface]" value="hybrid-h-v" <?php echo ( $loginradius_share_settings['horizontal_share_interface'] == 'hybrid-h-v' ) ? 'checked' : ''; ?> />
<label class="lr_horizontal_interface_img" for="lr-hybrid-h-v"><img src="<?php echo LR_SHARE_PLUGIN_URL . "/assets/images/sharing/hybrid-h-v.png" ?>" /></label>
</div>
</div>
<div id="lr_hz_theme_options" class="lr-row cf">
<h3>
Select the sharing networks
<span class="lr-tooltip" data-title="Selected sharing networks will be displayed in the widget">
<span class="dashicons dashicons-editor-help"></span>
</span>
</h3>
<div id="lr_hz_hz_theme_options" style="display:block;">
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Default][Delicious]" value="Delicious" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Default']['Delicious']) && $loginradius_share_settings['horizontal_sharing_providers']['Default']['Delicious'] == 'Delicious' ) ? 'checked' : ''; ?> />
<span class="lr-text lr-icon-delicious">Delicious</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Default][Digg]" value="Digg" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Default']['Digg']) && $loginradius_share_settings['horizontal_sharing_providers']['Default']['Digg'] == 'Digg' ) ? 'checked' : ''; ?> />
<span class="lr-text lr-icon-digg">Digg</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Default][Email]" value="Email" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Default']['Email']) && $loginradius_share_settings['horizontal_sharing_providers']['Default']['Email'] == 'Email' ) ? 'checked' : ''; ?> />
<span class="lr-text lr-icon-email">Email</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Default][Facebook]" value="Facebook" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Default']['Facebook']) && $loginradius_share_settings['horizontal_sharing_providers']['Default']['Facebook'] == 'Facebook' ) ? 'checked' : ''; ?> />
<span class="lr-text lr-icon-facebook">Facebook</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Default][GooglePlus]" value="GooglePlus" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Default']['GooglePlus']) && $loginradius_share_settings['horizontal_sharing_providers']['Default']['GooglePlus'] == 'GooglePlus' ) ? 'checked' : ''; ?> />
<span class="lr-text lr-icon-googleplus">Google+</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Default][Google]" value="Google" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Default']['Google']) && $loginradius_share_settings['horizontal_sharing_providers']['Default']['Google'] == 'Google' ) ? 'checked' : ''; ?> />
<span class="lr-text lr-icon-google">Google</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Default][LinkedIn]" value="LinkedIn" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Default']['LinkedIn']) && $loginradius_share_settings['horizontal_sharing_providers']['Default']['LinkedIn'] == 'LinkedIn' ) ? 'checked' : ''; ?> />
<span class="lr-text lr-icon-linkedin">LinkedIn</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Default][MySpace]" value="MySpace" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Default']['MySpace']) && $loginradius_share_settings['horizontal_sharing_providers']['Default']['MySpace'] == 'MySpace' ) ? 'checked' : ''; ?> />
<span class="lr-text lr-icon-myspace">MySpace</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Default][Pinterest]" value="Pinterest" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Default']['Pinterest']) && $loginradius_share_settings['horizontal_sharing_providers']['Default']['Pinterest'] == 'Pinterest' ) ? 'checked' : ''; ?> />
<span class="lr-text lr-icon-pinterest">Pinterest</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Default][Print]" value="Print" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Default']['Print']) && $loginradius_share_settings['horizontal_sharing_providers']['Default']['Print'] == 'Print' ) ? 'checked' : ''; ?> />
<span class="lr-text lr-icon-print">Print</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Default][Reddit]" value="Reddit" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Default']['Reddit']) && $loginradius_share_settings['horizontal_sharing_providers']['Default']['Reddit'] == 'Reddit' ) ? 'checked' : ''; ?> />
<span class="lr-text lr-icon-reddit">Reddit</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Default][Tumblr]" value="Tumblr" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Default']['Tumblr']) && $loginradius_share_settings['horizontal_sharing_providers']['Default']['Tumblr'] == 'Tumblr' ) ? 'checked' : ''; ?> />
<span class="lr-text lr-icon-tumblr">Tumblr</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Default][Twitter]" value="Twitter" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Default']['Twitter']) && $loginradius_share_settings['horizontal_sharing_providers']['Default']['Twitter'] == 'Twitter' ) ? 'checked' : ''; ?> />
<span class="lr-text lr-icon-twitter">Twitter</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Default][Vkontakte]" value="Vkontakte" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Default']['Vkontakte']) && $loginradius_share_settings['horizontal_sharing_providers']['Default']['Vkontakte'] == 'Vkontakte' ) ? 'checked' : ''; ?> />
<span class="lr-text lr-icon-vkontakte">Vkontakte</span>
</label>
<div id="loginRadiusHorizontalSharingLimit" class="lr-alert-box" style="display:none; margin-bottom: 5px;"><?php _e( 'You can select only eight providers', 'LoginRadius' ) ?>.</div>
<p class="lr-footnote">*All other icons will be included in the pop-up</p>
</div>
<div id="lr_hz_ve_theme_options" style="display:none;">
<!-- <h5>Vertical Theme</h5> -->
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_ve_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Hybrid][Facebook Like]" value="Facebook Like" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Facebook Like']) && $loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Facebook Like'] == 'Facebook Like' ) ? 'checked' : ''; ?> />
<span class="lr-text">Facebook Like</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_ve_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Hybrid][Twitter Tweet]" value="Twitter Tweet" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Twitter Tweet']) && $loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Twitter Tweet'] == 'Twitter Tweet' ) ? 'checked' : ''; ?> />
<span class="lr-text">Twitter Tweet</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_ve_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Hybrid][StumbleUpon Badge]" value="StumbleUpon Badge" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['StumbleUpon Badge']) && $loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['StumbleUpon Badge'] == 'StumbleUpon Badge' ) ? 'checked' : ''; ?> />
<span class="lr-text">StumbleUpon Badge</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_ve_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Hybrid][Google+ Share]" value="Google+ Share" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Google+ Share']) && $loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Google+ Share'] == 'Google+ Share' ) ? 'checked' : ''; ?> />
<span class="lr-text">Google+ Share</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_ve_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Hybrid][Facebook Recommend]" value="Facebook Recommend" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Facebook Recommend']) && $loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Facebook Recommend'] == 'Facebook Recommend' ) ? 'checked' : ''; ?> />
<span class="lr-text">Facebook Recommend</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_ve_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Hybrid][Pinterest Pin it]" value="Pinterest Pin it" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Pinterest Pin it']) && $loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Pinterest Pin it'] == 'Pinterest Pin it' ) ? 'checked' : ''; ?> />
<span class="lr-text">Pinterest Pin it</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_ve_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Hybrid][Reddit]" value="Reddit" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Reddit']) && $loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Reddit'] == 'Reddit' ) ? 'checked' : ''; ?> />
<span class="lr-text">Reddit</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_ve_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Hybrid][Hybridshare]" value="Hybridshare" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Hybridshare']) && $loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Hybridshare'] == 'Hybridshare' ) ? 'checked' : ''; ?> />
<span class="lr-text">Hybridshare</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_ve_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Hybrid][Facebook Send]" value="Facebook Send" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Facebook Send']) && $loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Facebook Send'] == 'Facebook Send' ) ? 'checked' : ''; ?> />
<span class="lr-text">Facebook Send</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_ve_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Hybrid][LinkedIn Share]" value="LinkedIn Share" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['LinkedIn Share']) && $loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['LinkedIn Share'] == 'LinkedIn Share' ) ? 'checked' : ''; ?> />
<span class="lr-text">LinkedIn Share</span>
</label>
<label class="lr-sharing-cb">
<input type="checkbox" class="LoginRadius_hz_ve_share_providers" name="LoginRadius_share_settings[horizontal_sharing_providers][Hybrid][Google+ +1]" value="Google+ +1" <?php echo ( isset($loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Google+ +1']) && $loginradius_share_settings['horizontal_sharing_providers']['Hybrid']['Google+ +1'] == 'Google+ +1' ) ? 'checked' : ''; ?> />
<span class="lr-text">Google+ +1</span>
</label>
<div id="loginRadiusHorizontalVerticalSharingLimit" class="lr-alert-box" style="display:none; margin-bottom: 5px;">
<?php _e( 'You can select only eight providers', 'LoginRadius' ) ?>.
</div>
<p class="lr-footnote"></p>
</div>
</div>
<div class="lr-row" id="login_radius_horizontal_rearrange_container">
<h3>
<?php _e( 'Select the sharing networks order', 'LoginRadius' ) ?>
<span class="lr-tooltip" data-title="Drag the icons around to set the order">
<span class="dashicons dashicons-editor-help"></span>
</span>
</h3>
<ul id="loginRadiusHorizontalSortable" class="cf">
<?php
if ( isset( $loginradius_share_settings['horizontal_rearrange_providers'] ) && count( $loginradius_share_settings['horizontal_rearrange_providers'] ) > 0 ) {
foreach ( $loginradius_share_settings['horizontal_rearrange_providers'] as $provider ) {
?>
<li title="<?php echo $provider ?>" id="loginRadiusHorizontalLI<?php echo $provider ?>" class="lrshare_iconsprite32 lr-icon-<?php echo strtolower( $provider ) ?>">
<input type="hidden" name="LoginRadius_share_settings[horizontal_rearrange_providers][]" value="<?php echo $provider ?>" />
</li>
<?php
}
}
?>
</ul>
<ul class="lr-static">
<li title="More" id="loginRadiusHorizontalLImore" class="lr-pin lr-icon-more lrshare_evenmore">
</li>
<li title="Counter" id="loginRadiusHorizontalLIcounter" class="lr-pin lr-counter">1.2m
</li>
</ul>
</div>
<div class="lr-row cf">
<h3>
Choose the location(s) to display the widget
<span class="lr-tooltip" data-title="Sharing widget will be displayed at the selected location(s)">
<span class="dashicons dashicons-editor-help"></span>
</span>
</h3>
<div>
<input type="checkbox" class="lr-toggle" id="lr-clicker-hr-home" name="LoginRadius_share_settings[lr-clicker-hr-home]" value="1" <?php echo ( isset($loginradius_share_settings['lr-clicker-hr-home']) && $loginradius_share_settings['lr-clicker-hr-home'] == '1') ? 'checked' : ''; ?> />
<label class="lr-show-toggle" for="lr-clicker-hr-home">
Home Page
<span class="lr-tooltip" data-title="Home page of your blog">
<span class="dashicons dashicons-editor-help"></span>
</span>
</label>
<div class="lr-show-options">
<label>
<input type="checkbox" class="lr-clicker-hr-home-options default" name="LoginRadius_share_settings[horizontal_position][Home][Top]" value="Top" <?php echo ( isset($loginradius_share_settings['horizontal_position']['Home']['Top']) && $loginradius_share_settings['horizontal_position']['Home']['Top'] == 'Top' ) ? 'checked' : ''; ?> />
<span>Top of the content</span>
</label>
<label>
<input type="checkbox" class="lr-clicker-hr-home-options" name="LoginRadius_share_settings[horizontal_position][Home][Bottom]" value="Bottom" <?php echo ( isset($loginradius_share_settings['horizontal_position']['Home']['Bottom']) && $loginradius_share_settings['horizontal_position']['Home']['Bottom'] == 'Bottom' ) ? 'checked' : ''; ?> />
<span>Bottom of the content</span>
</label>
</div>
</div>
<div>
<input type="checkbox" class="lr-toggle" id="lr-clicker-hr-post" name="LoginRadius_share_settings[lr-clicker-hr-post]" value="1" <?php echo ( isset($loginradius_share_settings['lr-clicker-hr-post']) && $loginradius_share_settings['lr-clicker-hr-post'] == '1') ? 'checked' : ''; ?> />
<label class="lr-show-toggle" for="lr-clicker-hr-post">
Blog Post
<span class="lr-tooltip" data-title="Each post of your blog">
<span class="dashicons dashicons-editor-help"></span>
</span>
</label>
<div class="lr-show-options">
<label>
<input type="checkbox" class="lr-clicker-hr-post-options default" name="LoginRadius_share_settings[horizontal_position][Posts][Top]" value="Top" <?php echo ( isset($loginradius_share_settings['horizontal_position']['Posts']['Top']) && $loginradius_share_settings['horizontal_position']['Posts']['Top'] == 'Top' ) ? 'checked' : ''; ?> />
<span>Top of the content</span>
</label>
<label>
<input type="checkbox" class="lr-clicker-hr-post-options default" name="LoginRadius_share_settings[horizontal_position][Posts][Bottom]" value="Bottom" <?php echo ( isset($loginradius_share_settings['horizontal_position']['Posts']['Bottom']) && $loginradius_share_settings['horizontal_position']['Posts']['Bottom'] == 'Bottom' ) ? 'checked' : ''; ?> />
<span>Bottom of the content</span>
</label>
</div>
</div>
<div>
<input type="checkbox" class="lr-toggle" id="lr-clicker-hr-static" name="LoginRadius_share_settings[lr-clicker-hr-static]" value="1" <?php echo ( isset($loginradius_share_settings['lr-clicker-hr-static']) && $loginradius_share_settings['lr-clicker-hr-static'] == '1') ? 'checked' : ''; ?> />
<label class="lr-show-toggle" for="lr-clicker-hr-static">
Static Pages
<span class="lr-tooltip" data-title="Static pages of your blog (e.g – about, contact, etc.)">
<span class="dashicons dashicons-editor-help"></span>
</span>
</label>
<div class="lr-show-options">
<label>
<input type="checkbox" class="lr-clicker-hr-static-options default" name="LoginRadius_share_settings[horizontal_position][Pages][Top]" value="Top" <?php echo ( isset($loginradius_share_settings['horizontal_position']['Pages']['Top']) && $loginradius_share_settings['horizontal_position']['Pages']['Top'] == 'Top' ) ? 'checked' : ''; ?> />
<span>Top of the content</span>
</label>
<label>
<input type="checkbox" class="lr-clicker-hr-static-options" name="LoginRadius_share_settings[horizontal_position][Pages][Bottom]" value="Bottom" <?php echo ( isset($loginradius_share_settings['horizontal_position']['Pages']['Bottom']) && $loginradius_share_settings['horizontal_position']['Pages']['Bottom'] == 'Bottom' ) ? 'checked' : ''; ?> />
<span>Bottom of the content</span>
</label>
</div>
</div>
<div>
<input type="checkbox" class="lr-toggle" id="lr-clicker-hr-excerpts" name="LoginRadius_share_settings[lr-clicker-hr-excerpts]" value="1" <?php echo ( isset($loginradius_share_settings['lr-clicker-hr-excerpts']) && $loginradius_share_settings['lr-clicker-hr-excerpts'] == '1') ? 'checked' : ''; ?> />
<label class="lr-show-toggle" for="lr-clicker-hr-excerpts">
Post Excerpts
<span class="lr-tooltip" data-title="Post excerpts page">
<span class="dashicons dashicons-editor-help"></span>
</span>
</label>
<div class="lr-show-options">
<label>
<input type="checkbox" class="lr-clicker-hr-excerpts-options default" name="LoginRadius_share_settings[horizontal_position][Excerpts][Top]" value="Top" <?php echo ( isset($loginradius_share_settings['horizontal_position']['Excerpts']['Top']) && $loginradius_share_settings['horizontal_position']['Excerpts']['Top'] == 'Top' ) ? 'checked' : ''; ?> />
<span>Top of the content</span>
</label>
<label>
<input type="checkbox" class="lr-clicker-hr-excerpts-options" name="LoginRadius_share_settings[horizontal_position][Excerpts][Bottom]" value="Bottom" <?php echo ( isset($loginradius_share_settings['horizontal_position']['Excerpts']['Bottom']) && $loginradius_share_settings['horizontal_position']['Excerpts']['Bottom'] == 'Bottom' ) ? 'checked' : ''; ?> />
<span>Bottom of the content</span>
</label>
</div><!-- options -->
</div>
</div><!-- row -->
</div><!-- Container -->
<?php submit_button('Save changes'); ?>
</div><!-- End Horizontal Sharing -->
<?php
}
}
} | gpl-2.0 |
fvaron/zencart_fr | includes/languages/spanish/html_includes/classic/define_videos.php | 414 | <b>¿Cómo cambiar una lámapara de un proyector de video?
</b><br /><br />
Esta guía explica las etapas del montaje y desmontaje de una lámpara de un proyector de video.
<br /><br />
<object height="175" width="212">
<param value="http://www.youtube.com/v/ej300mRfa54" name="movie" />
<embed height="227" width="270" type="application/x-shockwave-flash" src="http://www.youtube.com/v/ej300mRfa54" />
</object>
| gpl-2.0 |
adrianjonmiller/anacapa_animal_health | wp-content/plugins/wp-views/res/js/codemirror234/mode/stex/test.js | 4562 | var MT = ModeTest;
MT.modeName = 'stex';
MT.modeOptions = {};
MT.testMode(
'word',
'foo',
[
null, 'foo'
]
);
MT.testMode(
'twoWords',
'foo bar',
[
null, 'foo bar'
]
);
MT.testMode(
'beginEndDocument',
'\\begin{document}\n\\end{document}',
[
'tag', '\\begin',
'bracket', '{',
'atom', 'document',
'bracket', '}',
'tag', '\\end',
'bracket', '{',
'atom', 'document',
'bracket', '}'
]
);
MT.testMode(
'beginEndEquation',
'\\begin{equation}\n E=mc^2\n\\end{equation}',
[
'tag', '\\begin',
'bracket', '{',
'atom', 'equation',
'bracket', '}',
null, ' E=mc^2',
'tag', '\\end',
'bracket', '{',
'atom', 'equation',
'bracket', '}'
]
);
MT.testMode(
'beginModule',
'\\begin{module}[]',
[
'tag', '\\begin',
'bracket', '{',
'atom', 'module',
'bracket', '}[]'
]
);
MT.testMode(
'beginModuleId',
'\\begin{module}[id=bbt-size]',
[
'tag', '\\begin',
'bracket', '{',
'atom', 'module',
'bracket', '}[',
null, 'id=bbt-size',
'bracket', ']'
]
);
MT.testMode(
'importModule',
'\\importmodule[b-b-t]{b-b-t}',
[
'tag', '\\importmodule',
'bracket', '[',
'string', 'b-b-t',
'bracket', ']{',
'builtin', 'b-b-t',
'bracket', '}'
]
);
MT.testMode(
'importModulePath',
'\\importmodule[\\KWARCslides{dmath/en/cardinality}]{card}',
[
'tag', '\\importmodule',
'bracket', '[',
'tag', '\\KWARCslides',
'bracket', '{',
'string', 'dmath/en/cardinality',
'bracket', '}]{',
'builtin', 'card',
'bracket', '}'
]
);
MT.testMode(
'psForPDF',
'\\PSforPDF[1]{#1}', // could treat #1 specially
[
'tag', '\\PSforPDF',
'bracket', '[',
'atom', '1',
'bracket', ']{',
null, '#1',
'bracket', '}'
]
);
MT.testMode(
'comment',
'% foo',
[
'comment', '% foo'
]
);
MT.testMode(
'tagComment',
'\\item% bar',
[
'tag', '\\item',
'comment', '% bar'
]
);
MT.testMode(
'commentTag',
' % \\item',
[
null, ' ',
'comment', '% \\item'
]
);
MT.testMode(
'commentLineBreak',
'%\nfoo',
[
'comment', '%',
null, 'foo'
]
);
MT.testMode(
'tagErrorCurly',
'\\begin}{',
[
'tag', '\\begin',
'error', '}',
'bracket', '{'
]
);
MT.testMode(
'tagErrorSquare',
'\\item]{',
[
'tag', '\\item',
'error', ']',
'bracket', '{'
]
);
MT.testMode(
'commentCurly',
'% }',
[
'comment', '% }'
]
);
MT.testMode(
'tagHash',
'the \\# key',
[
null, 'the ',
'tag', '\\#',
null, ' key'
]
);
MT.testMode(
'tagNumber',
'a \\$5 stetson',
[
null, 'a ',
'tag', '\\$',
'atom', 5,
null, ' stetson'
]
);
MT.testMode(
'tagPercent',
'100\\% beef',
[
'atom', '100',
'tag', '\\%',
null, ' beef'
]
);
MT.testMode(
'tagAmpersand',
'L \\& N',
[
null, 'L ',
'tag', '\\&',
null, ' N'
]
);
MT.testMode(
'tagUnderscore',
'foo\\_bar',
[
null, 'foo',
'tag', '\\_',
null, 'bar'
]
);
MT.testMode(
'tagBracketOpen',
'\\emph{\\{}',
[
'tag', '\\emph',
'bracket', '{',
'tag', '\\{',
'bracket', '}'
]
);
MT.testMode(
'tagBracketClose',
'\\emph{\\}}',
[
'tag', '\\emph',
'bracket', '{',
'tag', '\\}',
'bracket', '}'
]
);
MT.testMode(
'tagLetterNumber',
'section \\S1',
[
null, 'section ',
'tag', '\\S',
'atom', '1'
]
);
MT.testMode(
'textTagNumber',
'para \\P2',
[
null, 'para ',
'tag', '\\P',
'atom', '2'
]
);
MT.testMode(
'thinspace',
'x\\,y', // thinspace
[
null, 'x',
'tag', '\\,',
null, 'y'
]
);
MT.testMode(
'thickspace',
'x\\;y', // thickspace
[
null, 'x',
'tag', '\\;',
null, 'y'
]
);
MT.testMode(
'negativeThinspace',
'x\\!y', // negative thinspace
[
null, 'x',
'tag', '\\!',
null, 'y'
]
);
MT.testMode(
'periodNotSentence',
'J.\\ L.\\ is', // period not ending a sentence
[
null, 'J.\\ L.\\ is'
]
); // maybe could be better
MT.testMode(
'periodSentence',
'X\\@. The', // period ending a sentence
[
null, 'X',
'tag', '\\@',
null, '. The'
]
);
MT.testMode(
'italicCorrection',
'{\\em If\\/} I', // italic correction
[
'bracket', '{',
'tag', '\\em',
null, ' If',
'tag', '\\/',
'bracket', '}',
null, ' I'
]
);
MT.testMode(
'tagBracket',
'\\newcommand{\\pop}',
[
'tag', '\\newcommand',
'bracket', '{',
'tag', '\\pop',
'bracket', '}'
]
);
| gpl-2.0 |
TPETb/TPPPTX | src/TPPPTX/Type/Presentation/Main/Complex/Placeholder.php | 1798 | <?php
/**
* Created by PhpStorm.
* User: alex
* Date: 6/15/14
* Time: 6:02 PM
*/
namespace TPPPTX\Type\Presentation\Main\Complex;
use TPPPTX\Type\ComplexAbstract;
use TPPPTX\Type\Presentation\Main\Simple\Direction;
use TPPPTX\Type\Presentation\Main\Simple\PlaceholderSize;
use TPPPTX\Type\Presentation\Main\Simple\PlaceholderType;
/**
* Class Placeholder
* <xsd:complexType name="CT_Placeholder">
* <xsd:sequence>
* <xsd:element name="extLst" type="CT_ExtensionListModify" minOccurs="0" maxOccurs="1"/>
* </xsd:sequence>
* <xsd:attribute name="type" type="ST_PlaceholderType" use="optional" default="obj"/>
* <xsd:attribute name="orient" type="ST_Direction" use="optional" default="horz"/>
* <xsd:attribute name="sz" type="ST_PlaceholderSize" use="optional" default="full"/>
* <xsd:attribute name="idx" type="xsd:unsignedInt" use="optional" default="0"/>
* <xsd:attribute name="hasCustomPrompt" type="xsd:boolean" use="optional" default="false"/>
* </xsd:complexType>
* @package TPPPTX\Type\Presentation\Main\Complex
*/
class Placeholder extends ComplexAbstract
{
/**
* @var array
*/
protected $sequence = array( // 'extLst' => 'Presentation\\Main\\Complex\\ExtensionListModify',
);
/**
* @param string $tagName
* @param array $attributes
* @param array $options
*/
function __construct($tagName = '', $attributes = array(), $options = array())
{
$this->attributes = array(
'type' => new PlaceholderType('obj'),
'orient' => new Direction('horz'),
'sz' => new PlaceholderSize('full'),
'idx' => 0,
'hasCustomPrompt' => 'false',
);
parent::__construct($tagName, $attributes, $options);
}
} | gpl-2.0 |
ClimateFAST/NetCDFHDFS | shared/src/test/java/se/kth/climate/fast/netcdf/testing/FileGeneratorTest.java | 4724 | /*
* Copyright (C) 2017 KTH Royal Institute of Technology
*
* 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.
*/
package se.kth.climate.fast.netcdf.testing;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.runners.MethodSorters;
import ucar.nc2.NetcdfFile;
/**
*
* @author Lars Kroll <lkroll@kth.se>
*/
@RunWith(JUnit4.class)
@FixMethodOrder(MethodSorters.DEFAULT)
@net.jcip.annotations.NotThreadSafe
public class FileGeneratorTest {
// public FileGeneratorTest() {
// }
private static final long MB = 1024 * 1024;
private final File dir;
{
dir = Files.createTempDir();
dir.deleteOnExit();
System.out.println("Generating instance of test" + dir.getAbsolutePath());
}
@Test
public void smallFileTest() {
System.out.println("Running test case small!");
try {
long size = 10 * MB;
FileGenerator fg = new FileGenerator(size);
Path p = dir.toPath();
Path fp = p.resolve("smallFile.nc");
File f = fp.toFile();
System.out.println("Creating file: " + f.getAbsolutePath());
f.createNewFile();
f.deleteOnExit();
fg.generate(f);
System.out.println("Generated file: " + f.getAbsolutePath());
NetcdfFile ncfile = NetcdfFile.open(f.getAbsolutePath());
Assert.assertTrue("File did not check out!", fg.check(ncfile));
ncfile.close();
System.out.println("Checked file: " + f.getAbsolutePath());
} catch (IOException ex) {
ex.printStackTrace(System.err);
Assert.fail(ex.getMessage());
}
System.out.println("Finished test case small!");
}
@Test
public void largeFileTest() {
System.out.println("Running test case large!");
try {
long size = 200 * MB;
FileGenerator fg = new FileGenerator(size);
Path p = dir.toPath();
Path fp = p.resolve("largeFile.nc");
File f = fp.toFile();
System.out.println("Creating file: " + f.getAbsolutePath());
f.createNewFile();
f.deleteOnExit();
fg.generate(f);
System.out.println("Generated file: " + f.getAbsolutePath());
NetcdfFile ncfile = NetcdfFile.open(f.getAbsolutePath());
Assert.assertTrue("File did not check out!", fg.check(ncfile));
ncfile.close();
System.out.println("Checked file: " + f.getAbsolutePath());
} catch (IOException ex) {
ex.printStackTrace(System.err);
Assert.fail(ex.getMessage());
}
System.out.println("Finished test case large!");
}
@Test
public void blockedFileTest() {
System.out.println("Running test case blocked!");
try {
long size = 200 * MB;
FileGenerator fg = new FileGenerator(size);
List<Path> files = fg.generateBlocks(dir, 3);
System.out.println("Generated files: " + Iterables.toString(files));
List<NetcdfFile> ncfiles = new ArrayList<>(files.size());
for (Path p : files) {
File f = p.toFile();
f.deleteOnExit();
NetcdfFile ncfile = NetcdfFile.open(p.toString());
ncfiles.add(ncfile);
}
Assert.assertTrue("Files did not check out!", fg.checkBlocks(ncfiles));
for (NetcdfFile ncfile : ncfiles) {
ncfile.close();
}
} catch (IOException ex) {
ex.printStackTrace(System.err);
Assert.fail(ex.getMessage());
}
System.out.println("Finished test case blocked!");
}
}
| gpl-2.0 |
allendav/wp-calypso | client/state/ui/editor/test/reducer.js | 1134 | /**
* External dependencies
*/
import { expect } from 'chai';
/**
* Internal dependencies
*/
import { EDITOR_POST_ID_SET, EDITOR_SHOW_DRAFTS_TOGGLE } from 'state/action-types';
import reducer, { postId, showDrafts } from '../reducer';
describe( 'reducer', () => {
it( 'should export expected reducer keys', () => {
expect( reducer( undefined, {} ) ).to.have.keys( [
'postId',
'showDrafts',
'media',
'contactForm'
] );
} );
describe( '#postId()', () => {
it( 'should default to null', () => {
const state = postId( undefined, {} );
expect( state ).to.be.null;
} );
it( 'should track editor post ID', () => {
const state = postId( undefined, {
type: EDITOR_POST_ID_SET,
postId: 184
} );
expect( state ).to.equal( 184 );
} );
} );
describe( '#showDrafts()', () => {
it( 'should default to false', () => {
const state = showDrafts( undefined, {} );
expect( state ).to.be.false;
} );
it( 'should track toggled state', () => {
const state = showDrafts( undefined, {
type: EDITOR_SHOW_DRAFTS_TOGGLE
} );
expect( state ).to.be.true;
} );
} );
} );
| gpl-2.0 |
ntmcminn/alfresco-pdf-a-transform-action | pdf-archival-share/src/main/resources/META-INF/pdfarchival/components/doclib/pdfarchival-doclib-actions.js | 811 | if(typeof PDFArchive == "undefined" || !PDFArchive)
{
var PDFArchive = {};
}
PDFArchive.Util = {};
(function()
{
PDFArchive.Util.HideDependentControls = function(element, htmlIdPrefix)
{
// get the field html id
var fieldHtmlId = element.id;
// set the value of the hidden field
var value = YAHOO.util.Dom.get(fieldHtmlId).checked;
YAHOO.util.Dom.get(fieldHtmlId + "-hidden").value = value;
// find and hide the dependent controls
var controls = YAHOO.util.Dom.get(fieldHtmlId + "-tohide").value.split(",");
for(index in controls)
{
var control = new YAHOO.util.Dom.get((htmlIdPrefix + "_" + controls[index]));
var container = control.parentElement;
if(value)
{
container.style.display = 'none';
}
else
{
container.style.display = 'block';
}
}
}
})();
| gpl-2.0 |
mambax7/wflinks | admin/mygroupperm.php | 4628 | <?php
use Xmf\Request;
/**
* @param $db
* @param $gperm_modid
* @param null $gperm_name
* @param null $gperm_itemid
*
* @return bool
*/
function myDeleteByModule(\XoopsDatabase $db, $gperm_modid, $gperm_name = null, $gperm_itemid = null)
{
$criteria = new \CriteriaCompo(new \Criteria('gperm_modid', (int)$gperm_modid));
if (isset($gperm_name)) {
$criteria->add(new \Criteria('gperm_name', $gperm_name));
if (isset($gperm_itemid)) {
$criteria->add(new \Criteria('gperm_itemid', (int)$gperm_itemid));
}
}
$sql = 'DELETE FROM ' . $db->prefix('group_permission') . ' ' . $criteria->renderWhere();
if (!$result = $db->query($sql)) {
return false;
}
return true;
}
// require_once dirname(dirname(dirname(__DIR__))) . '/include/cp_header.php'; GIJ
$modid = Request::getInt('modid', 1, 'POST');
// we dont want system module permissions to be changed here ( 1 -> 0 GIJ)
if ($modid <= 0 || !is_object($xoopsUser) || !$xoopsUser->isAdmin($modid)) {
redirect_header(XOOPS_URL . '/user.php', 1, _NOPERM);
}
/** @var \XoopsModuleHandler $moduleHandler */
$moduleHandler = xoops_getHandler('module');
$module = $moduleHandler->get($modid);
if (!is_object($module) || !$module->getVar('isactive')) {
redirect_header(XOOPS_URL . '/admin.php', 1, _MODULENOEXIST);
}
/** @var \XoopsMemberHandler $memberHandler */
$memberHandler = xoops_getHandler('member');
$group_list = $memberHandler->getGroupList();
if (is_array($_POST['perms']) && !empty($_POST['perms'])) {
/** @var \XoopsGroupPermHandler $grouppermHandler */
$grouppermHandler = xoops_getHandler('groupperm');
foreach ($_POST['perms'] as $perm_name => $perm_data) {
foreach ($perm_data['itemname'] as $item_id => $item_name) {
// checking code
// echo "<pre>" ;
// var_dump( $_POST['perms'] ) ;
// exit ;
if (false !== myDeleteByModule($grouppermHandler->db, $modid, $perm_name, $item_id)) {
if (empty($perm_data['groups'])) {
continue;
}
foreach ($perm_data['groups'] as $group_id => $item_ids) {
// foreach ($item_ids as $item_id => $selected) {
$selected = $item_ids[$item_id] ?? 0;
if (1 == $selected) {
// make sure that all parent ids are selected as well
if ('' !== $perm_data['parents'][$item_id]) {
$parent_ids = explode(':', $perm_data['parents'][$item_id]);
foreach ($parent_ids as $pid) {
if (0 != $pid && !array_key_exists($pid, $item_ids)) {
// one of the parent items were not selected, so skip this item
$msg[] = sprintf(_MD_AM_PERMADDNG, '<b>' . $perm_name . '</b>', '<b>' . $perm_data['itemname'][$item_id] . '</b>', '<b>' . $group_list[$group_id] . '</b>') . ' (' . _MD_AM_PERMADDNGP . ')';
continue 2;
}
}
}
$gperm = $grouppermHandler->create();
$gperm->setVar('gperm_groupid', $group_id);
$gperm->setVar('gperm_name', $perm_name);
$gperm->setVar('gperm_modid', $modid);
$gperm->setVar('gperm_itemid', $item_id);
if ($grouppermHandler->insert($gperm)) {
$msg[] = sprintf(_MD_AM_PERMADDOK, '<b>' . $perm_name . '</b>', '<b>' . $perm_data['itemname'][$item_id] . '</b>', '<b>' . $group_list[$group_id] . '</b>');
} else {
$msg[] = sprintf(_MD_AM_PERMADDNG, '<b>' . $perm_name . '</b>', '<b>' . $perm_data['itemname'][$item_id] . '</b>', '<b>' . $group_list[$group_id] . '</b>');
}
unset($gperm);
}
}
} else {
$msg[] = sprintf(_MD_AM_PERMRESETNG, $module->getVar('name'));
}
}
}
}
/*
$backlink = XOOPS_URL.'/admin.php';
if ($module->getVar('hasadmin')) {
$adminindex = $module->getInfo('adminindex');
if ($adminindex) {
$backlink = XOOPS_URL.'/modules/'.$module->getVar('dirname').'/'.$adminindex;
}
}
$msg[] = '<br><br><a href="'.$backlink.'">'._BACK.'</a>';
xoops_cp_header();
xoops_result($msg);
xoops_cp_footer(); GIJ */
| gpl-2.0 |
tonnrueter/pymca_devel | PyMca/HDF5Stack1D.py | 25286 | #/*##########################################################################
# Copyright (C) 2004-2012 European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF by the Software group.
#
# This toolkit 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.
#
# PyMca 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
# PyMca; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# PyMca follows the dual licensing model of Riverbank's PyQt and cannot be
# used as a free plugin for a non-free program.
#
# Please contact the ESRF industrial unit (industry@esrf.fr) if this license
# is a problem for you.
#############################################################################*/
import posixpath
import numpy
import h5py
try:
from PyMca import DataObject
from PyMca import PhysicalMemory
except ImportError:
print("HDF5Stack1D importing DataObject from local directory!")
import DataObject
import PhysicalMemory
try:
from PyMca import NexusDataSource
except ImportError:
print("HDF5Stack1D importing NexusDataSource from local directory!")
import NexusDataSource
DEBUG = 0
SOURCE_TYPE = "HDF5Stack1D"
class HDF5Stack1D(DataObject.DataObject):
def __init__(self, filelist, selection,
scanlist=None,
dtype=None):
DataObject.DataObject.__init__(self)
#the data type of the generated stack
self.__dtype0 = dtype
self.__dtype = dtype
if filelist is not None:
if selection is not None:
self.loadFileList(filelist, selection, scanlist)
def loadFileList(self, filelist, selection, scanlist=None):
"""
loadFileList(self, filelist, y, scanlist=None, monitor=None, x=None)
filelist is the list of file names belonging to the stack
selection is a dictionary with the keys x, y, m.
x is the path to the x data (the channels) in the spectrum,
without the first level "directory". It is unused (for now).
y is the path to the 1D data (the counts) in the spectrum,
without the first level "directory"
m is the path to the normalizing data (I0 or whatever)
without the first level "directory".
scanlist is the list of first level "directories" containing the 1D data
Example: The actual path has the form:
/whatever1/whatever2/counts
That means scanlist = ["/whatever1"]
and selection['y'] = "/whatever2/counts"
"""
# all the files in the same source
hdfStack = NexusDataSource.NexusDataSource(filelist)
#if there is more than one file, it is assumed all the files have
#the same structure.
tmpHdf = hdfStack._sourceObjectList[0]
entryNames = []
for key in tmpHdf["/"].keys():
if isinstance(tmpHdf["/"+key], h5py.Group):
entryNames.append(key)
# built the selection in terms of HDF terms
# for the time being, the only the firs item in x selection used
xSelection = selection['x']
if type(xSelection) == type([]):
if len(xSelection):
xSelection = xSelection[0]
else:
xSelection = None
else:
xSelection = None
# only one y is taken
ySelection = selection['y']
if type(ySelection) == type([]):
ySelection = ySelection[0]
# monitor selection
mSelection = selection['m']
if type(mSelection) == type([]):
if len(mSelection):
mSelection = mSelection[0]
else:
mSelection = None
else:
mSelection = None
# deal with the pathological case where the scanlist corresponds
# to a selected top level dataset
if len(entryNames) == 0:
if scanlist is not None:
if len(scanlist) == 1:
if scanlist[0] == ySelection:
scanlist = None
if scanlist in [None, []]:
#if the scanlist is None, it is assumed we are interested on all
#the scans containing the selection, not that all the scans
#contain the selection.
scanlist = []
if 0:
JUST_KEYS = False
#expect same entry names in the files
for entry in entryNames:
path = "/"+entry + ySelection
dirname = posixpath.dirname(path)
base = posixpath.basename(path)
try:
if base in tmpHdf[dirname].keys():
scanlist.append(entry)
except:
pass
else:
JUST_KEYS = True
#expect same structure in the files
if len(entryNames):
i = 0
for entry in entryNames:
i += 1
path = "/"+entry + ySelection
dirname = posixpath.dirname(path)
base = posixpath.basename(path)
try:
if base in tmpHdf[dirname].keys():
scanlist.append("1.%d" % i)
except:
pass
if not len(scanlist):
path = "/" + ySelection
dirname = posixpath.dirname(path)
base = posixpath.basename(path)
try:
if base in tmpHdf[dirname].keys():
JUST_KEYS = False
scanlist.append("")
except:
#it will crash later on
pass
else:
JUST_KEYS = False
scanlist.append("")
else:
try:
number, order = [int(x) for x in scanlist[0].split(".")]
JUST_KEYS = True
except:
JUST_KEYS = False
if not JUST_KEYS:
for scan in scanlist:
if scan.startswith("/"):
t = scan[1:]
else:
t = scan
if t not in entryNames:
raise ValueError("Entry %s not in file" % scan)
nFiles = len(filelist)
nScans = len(scanlist)
if JUST_KEYS:
if not nScans:
raise IOError("No entry contains the required data")
#Now is to decide the number of mca ...
#I assume all the scans contain the same number of mca
if JUST_KEYS:
path = "/" + entryNames[int(scanlist[0].split(".")[-1])-1] + ySelection
if mSelection is not None:
mpath = "/" + entryNames[int(scanlist[0].split(".")[-1])-1] + mSelection
if xSelection is not None:
xpath = "/" + entryNames[int(scanlist[0].split(".")[-1])-1] + xSelection
else:
path = scanlist[0] + ySelection
if mSelection is not None:
mpath = scanlist[0] + mSelection
if xSelection is not None:
xpath = scanlist[0] + xSelection
yDataset = tmpHdf[path]
if self.__dtype is None:
self.__dtype = yDataset.dtype
#figure out the shape of the stack
shape = yDataset.shape
mcaIndex = selection.get('index', len(shape)-1)
if mcaIndex == -1:
mcaIndex = len(shape) - 1
dim0, dim1, mcaDim = self.getDimensions(nFiles, nScans, shape,
index=mcaIndex)
try:
if self.__dtype in [numpy.float32, numpy.int32]:
bytefactor = 4
elif self.__dtype in [numpy.int16, numpy.uint16]:
bytefactor = 2
elif self.__dtype in [numpy.int8, numpy.uint8]:
bytefactor = 1
else:
bytefactor = 8
neededMegaBytes = nFiles * dim0 * dim1 * mcaDim * bytefactor/(1024*1024.)
physicalMemory = PhysicalMemory.getPhysicalMemoryOrNone()
if physicalMemory is None:
# 5 Gigabytes should be a good compromise
physicalMemory = 6000
else:
physicalMemory /= (1024*1024.)
if (neededMegaBytes > (0.95*physicalMemory))\
and (nFiles == 1) and (len(shape) == 3):
if self.__dtype0 is None:
if (bytefactor == 8) and (neededMegaBytes < (2*physicalMemory)):
#try reading as float32
self.__dtype = numpy.float32
else:
raise MemoryError("Force dynamic loading")
else:
raise MemoryError("Force dynamic loading")
self.data = numpy.zeros((dim0, dim1, mcaDim), self.__dtype)
DONE = False
except (MemoryError, ValueError):
#some versions report ValueError instead of MemoryError
if (nFiles == 1) and (len(shape) == 3):
print("Attempting dynamic loading")
self.data = yDataset
if mSelection is not None:
mDataset = tmpHdf[mpath].value
self.monitor = [mDataset]
if xSelection is not None:
xDataset = tmpHdf[xpath].value
self.x = [xDataset]
if h5py.version.version < '2.0':
#prevent automatic closing keeping a reference
#to the open file
self._fileReference = hdfStack
DONE = True
else:
#what to do if the number of dimensions is only 2?
raise
if not DONE:
self.info["McaIndex"] = 2
n = 0
if dim0 == 1:
self.onBegin(dim1)
else:
self.onBegin(dim0)
self.incrProgressBar=0
for hdf in hdfStack._sourceObjectList:
entryNames = list(hdf["/"].keys())
for scan in scanlist:
if JUST_KEYS:
entryName = entryNames[int(scan.split(".")[-1])-1]
path = entryName + ySelection
if mSelection is not None:
mpath = entryName + mSelection
mDataset = hdf[mpath].value
if xSelection is not None:
xpath = entryName + xSelection
xDataset = hdf[xpath].value
else:
path = scan + ySelection
if mSelection is not None:
mpath = scan + mSelection
mDataset = hdf[mpath].value
if xSelection is not None:
xpath = scan + xSelection
xDataset = hdf[xpath].value
try:
yDataset = hdf[path]
tmpShape = yDataset.shape
totalBytes = numpy.ones((1,), yDataset.dtype).itemsize
for nItems in tmpShape:
totalBytes *= nItems
if (totalBytes/(1024.*1024.)) > 500:
#read from disk
IN_MEMORY = False
else:
#read the data into memory
yDataset = hdf[path].value
IN_MEMORY = True
except (MemoryError, ValueError):
yDataset = hdf[path]
IN_MEMORY = False
nMcaInYDataset = 1
for dim in yDataset.shape:
nMcaInYDataset *= dim
nMcaInYDataset = int(nMcaInYDataset/mcaDim)
if mcaIndex != 0:
if IN_MEMORY:
yDataset.shape = -1, mcaDim
if mSelection is not None:
case = -1
nMonitorData = 1
for v in mDataset.shape:
nMonitorData *= v
if nMonitorData == nMcaInYDataset:
mDataset.shape = nMcaInYDataset
case = 0
elif nMonitorData == (nMcaInYDataset * mcaDim):
case = 1
mDataset.shape = nMcaInYDataset, mcaDim
if case == -1:
raise ValueError(\
"I do not know how to handle this monitor data")
if (len(yDataset.shape) == 3) and\
(dim1 == yDataset.shape[1]):
mca = 0
deltaI = int(yDataset.shape[1]/dim1)
for ii in range(yDataset.shape[0]):
i = int(n/dim1)
yData = yDataset[ii:(ii+1)]
yData.shape = -1, mcaDim
if mSelection is not None:
if case == 0:
mData = numpy.outer(mDataset[mca:(mca+dim1)],
numpy.ones((mcaDim)))
self.data[i, :, :] = yData/mData
elif case == 1:
mData = mDataset[mca:(mca+dim1), :]
mData.shape = -1, mcaDim
self.data[i, :, :] = yData/mData
else:
self.data[i:(i+deltaI), :] = yData
n += yDataset.shape[1]
mca += dim1
else:
for mca in range(nMcaInYDataset):
i = int(n/dim1)
j = n % dim1
if len(yDataset.shape) == 3:
ii = int(mca/yDataset.shape[1])
jj = mca % yDataset.shape[1]
yData = yDataset[ii, jj]
elif len(yDataset.shape) == 2:
yData = yDataset[mca,:]
elif len(yDataset.shape) == 1:
yData = yDataset
if mSelection is not None:
if case == 0:
self.data[i, j, :] = yData/mDataset[mca]
elif case == 1:
self.data[i, j, :] = yData/mDataset[mca, :]
else:
self.data[i, j, :] = yData
n += 1
else:
if mSelection is not None:
case = -1
nMonitorData = 1
for v in mDataset.shape:
nMonitorData *= v
if nMonitorData == yDataset.shape[0]:
case = 3
mDataset.shape = yDataset.shape[0]
elif nMonitorData == nMcaInYDataset:
mDataset.shape = nMcaInYDataset
case = 0
#elif nMonitorData == (yDataset.shape[1] * yDataset.shape[2]):
# case = 1
# mDataset.shape = yDataset.shape[1], yDataset.shape[2]
if case == -1:
raise ValueError(\
"I do not know how to handle this monitor data")
if IN_MEMORY:
yDataset.shape = mcaDim, -1
if len(yDataset.shape) != 3:
for mca in range(nMcaInYDataset):
i = int(n/dim1)
j = n % dim1
if len(yDataset.shape) == 3:
ii = int(mca/yDataset.shape[2])
jj = mca % yDataset.shape[2]
yData = yDataset[:, ii, jj]
elif len(yDataset.shape) == 2:
yData = yDataset[:, mca]
elif len(yDataset.shape) == 1:
yData = yDataset[:]
if mSelection is not None:
if case == 0:
self.data[i, j, :] = yData/mDataset[mca]
elif case == 1:
self.data[i, j, :] = yData/mDataset[:, mca]
elif case == 3:
self.data[i, j, :] = yData/mDataset
else:
self.data[i, j, :] = yData
n += 1
else:
#stack of images to be read as MCA
for nImage in range(yDataset.shape[0]):
tmp = yDataset[nImage:(nImage+1)]
if len(tmp.shape) == 3:
i = int(n/dim1)
j = n % dim1
if 0:
#this loop is extremely SLOW!!!(and useless)
for ii in range(tmp.shape[1]):
for jj in range(tmp.shape[2]):
self.data[i+ii, j+jj, nImage] = tmp[0, ii, jj]
else:
self.data[i:i+tmp.shape[1],
j:j+tmp.shape[2], nImage] = tmp[0]
if mSelection is not None:
for mca in range(yDataset.shape[0]):
i = int(n/dim1)
j = n % dim1
yData = self.data[i, j, :]
if case == 0:
self.data[i, j, :] = yData/mDataset[mca]
elif case == 1:
self.data[i, j, :] = yData/mDataset[:, mca]
n += 1
else:
n += tmp.shape[1] * tmp.shape[2]
if dim0 == 1:
self.onProgress(j)
if dim0 != 1:
self.onProgress(i)
self.onEnd()
else:
self.info["McaIndex"] = mcaIndex
self.info["SourceType"] = SOURCE_TYPE
self.info["SourceName"] = filelist
self.info["Size"] = 1
self.info["NumberOfFiles"] = 1
if mcaIndex == 0:
self.info["FileIndex"] = 1
else:
self.info["FileIndex"] = 0
self.info['McaCalib'] = [ 0.0, 1.0, 0.0]
self.info['Channel0'] = 0
shape = self.data.shape
for i in range(len(shape)):
key = 'Dim_%d' % (i+1,)
self.info[key] = shape[i]
if xSelection is not None:
if xDataset.size == shape[self.info['McaIndex']]:
self.x = [xDataset.reshape(-1)]
else:
print("Ignoring xSelection")
def getDimensions(self, nFiles, nScans, shape, index=None):
#some body may want to overwrite this
"""
Returns the shape of the final stack as (Dim0, Dim1, Nchannels)
"""
if index is None:
index = -1
if index == -1:
index = len(shape) - 1
if DEBUG:
print("INDEX = %d" % index)
#figure out the shape of the stack
if len(shape) == 0:
#a scalar?
raise ValueError("Selection corresponds to a scalar")
elif len(shape) == 1:
#nchannels
nMca = 1
elif len(shape) == 2:
if index == 0:
#npoints x nchannels
nMca = shape[1]
else:
#npoints x nchannels
nMca = shape[0]
elif len(shape) == 3:
if index in [2, -1]:
#dim1 x dim2 x nchannels
nMca = shape[0] * shape[1]
elif index == 0:
nMca = shape[1] * shape[2]
else:
raise IndexError("Only first and last dimensions handled")
else:
nMca = 1
for i in range(len(shape)):
if i == index:
continue
nMca *= shape[i]
mcaDim = shape[index]
if DEBUG:
print("nMca = %d" % nMca)
print("mcaDim = ", mcaDim)
# HDF allows to work directly from the files without loading
# them into memory.
if (nScans == 1) and (nFiles > 1):
if nMca == 1:
#specfile like case
dim0 = nFiles
dim1 = nMca * nScans # nScans is 1
else:
#ESRF EDF like case
dim0 = nFiles
dim1 = nMca * nScans # nScans is 1
elif (nScans == 1) and (nFiles == 1):
if nMca == 1:
#specfile like single mca
dim0 = nFiles # it is 1
dim1 = nMca * nScans # nScans is 1
elif len(shape) == 2:
dim0 = nFiles # it is 1
dim1 = nMca * nScans # nScans is 1
elif len(shape) == 3:
if index == 0:
dim0 = shape[1]
dim1 = shape[2]
else:
dim0 = shape[0]
dim1 = shape[1]
else:
#specfile like multiple mca
dim0 = nFiles # it is 1
dim1 = nMca * nScans # nScans is 1
elif (nScans > 1) and (nFiles == 1):
if nMca == 1:
#specfile like case
dim0 = nFiles
dim1 = nMca * nScans
elif nMca > 1:
if len(shape) == 1:
#specfile like case
dim0 = nFiles
dim1 = nMca * nScans
elif len(shape) == 2:
dim0 = nScans
dim1 = nMca #shape[0]
elif len(shape) == 3:
if (shape[0] == 1) or (shape[1] == 1):
dim0 = nScans
dim1 = nMca
else:
#The user will have to decide the shape
dim0 = 1
dim1 = nScans * nMca
else:
#The user will have to decide the shape
dim0 = 1
dim1 = nScans * nMca
elif (nScans > 1) and (nFiles > 1):
dim0 = nFiles
dim1 = nMca * nScans
else:
#I should not reach this point
raise ValueError("Unhandled case")
return dim0, dim1, shape[index]
def onBegin(self, n):
pass
def onProgress(self, n):
pass
def onEnd(self):
pass
| gpl-2.0 |
pierrewillenbrock/dolphin | Source/Core/Core/DSP/Interpreter/DSPInterpreter.cpp | 19577 | // Copyright 2008 Dolphin Emulator Project
// Copyright 2004 Duddie & Tratax
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "Core/DSP/Interpreter/DSPInterpreter.h"
#include "Common/Assert.h"
#include "Common/CommonTypes.h"
#include "Common/Logging/Log.h"
#include "Core/DSP/DSPAnalyzer.h"
#include "Core/DSP/DSPCore.h"
#include "Core/DSP/DSPTables.h"
#include "Core/DSP/Interpreter/DSPIntTables.h"
namespace DSP::Interpreter
{
// Not needed for game ucodes (it slows down interpreter + easier to compare int VS
// dspjit64 without it)
//#define PRECISE_BACKLOG
Interpreter::Interpreter(DSPCore& dsp) : m_dsp_core{dsp}
{
InitInstructionTables();
}
Interpreter::~Interpreter() = default;
void Interpreter::ExecuteInstruction(const UDSPInstruction inst)
{
const DSPOPCTemplate* opcode_template = GetOpTemplate(inst);
if (opcode_template->extended)
{
(this->*GetExtOp(inst))(inst);
}
(this->*GetOp(inst))(inst);
if (opcode_template->extended)
{
ApplyWriteBackLog();
}
}
void Interpreter::Step()
{
auto& state = m_dsp_core.DSPState();
m_dsp_core.CheckExceptions();
state.AdvanceStepCounter();
const u16 opc = state.FetchInstruction();
ExecuteInstruction(UDSPInstruction{opc});
const auto pc = state.pc;
if (state.GetAnalyzer().IsLoopEnd(static_cast<u16>(pc - 1)))
HandleLoop();
}
// Used by thread mode.
int Interpreter::RunCyclesThread(int cycles)
{
auto& state = m_dsp_core.DSPState();
while (true)
{
if ((state.cr & CR_HALT) != 0)
return 0;
if (state.external_interrupt_waiting.exchange(false, std::memory_order_acquire))
{
m_dsp_core.CheckExternalInterrupt();
}
Step();
cycles--;
if (cycles < 0)
return 0;
}
}
// This one has basic idle skipping, and checks breakpoints.
int Interpreter::RunCyclesDebug(int cycles)
{
auto& state = m_dsp_core.DSPState();
// First, let's run a few cycles with no idle skipping so that things can progress a bit.
for (int i = 0; i < 8; i++)
{
if ((state.cr & CR_HALT) != 0)
return 0;
if (m_dsp_core.BreakPoints().IsAddressBreakPoint(state.pc))
{
m_dsp_core.SetState(State::Stepping);
return cycles;
}
Step();
cycles--;
if (cycles < 0)
return 0;
}
while (true)
{
// Next, let's run a few cycles with idle skipping, so that we can skip
// idle loops.
for (int i = 0; i < 8; i++)
{
if ((state.cr & CR_HALT) != 0)
return 0;
if (m_dsp_core.BreakPoints().IsAddressBreakPoint(state.pc))
{
m_dsp_core.SetState(State::Stepping);
return cycles;
}
if (state.GetAnalyzer().IsIdleSkip(state.pc))
return 0;
Step();
cycles--;
if (cycles < 0)
return 0;
}
// Now, lets run some more without idle skipping.
for (int i = 0; i < 200; i++)
{
if (m_dsp_core.BreakPoints().IsAddressBreakPoint(state.pc))
{
m_dsp_core.SetState(State::Stepping);
return cycles;
}
Step();
cycles--;
if (cycles < 0)
return 0;
// We don't bother directly supporting pause - if the main emu pauses,
// it just won't call this function anymore.
}
}
}
// Used by non-thread mode. Meant to be efficient.
int Interpreter::RunCycles(int cycles)
{
auto& state = m_dsp_core.DSPState();
// First, let's run a few cycles with no idle skipping so that things can
// progress a bit.
for (int i = 0; i < 8; i++)
{
if ((state.cr & CR_HALT) != 0)
return 0;
Step();
cycles--;
if (cycles < 0)
return 0;
}
while (true)
{
// Next, let's run a few cycles with idle skipping, so that we can skip
// idle loops.
for (int i = 0; i < 8; i++)
{
if ((state.cr & CR_HALT) != 0)
return 0;
if (state.GetAnalyzer().IsIdleSkip(state.pc))
return 0;
Step();
cycles--;
if (cycles < 0)
return 0;
}
// Now, lets run some more without idle skipping.
for (int i = 0; i < 200; i++)
{
Step();
cycles--;
if (cycles < 0)
return 0;
// We don't bother directly supporting pause - if the main emu pauses,
// it just won't call this function anymore.
}
}
}
// NOTE: These have nothing to do with SDSP::r::cr!
void Interpreter::WriteCR(u16 val)
{
// reset
if ((val & CR_RESET) != 0)
{
INFO_LOG_FMT(DSPLLE, "DSP_CONTROL RESET");
m_dsp_core.Reset();
val &= ~CR_RESET;
}
// init
else if (val == CR_HALT)
{
// HAX!
// OSInitAudioSystem ucode should send this mail - not DSP core itself
INFO_LOG_FMT(DSPLLE, "DSP_CONTROL INIT");
m_dsp_core.SetInitHax(true);
val |= CR_INIT;
}
// update cr
m_dsp_core.DSPState().cr = val;
}
u16 Interpreter::ReadCR()
{
auto& state = m_dsp_core.DSPState();
if ((state.pc & 0x8000) != 0)
{
state.cr |= CR_INIT;
}
else
{
state.cr &= ~CR_INIT;
}
return state.cr;
}
void Interpreter::SetSRFlag(u16 flag)
{
m_dsp_core.DSPState().SetSRFlag(flag);
}
bool Interpreter::IsSRFlagSet(u16 flag) const
{
return m_dsp_core.DSPState().IsSRFlagSet(flag);
}
bool Interpreter::CheckCondition(u8 condition) const
{
const auto IsCarry = [this] { return IsSRFlagSet(SR_CARRY); };
const auto IsOverflow = [this] { return IsSRFlagSet(SR_OVERFLOW); };
const auto IsOverS32 = [this] { return IsSRFlagSet(SR_OVER_S32); };
const auto IsLess = [this] {
const auto& state = m_dsp_core.DSPState();
return (!(m_dsp_core.DSPState().r.sr & SR_OVERFLOW) != !(m_dsp_core.DSPState().r.sr & SR_SIGN));
};
const auto IsZero = [this] { return IsSRFlagSet(SR_ARITH_ZERO); };
const auto IsLogicZero = [this] { return IsSRFlagSet(SR_LOGIC_ZERO); };
const auto IsConditionA = [this] {
return (IsSRFlagSet(SR_OVER_S32) || IsSRFlagSet(SR_TOP2BITS)) && !IsSRFlagSet(SR_ARITH_ZERO);
};
switch (condition & 0xf)
{
case 0xf: // Always true.
return true;
case 0x0: // GE - Greater Equal
return !IsLess();
case 0x1: // L - Less
return IsLess();
case 0x2: // G - Greater
return !IsLess() && !IsZero();
case 0x3: // LE - Less Equal
return IsLess() || IsZero();
case 0x4: // NZ - Not Zero
return !IsZero();
case 0x5: // Z - Zero
return IsZero();
case 0x6: // NC - Not carry
return !IsCarry();
case 0x7: // C - Carry
return IsCarry();
case 0x8: // ? - Not over s32
return !IsOverS32();
case 0x9: // ? - Over s32
return IsOverS32();
case 0xa: // ?
return IsConditionA();
case 0xb: // ?
return !IsConditionA();
case 0xc: // LNZ - Logic Not Zero
return !IsLogicZero();
case 0xd: // LZ - Logic Zero
return IsLogicZero();
case 0xe: // 0 - Overflow
return IsOverflow();
default:
return true;
}
}
u16 Interpreter::IncrementAddressRegister(u16 reg) const
{
auto& state = m_dsp_core.DSPState();
const u32 ar = state.r.ar[reg];
const u32 wr = state.r.wr[reg];
u32 nar = ar + 1;
if ((nar ^ ar) > ((wr | 1) << 1))
nar -= wr + 1;
return static_cast<u16>(nar);
}
u16 Interpreter::DecrementAddressRegister(u16 reg) const
{
const auto& state = m_dsp_core.DSPState();
const u32 ar = state.r.ar[reg];
const u32 wr = state.r.wr[reg];
u32 nar = ar + wr;
if (((nar ^ ar) & ((wr | 1) << 1)) > wr)
nar -= wr + 1;
return static_cast<u16>(nar);
}
u16 Interpreter::IncreaseAddressRegister(u16 reg, s16 ix_) const
{
const auto& state = m_dsp_core.DSPState();
const u32 ar = state.r.ar[reg];
const u32 wr = state.r.wr[reg];
const s32 ix = ix_;
const u32 mx = (wr | 1) << 1;
u32 nar = ar + ix;
const u32 dar = (nar ^ ar ^ ix) & mx;
if (ix >= 0)
{
if (dar > wr) // Overflow
nar -= wr + 1;
}
else
{
// Underflow or below min for mask
if ((((nar + wr + 1) ^ nar) & dar) <= wr)
nar += wr + 1;
}
return static_cast<u16>(nar);
}
u16 Interpreter::DecreaseAddressRegister(u16 reg, s16 ix_) const
{
const auto& state = m_dsp_core.DSPState();
const u32 ar = state.r.ar[reg];
const u32 wr = state.r.wr[reg];
const s32 ix = ix_;
const u32 mx = (wr | 1) << 1;
u32 nar = ar - ix;
const u32 dar = (nar ^ ar ^ ~ix) & mx;
// (ix < 0 && ix != -0x8000)
if (static_cast<u32>(ix) > 0xFFFF8000)
{
if (dar > wr) // overflow
nar -= wr + 1;
}
else
{
// Underflow or below min for mask
if ((((nar + wr + 1) ^ nar) & dar) <= wr)
nar += wr + 1;
}
return static_cast<u16>(nar);
}
s32 Interpreter::GetLongACX(s32 reg) const
{
const auto& state = m_dsp_core.DSPState();
return static_cast<s32>((static_cast<u32>(state.r.ax[reg].h) << 16) | state.r.ax[reg].l);
}
s16 Interpreter::GetAXLow(s32 reg) const
{
return static_cast<s16>(m_dsp_core.DSPState().r.ax[reg].l);
}
s16 Interpreter::GetAXHigh(s32 reg) const
{
return static_cast<s16>(m_dsp_core.DSPState().r.ax[reg].h);
}
s64 Interpreter::GetLongAcc(s32 reg) const
{
const auto& state = m_dsp_core.DSPState();
return static_cast<s64>(state.r.ac[reg].val << 24) >> 24;
}
void Interpreter::SetLongAcc(s32 reg, s64 value)
{
auto& state = m_dsp_core.DSPState();
state.r.ac[reg].val = static_cast<u64>(value);
}
s16 Interpreter::GetAccLow(s32 reg) const
{
return static_cast<s16>(m_dsp_core.DSPState().r.ac[reg].l);
}
s16 Interpreter::GetAccMid(s32 reg) const
{
return static_cast<s16>(m_dsp_core.DSPState().r.ac[reg].m);
}
s16 Interpreter::GetAccHigh(s32 reg) const
{
return static_cast<s16>(m_dsp_core.DSPState().r.ac[reg].h);
}
s64 Interpreter::GetLongProduct() const
{
const auto& state = m_dsp_core.DSPState();
s64 val = static_cast<s8>(static_cast<u8>(state.r.prod.h));
val <<= 32;
s64 low_prod = state.r.prod.m;
low_prod += state.r.prod.m2;
low_prod <<= 16;
low_prod |= state.r.prod.l;
val += low_prod;
return val;
}
s64 Interpreter::GetLongProductRounded() const
{
const s64 prod = GetLongProduct();
if ((prod & 0x10000) != 0)
return (prod + 0x8000) & ~0xffff;
else
return (prod + 0x7fff) & ~0xffff;
}
void Interpreter::SetLongProduct(s64 value)
{
// For accurate emulation, this is wrong - but the real prod registers behave
// in completely bizarre ways. Not needed to emulate them correctly for game ucodes.
m_dsp_core.DSPState().r.prod.val = static_cast<u64>(value & 0x000000FFFFFFFFFFULL);
}
s64 Interpreter::GetMultiplyProduct(u16 a, u16 b, u8 sign) const
{
s64 prod;
// Unsigned
if (sign == 1 && IsSRFlagSet(SR_MUL_UNSIGNED))
prod = static_cast<u32>(a * b);
else if (sign == 2 && IsSRFlagSet(SR_MUL_UNSIGNED)) // mixed
prod = a * static_cast<s16>(b);
else // Signed
prod = static_cast<s16>(a) * static_cast<s16>(b);
// Conditionally multiply by 2.
if (!IsSRFlagSet(SR_MUL_MODIFY))
prod <<= 1;
return prod;
}
s64 Interpreter::Multiply(u16 a, u16 b, u8 sign) const
{
return GetMultiplyProduct(a, b, sign);
}
s64 Interpreter::MultiplyAdd(u16 a, u16 b, u8 sign) const
{
return GetLongProduct() + GetMultiplyProduct(a, b, sign);
}
s64 Interpreter::MultiplySub(u16 a, u16 b, u8 sign) const
{
return GetLongProduct() - GetMultiplyProduct(a, b, sign);
}
s64 Interpreter::MultiplyMulX(u8 axh0, u8 axh1, u16 val1, u16 val2) const
{
s64 result;
if (axh0 == 0 && axh1 == 0)
result = Multiply(val1, val2, 1); // Unsigned support ON if both ax?.l regs are used
else if (axh0 == 0 && axh1 == 1)
result = Multiply(val1, val2, 2); // Mixed support ON (u16)axl.0 * (s16)axh.1
else if (axh0 == 1 && axh1 == 0)
result = Multiply(val2, val1, 2); // Mixed support ON (u16)axl.1 * (s16)axh.0
else
result = Multiply(val1, val2, 0); // Unsigned support OFF if both ax?.h regs are used
return result;
}
void Interpreter::UpdateSR16(s16 value, bool carry, bool overflow, bool over_s32)
{
auto& state = m_dsp_core.DSPState();
state.r.sr &= ~SR_CMP_MASK;
// 0x01
if (carry)
{
state.r.sr |= SR_CARRY;
}
// 0x02 and 0x80
if (overflow)
{
state.r.sr |= SR_OVERFLOW;
state.r.sr |= SR_OVERFLOW_STICKY;
}
// 0x04
if (value == 0)
{
state.r.sr |= SR_ARITH_ZERO;
}
// 0x08
if (value < 0)
{
state.r.sr |= SR_SIGN;
}
// 0x10
if (over_s32)
{
state.r.sr |= SR_OVER_S32;
}
// 0x20 - Checks if top bits of m are equal
if (((static_cast<u16>(value) >> 14) == 0) || ((static_cast<u16>(value) >> 14) == 3))
{
state.r.sr |= SR_TOP2BITS;
}
}
void Interpreter::UpdateSR64(s64 value, bool carry, bool overflow)
{
auto& state = m_dsp_core.DSPState();
state.r.sr &= ~SR_CMP_MASK;
// 0x01
if (carry)
{
state.r.sr |= SR_CARRY;
}
// 0x02 and 0x80
if (overflow)
{
state.r.sr |= SR_OVERFLOW;
state.r.sr |= SR_OVERFLOW_STICKY;
}
// 0x04
if (value == 0)
{
state.r.sr |= SR_ARITH_ZERO;
}
// 0x08
if (value < 0)
{
state.r.sr |= SR_SIGN;
}
// 0x10
if (value != static_cast<s32>(value))
{
state.r.sr |= SR_OVER_S32;
}
// 0x20 - Checks if top bits of m are equal
if (((value & 0xc0000000) == 0) || ((value & 0xc0000000) == 0xc0000000))
{
state.r.sr |= SR_TOP2BITS;
}
}
void Interpreter::UpdateSRLogicZero(bool value)
{
auto& state = m_dsp_core.DSPState();
if (value)
state.r.sr |= SR_LOGIC_ZERO;
else
state.r.sr &= ~SR_LOGIC_ZERO;
}
u16 Interpreter::OpReadRegister(int reg_)
{
const int reg = reg_ & 0x1f;
auto& state = m_dsp_core.DSPState();
switch (reg)
{
case DSP_REG_ST0:
case DSP_REG_ST1:
case DSP_REG_ST2:
case DSP_REG_ST3:
return state.PopStack(static_cast<StackRegister>(reg - DSP_REG_ST0));
case DSP_REG_AR0:
case DSP_REG_AR1:
case DSP_REG_AR2:
case DSP_REG_AR3:
return state.r.ar[reg - DSP_REG_AR0];
case DSP_REG_IX0:
case DSP_REG_IX1:
case DSP_REG_IX2:
case DSP_REG_IX3:
return state.r.ix[reg - DSP_REG_IX0];
case DSP_REG_WR0:
case DSP_REG_WR1:
case DSP_REG_WR2:
case DSP_REG_WR3:
return state.r.wr[reg - DSP_REG_WR0];
case DSP_REG_ACH0:
case DSP_REG_ACH1:
return state.r.ac[reg - DSP_REG_ACH0].h;
case DSP_REG_CR:
return state.r.cr;
case DSP_REG_SR:
return state.r.sr;
case DSP_REG_PRODL:
return state.r.prod.l;
case DSP_REG_PRODM:
return state.r.prod.m;
case DSP_REG_PRODH:
return state.r.prod.h;
case DSP_REG_PRODM2:
return state.r.prod.m2;
case DSP_REG_AXL0:
case DSP_REG_AXL1:
return state.r.ax[reg - DSP_REG_AXL0].l;
case DSP_REG_AXH0:
case DSP_REG_AXH1:
return state.r.ax[reg - DSP_REG_AXH0].h;
case DSP_REG_ACL0:
case DSP_REG_ACL1:
return state.r.ac[reg - DSP_REG_ACL0].l;
case DSP_REG_ACM0:
case DSP_REG_ACM1:
return state.r.ac[reg - DSP_REG_ACM0].m;
default:
ASSERT_MSG(DSP_INT, 0, "cannot happen");
return 0;
}
}
u16 Interpreter::OpReadRegisterAndSaturate(int reg) const
{
if (IsSRFlagSet(SR_40_MODE_BIT))
{
const s64 acc = GetLongAcc(reg);
if (acc != static_cast<s32>(acc))
{
if (acc > 0)
return 0x7fff;
else
return 0x8000;
}
return m_dsp_core.DSPState().r.ac[reg].m;
}
return m_dsp_core.DSPState().r.ac[reg].m;
}
void Interpreter::OpWriteRegister(int reg_, u16 val)
{
const int reg = reg_ & 0x1f;
auto& state = m_dsp_core.DSPState();
switch (reg)
{
// 8-bit sign extended registers. Should look at prod.h too...
case DSP_REG_ACH0:
case DSP_REG_ACH1:
// sign extend from the bottom 8 bits.
state.r.ac[reg - DSP_REG_ACH0].h = (u16)(s16)(s8)(u8)val;
break;
// Stack registers.
case DSP_REG_ST0:
case DSP_REG_ST1:
case DSP_REG_ST2:
case DSP_REG_ST3:
state.StoreStack(static_cast<StackRegister>(reg - DSP_REG_ST0), val);
break;
case DSP_REG_AR0:
case DSP_REG_AR1:
case DSP_REG_AR2:
case DSP_REG_AR3:
state.r.ar[reg - DSP_REG_AR0] = val;
break;
case DSP_REG_IX0:
case DSP_REG_IX1:
case DSP_REG_IX2:
case DSP_REG_IX3:
state.r.ix[reg - DSP_REG_IX0] = val;
break;
case DSP_REG_WR0:
case DSP_REG_WR1:
case DSP_REG_WR2:
case DSP_REG_WR3:
state.r.wr[reg - DSP_REG_WR0] = val;
break;
case DSP_REG_CR:
state.r.cr = val;
break;
case DSP_REG_SR:
state.r.sr = val;
break;
case DSP_REG_PRODL:
state.r.prod.l = val;
break;
case DSP_REG_PRODM:
state.r.prod.m = val;
break;
case DSP_REG_PRODH:
state.r.prod.h = val;
break;
case DSP_REG_PRODM2:
state.r.prod.m2 = val;
break;
case DSP_REG_AXL0:
case DSP_REG_AXL1:
state.r.ax[reg - DSP_REG_AXL0].l = val;
break;
case DSP_REG_AXH0:
case DSP_REG_AXH1:
state.r.ax[reg - DSP_REG_AXH0].h = val;
break;
case DSP_REG_ACL0:
case DSP_REG_ACL1:
state.r.ac[reg - DSP_REG_ACL0].l = val;
break;
case DSP_REG_ACM0:
case DSP_REG_ACM1:
state.r.ac[reg - DSP_REG_ACM0].m = val;
break;
}
}
void Interpreter::ConditionalExtendAccum(int reg)
{
if (reg != DSP_REG_ACM0 && reg != DSP_REG_ACM1)
return;
if (!IsSRFlagSet(SR_40_MODE_BIT))
return;
// Sign extend into whole accum.
auto& state = m_dsp_core.DSPState();
const u16 val = state.r.ac[reg - DSP_REG_ACM0].m;
state.r.ac[reg - DSP_REG_ACM0].h = (val & 0x8000) != 0 ? 0xFFFF : 0x0000;
state.r.ac[reg - DSP_REG_ACM0].l = 0;
}
// The ext op are writing their output into the backlog which is
// being applied to the real registers after the main op was executed
void Interpreter::ApplyWriteBackLog()
{
// Always make sure to have an extra entry at the end w/ -1 to avoid
// infinitive loops
for (int i = 0; m_write_back_log_idx[i] != -1; i++)
{
u16 value = m_write_back_log[i];
#ifdef PRECISE_BACKLOG
value |= OpReadRegister(m_write_back_log_idx[i]);
#endif
OpWriteRegister(m_write_back_log_idx[i], value);
// Clear back log
m_write_back_log_idx[i] = -1;
}
}
void Interpreter::WriteToBackLog(int i, int idx, u16 value)
{
m_write_back_log[i] = value;
m_write_back_log_idx[i] = idx;
}
// This function is being called in the main op after all input regs were read
// and before it writes into any regs. This way we can always use bitwise or to
// apply the ext command output, because if the main op didn't change the value
// then 0 | ext output = ext output and if it did then bitwise or is still the
// right thing to do
// Only needed for cases when mainop and extended are modifying the same ACC
// Games are not doing that + in motorola (similar DSP) dox this is forbidden to do.
void Interpreter::ZeroWriteBackLog()
{
#ifdef PRECISE_BACKLOG
// always make sure to have an extra entry at the end w/ -1 to avoid
// infinitive loops
for (int i = 0; m_write_back_log_idx[i] != -1; i++)
{
OpWriteRegister(m_write_back_log_idx[i], 0);
}
#endif
}
void Interpreter::ZeroWriteBackLogPreserveAcc([[maybe_unused]] u8 acc)
{
#ifdef PRECISE_BACKLOG
for (int i = 0; m_write_back_log_idx[i] != -1; i++)
{
// acc0
if (acc == 0 &&
((m_write_back_log_idx[i] == DSP_REG_ACL0) || (m_write_back_log_idx[i] == DSP_REG_ACM0) ||
(m_write_back_log_idx[i] == DSP_REG_ACH0)))
{
continue;
}
// acc1
if (acc == 1 &&
((m_write_back_log_idx[i] == DSP_REG_ACL1) || (m_write_back_log_idx[i] == DSP_REG_ACM1) ||
(m_write_back_log_idx[i] == DSP_REG_ACH1)))
{
continue;
}
OpWriteRegister(m_write_back_log_idx[i], 0);
}
#endif
}
void Interpreter::nop(const UDSPInstruction opc)
{
// The real nop is 0. Anything else is bad.
if (opc == 0)
return;
ERROR_LOG_FMT(DSPLLE, "LLE: Unrecognized opcode {:#06x}", opc);
}
} // namespace DSP::Interpreter
| gpl-2.0 |
DialloAbdourahamane/siteDepotProjet | wp-content/plugins/simple-press/admin/panel-permissions/forms/spa-permissions-add-permission-form.php | 5995 | <?php
/*
Simple:Press
Admin Permissions Add Permission Form
$LastChangedDate: 2012-11-18 11:04:10 -0700 (Sun, 18 Nov 2012) $
$Rev: 9312 $
*/
if (preg_match('#'.basename(__FILE__).'#', $_SERVER['PHP_SELF'])) die('Access denied - you cannot directly call this file');
function spa_permissions_add_permission_form() {
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#sfrolenew').ajaxForm({
target: '#sfmsgspot',
success: function() {
jQuery('#sfreloadpb').click();
jQuery('#sfmsgspot').fadeIn();
jQuery('#sfmsgspot').fadeOut(6000);
}
});
jQuery(function(jQuery){vtip();})
});
</script>
<?php
# Get correct tooltips file
$lang = WPLANG;
if (empty($lang)) $lang = 'en';
$ttpath = SPHELP.'admin/tooltips/admin-permissions-tips-'.$lang.'.php';
if (file_exists($ttpath) == false) $ttpath = SPHELP.'admin/tooltips/admin-permissions-tips-en.php';
if (file_exists($ttpath)) include_once($ttpath);
global $sfglobals;
spa_paint_options_init();
$ahahURL = SFHOMEURL."index.php?sp_ahah=permissions-loader&sfnonce=".wp_create_nonce('forum-ahah')."&saveform=addperm";
?>
<form action="<?php echo $ahahURL; ?>" method="post" id="sfrolenew" name="sfrolenew">
<?php
echo sp_create_nonce('forum-adminform_rolenew');
spa_paint_open_tab(spa_text('Permissions')." - ".spa_text('Add New Permission'));
spa_paint_open_panel();
spa_paint_open_fieldset(spa_text('Add New Permission'), 'true', 'create-new-permission-set', false);
?>
<table class="form-table">
<tr>
<td class="sflabel"><?php spa_etext("Permission Set Name") ?>: <br />
<input type="text" class="sfpostcontrol" size="45" name="role_name" value="" /></td>
<td class="sflabel"><?php spa_etext("Permission Set Description") ?>: <br/>
<input type="text" class="sfpostcontrol" size="85" name="role_desc" value="" /></td>
</tr>
<tr>
<td class="sflabel"><?php echo spa_text('Clone Existing Permission Set'); ?>
<br /><small><strong><?php echo spa_text('Select an existing Permission Set to Clone. Any settings below will be ignored.'); ?></strong></small>
</td>
<td class="sflabel"><?php spa_display_permission_select(); ?></td>
</tr>
</table>
<br /><p><strong><?php spa_etext("Permission Set Actions") ?>:</strong></p>
<?php
echo '<p><img src="'.SFADMINIMAGES.'sp_GuestPerm.png" alt="" width="16" height="16" align="top" />';
echo '<small> '.spa_text('Note: Action settings displaying this icon will be ignored for Guest Users').'</small>';
echo ' <img src="'.SFADMINIMAGES.'sp_GlobalPerm.png" alt="" width="16" height="16" align="top" />';
echo '<small> '.spa_text('Note: Action settings displaying this icon require enabling to use').'</small></p>';
sp_build_site_auths_cache();
$sql = "SELECT auth_id, auth_name, auth_cat, authcat_name FROM ".SFAUTHS."
JOIN ".SFAUTHCATS." ON ".SFAUTHS.".auth_cat = ".SFAUTHCATS.".authcat_id
WHERE active = 1
ORDER BY auth_cat, auth_id";
$authlist = spdb_select('set', $sql);
$firstitem = true;
$category = '';
$thiscol = 0;
?>
<!-- OPEN OUTER CONTAINER DIV -->
<div class="outershell" style="width: 100%;">
<?php
foreach($authlist as $a) {
if($category != $a->authcat_name) {
$category = $a->authcat_name;
if(!$firstitem) {
?>
<!-- CLOSE DOWN THE ENDS -->
</table><div class="clearboth"></div></div>
<?php
if($thiscol==3) {
?>
<div class="clearboth"></div>
<?php
$thiscol=0;
}
}
?>
<!-- OPEN NEW INNER DIV -->
<div class="innershell" style="width: 32%; float: left;padding: 10px 10px 0 0">
<!-- NEW INNER DETAIL TABLE -->
<table width="100%" border="0">
<tr><td colspan="2" class="permhead"><?php spa_etext($category); ?></td></tr>
<?php
$firstitem = false;
$thiscol++;
}
$auth_id = $a->auth_id;
$auth_name = $a->auth_name;
$button = 'b-'.$auth_id;
if ($sfglobals['auths'][$auth_id]->ignored || $sfglobals['auths'][$auth_id]->enabling) {
$span = '';
} else {
$span = ' colspan="2" ';
}
?>
<tr>
<td class="permentry">
<label for="sf<?php echo $button; ?>" class="sflabel">
<img align="top" style="float: right; border: 0pt none ; margin: -4px 5px 0px 3px; padding: 0;" class="vtip" title="<?php echo $tooltips[$auth_name]; ?>" src="<?php echo SFADMINIMAGES; ?>sp_Information.png" alt="" />
<?php spa_etext($sfglobals['auths'][$auth_id]->auth_desc); ?></label>
<input type="checkbox" name="<?php echo $button; ?>" id="sf<?php echo $button; ?>" />
<?php if ($span == '')
{ ?>
<td align="center" class="permentry" width="32px">
<?php }
if ($span == '') {
if ($sfglobals["auths"][$auth_id]->enabling)
{
echo '<img src="'.SFADMINIMAGES.'sp_GlobalPerm.png" alt="" width="16" height="16" title="'.spa_text('Requires Enabling').'" />';
}
echo '<img src="'.SFADMINIMAGES.'sp_GuestPerm.png" alt="" width="16" height="16" title="'.spa_text('Ignored for Guests').'" />';
echo '</td>';
} else {
?>
</td><td class="permentry" width="32px"></td>
<?php
}
?>
</tr>
<?php
}
?>
<!-- END CONTAINER DIV -->
</table></div><div class="clearboth"></div>
</div>
<?php
spa_paint_close_fieldset(false);
spa_paint_close_panel();
do_action('sph_perm_add_perm_panel');
spa_paint_close_tab();
?>
<div class="sfform-submit-bar">
<input type="submit" class="button-primary" id="saveit" name="saveit" value="<?php spa_etext('Create New Permission'); ?>" />
</div>
</form>
<div class="sfform-panel-spacer"></div>
<?php
}
?> | gpl-2.0 |
glibey/drupal8 | core/lib/Drupal/Core/Utility/Token.php | 11334 | <?php
/**
* @file
* Definition of Drupal\Core\Utility\Token.
*/
namespace Drupal\Core\Utility;
use Drupal\Core\Extension\ModuleHandlerInterface;
/**
* Drupal placeholder/token replacement system.
*
* API functions for replacing placeholders in text with meaningful values.
*
* For example: When configuring automated emails, an administrator enters
* standard text for the email. Variables like the title of a node and the date
* the email was sent can be entered as placeholders like [node:title] and
* [date:short]. When a Drupal module prepares to send the email, it can call
* the Token::replace() function, passing in the text. The token system will
* scan the text for placeholder tokens, give other modules an opportunity to
* replace them with meaningful text, then return the final product to the
* original module.
*
* Tokens follow the form: [$type:$name], where $type is a general class of
* tokens like 'node', 'user', or 'comment' and $name is the name of a given
* placeholder. For example, [node:title] or [node:created:since].
*
* In addition to raw text containing placeholders, modules may pass in an array
* of objects to be used when performing the replacement. The objects should be
* keyed by the token type they correspond to. For example:
*
* @code
* // Load a node and a user, then replace tokens in the text.
* $text = 'On [date:short], [user:name] read [node:title].';
* $node = node_load(1);
* $user = user_load(1);
*
* // [date:...] tokens use the current date automatically.
* $data = array('node' => $node, 'user' => $user);
* return Token::replace($text, $data);
* @endcode
*
* Some tokens may be chained in the form of [$type:$pointer:$name], where $type
* is a normal token type, $pointer is a reference to another token type, and
* $name is the name of a given placeholder. For example, [node:author:mail]. In
* that example, 'author' is a pointer to the 'user' account that created the
* node, and 'mail' is a placeholder available for any 'user'.
*
* @see Token::replace()
* @see hook_tokens()
* @see hook_token_info()
*/
class Token {
/**
* Token definitions.
*
* @var array|null
* An array of token definitions, or NULL when the definitions are not set.
*
* @see self::setInfo()
* @see self::getInfo()
* @see self::resetInfo()
*/
protected $tokenInfo;
/**
* The module handler service.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* Constructor.
*
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
*/
public function __construct(ModuleHandlerInterface $module_handler) {
$this->moduleHandler = $module_handler;
}
/**
* Replaces all tokens in a given string with appropriate values.
*
* @param string $text
* A string potentially containing replaceable tokens.
* @param array $data
* (optional) An array of keyed objects. For simple replacement scenarios
* 'node', 'user', and others are common keys, with an accompanying node or
* user object being the value. Some token types, like 'site', do not require
* any explicit information from $data and can be replaced even if it is
* empty.
* @param array $options
* (optional) A keyed array of settings and flags to control the token
* replacement process. Supported options are:
* - langcode: A language code to be used when generating locale-sensitive
* tokens.
* - callback: A callback function that will be used to post-process the
* array of token replacements after they are generated. For example, a
* module using tokens in a text-only email might provide a callback to
* strip HTML entities from token values before they are inserted into the
* final text.
* - clear: A boolean flag indicating that tokens should be removed from the
* final text if no replacement value can be generated.
* - sanitize: A boolean flag indicating that tokens should be sanitized for
* display to a web browser. Defaults to TRUE. Developers who set this
* option to FALSE assume responsibility for running
* \Drupal\Component\Utility\Xss::filter(),
* \Drupal\Component\Utility\String::checkPlain() or other appropriate
* scrubbing functions before displaying data to users.
*
* @return string
* Text with tokens replaced.
*/
public function replace($text, array $data = array(), array $options = array()) {
$text_tokens = $this->scan($text);
if (empty($text_tokens)) {
return $text;
}
$replacements = array();
foreach ($text_tokens as $type => $tokens) {
$replacements += $this->generate($type, $tokens, $data, $options);
if (!empty($options['clear'])) {
$replacements += array_fill_keys($tokens, '');
}
}
// Optionally alter the list of replacement values.
if (!empty($options['callback'])) {
$function = $options['callback'];
$function($replacements, $data, $options);
}
$tokens = array_keys($replacements);
$values = array_values($replacements);
return str_replace($tokens, $values, $text);
}
/**
* Builds a list of all token-like patterns that appear in the text.
*
* @param string $text
* The text to be scanned for possible tokens.
*
* @return array
* An associative array of discovered tokens, grouped by type.
*/
public function scan($text) {
// Matches tokens with the following pattern: [$type:$name]
// $type and $name may not contain [ ] characters.
// $type may not contain : or whitespace characters, but $name may.
preg_match_all('/
\[ # [ - pattern start
([^\s\[\]:]*) # match $type not containing whitespace : [ or ]
: # : - separator
([^\[\]]*) # match $name not containing [ or ]
\] # ] - pattern end
/x', $text, $matches);
$types = $matches[1];
$tokens = $matches[2];
// Iterate through the matches, building an associative array containing
// $tokens grouped by $types, pointing to the version of the token found in
// the source text. For example, $results['node']['title'] = '[node:title]';
$results = array();
for ($i = 0; $i < count($tokens); $i++) {
$results[$types[$i]][$tokens[$i]] = $matches[0][$i];
}
return $results;
}
/**
* Generates replacement values for a list of tokens.
*
* @param string $type
* The type of token being replaced. 'node', 'user', and 'date' are common.
* @param array $tokens
* An array of tokens to be replaced, keyed by the literal text of the token
* as it appeared in the source text.
* @param array $data
* (optional) An array of keyed objects. For simple replacement scenarios
* 'node', 'user', and others are common keys, with an accompanying node or
* user object being the value. Some token types, like 'site', do not require
* any explicit information from $data and can be replaced even if it is
* empty.
* @param array $options
* (optional) A keyed array of settings and flags to control the token
* replacement process. Supported options are:
* - langcode: A language code to be used when generating locale-sensitive
* tokens.
* - callback: A callback function that will be used to post-process the
* array of token replacements after they are generated. Can be used when
* modules require special formatting of token text, for example URL
* encoding or truncation to a specific length.
* - sanitize: A boolean flag indicating that tokens should be sanitized for
* display to a web browser. Developers who set this option to FALSE assume
* responsibility for running \Drupal\Component\Utility\Xss::filter(),
* \Drupal\Component\Utility\String::checkPlain() or other appropriate
* scrubbing functions before displaying data to users.
*
* @return array
* An associative array of replacement values, keyed by the original 'raw'
* tokens that were found in the source text. For example:
* $results['[node:title]'] = 'My new node';
*
* @see hook_tokens()
* @see hook_tokens_alter()
*/
public function generate($type, array $tokens, array $data = array(), array $options = array()) {
$options += array('sanitize' => TRUE);
$replacements = $this->moduleHandler->invokeAll('tokens', array($type, $tokens, $data, $options));
// Allow other modules to alter the replacements.
$context = array(
'type' => $type,
'tokens' => $tokens,
'data' => $data,
'options' => $options,
);
$this->moduleHandler->alter('tokens', $replacements, $context);
return $replacements;
}
/**
* Returns a list of tokens that begin with a specific prefix.
*
* Used to extract a group of 'chained' tokens (such as [node:author:name])
* from the full list of tokens found in text. For example:
* @code
* $data = array(
* 'author:name' => '[node:author:name]',
* 'title' => '[node:title]',
* 'created' => '[node:created]',
* );
* $results = Token::findWithPrefix($data, 'author');
* $results == array('name' => '[node:author:name]');
* @endcode
*
* @param array $tokens
* A keyed array of tokens, and their original raw form in the source text.
* @param string $prefix
* A textual string to be matched at the beginning of the token.
* @param string $delimiter
* (optional) A string containing the character that separates the prefix from
* the rest of the token. Defaults to ':'.
*
* @return array
* An associative array of discovered tokens, with the prefix and delimiter
* stripped from the key.
*/
public function findWithPrefix(array $tokens, $prefix, $delimiter = ':') {
$results = array();
foreach ($tokens as $token => $raw) {
$parts = explode($delimiter, $token, 2);
if (count($parts) == 2 && $parts[0] == $prefix) {
$results[$parts[1]] = $raw;
}
}
return $results;
}
/**
* Returns metadata describing supported tokens.
*
* The metadata array contains token type, name, and description data as well
* as an optional pointer indicating that the token chains to another set of
* tokens.
*
* @return array
* An associative array of token information, grouped by token type. The
* array structure is identical to that of hook_token_info().
*
* @see hook_token_info()
*/
public function getInfo() {
if (is_null($this->tokenInfo)) {
$this->tokenInfo = $this->moduleHandler->invokeAll('token_info');
$this->moduleHandler->alter('token_info', $this->tokenInfo);
}
return $this->tokenInfo;
}
/**
* Sets metadata describing supported tokens.
*
* @param array $tokens
* Token metadata that has an identical structure to the return value of
* hook_token_info().
*
* @see hook_token_info()
*/
public function setInfo(array $tokens) {
$this->tokenInfo = $tokens;
}
/**
* Resets metadata describing supported tokens.
*/
public function resetInfo() {
$this->tokenInfo = NULL;
}
}
| gpl-2.0 |
jheizmann/SMWHalo | includes/SMW_SemanticStore.php | 9837 | <?php
/*
* Copyright (C) Vulcan 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, see <http://www.gnu.org/licenses/>.
*
*/
/**
* @file
* @ingroup SMWHaloSemanticStorage
*
* Created on 19.09.2007
*
* Author: kai
*
* @defgroup SMWHaloSemanticStorage SMWHalo Semantic storage layer
* @ingroup SMWHalo
*/
abstract class SMWSemanticStore {
/**
* Must be called from derived class to initialize the member variables.
*/
protected function SMWSemanticStore() {
// nothing to do
}
/**
* Initializes all tables and predefined pages.
*/
public abstract function setup($verbose);
/**
* Returns pages of the given namespace.
*
* @param int[] $namespaces Array of ns constants, positive ns constants get or'ed, negative get and'ed and excluded.
* @param SMWRequestOptions $requestoptions object.
* @param boolean $addRedirectTargets If false, redirect are completely ignored. Otherwise their targets are added.
* @param string $bundleID Returns only pages which are part of the given bundle.
*
* @return array of Title
*/
public abstract function getPages($namespaces = NULL, $requestoptions = NULL, $addRedirectTargets = false, $bundleID = '');
/**
* Returns root categories (categories which have no super-category).
* Also returns non-existing root categories, ie. root categories which
* do only exist implicitly.
*
* @param SMWRequestOptions $requestoptions object.
* @param string $bundleID Returns only pages which are part of the given bundle.
*
* @return array of (Title t, boolean isLeaf)
*/
public abstract function getRootCategories($requestoptions = NULL, $bundleID = '');
/**
* Returns root properties (properties which have no super-property).
*
* @param SMWRequestOptions $requestoptions object.
* @param string $bundleID Returns only pages which are part of the given bundle.
*
* @return array of (Title t, boolean isLeaf)
*/
public abstract function getRootProperties($requestoptions = NULL, $bundleID = '');
/**
* Returns direct subcategories of $categoryTitle.
*
* @param Title $categoryTitle
* @param SMWRequestOptions $requestoptions object.
* @param string $bundleID Returns only pages which are part of the given bundle.
*
* @return array of (Title t, boolean isLeaf)
*/
public abstract function getDirectSubCategories(Title $categoryTitle, $requestoptions = NULL, $bundleID = '');
/**
* Returns all subcategories of $category
*
* @param $category
* @return array of Title
*/
public abstract function getSubCategories(Title $category);
/**
* Returns direct supercategories of $categoryTitle.
*
* @return array of Title
*/
public abstract function getDirectSuperCategories(Title $categoryTitle, $requestoptions = NULL);
/**
* Returns all categories the given instance is member of.
*
* @param Title $instanceTitle
* @param SMWRequestOptions $requestoptions object.
* @param string $bundleID Returns only pages which are part of the given bundle.
*
* @return array of Title
*/
public abstract function getCategoriesForInstance(Title $instanceTitle, $requestoptions = NULL, $bundleID = '');
/**
* Checks if $article is an article which is of category $category
*
* @param Title $article
* @param Title $category
*
* @return boolean
*/
public abstract function isInCategory(Title $article, Title $category);
/**
* Returns all articles of $categoryTitle lying in NS_MAIN including articles of all subcategories of $categoryTitle.
*
* In the case of a cycle in the category inheritance graph, this method has a treshhold
* to stop execution before a stack overflow occurs.
*
* @return if $withCategories == true array of tuples (Title instance, Title category), otherwise array of Title
*/
public abstract function getInstances(Title $categoryTitle, $requestoptions = NULL, $withCategories = true);
/**
* Returns all instances of $categoryTitle including instances of all subcategories of $categoryTitle.
* Articles of any namespace except the category namespace can be returned.
*
* In the case of a cycle in the category inheritance graph, this method has a treshhold
* to stop execution before a stack overflow occurs.
*
* @return if $withCategories == true array of tuples (Title instance, Title category), otherwise array of Title
*/
public abstract function getAllInstances(Title $categoryTitle, $requestoptions = NULL, $withCategories = true);
/**
* Returns all direct instances of $categoryTitle
*
* @param SMWRequestOption $requestOptions
* @return array of Title
*/
public abstract function getDirectInstances(Title $categoryTitle, $requestoptions = NULL);
/**
* Returns all properties with schema of $categoryTitle (including inherited).
*
* @param Title $categoryTitle Category whose properties should be returned.
* @param boolean $onlyDirect Show only direct properties (no inherited from super categories)
* @param int $dIndex 0 = get properties with the given category as domain
* 1 = get properties with the given category as range
* @param SMWRequestOption $requestOptions
* @param string $bundleID Retrieve only properties of the given bundle.
* @return tuples (title, minCard, maxCard, type, isSym, isTrans, range)
*/
public abstract function getPropertiesWithSchemaByCategory(Title $categoryTitle, $onlyDirect = false, $dIndex = 0, $requestoptions = NULL,$bundleID= '');
/**
* Returns all properties of matching $requestoptions
*
* @param SMWRequestOption $requestOptions
* @return tuples: (title, minCard, maxCard, type, isSym, isTrans, range)
*/
public abstract function getPropertiesWithSchemaByName($requestoptions);
/**
* Returns direct properties of $categoryTitle (but no schema-data!)
*
* @return array of Title
*/
//public abstract function getDirectPropertiesByCategory(Title $categoryTitle, $requestoptions = NULL);
/**
* Returns all properties with the given domain category.
*
* @param category Title
* @return array of Title
*/
public abstract function getPropertiesWithDomain(Title $category);
/**
* Return all properties with the given range category
*
* @param category Title
*
* @return array of Title
*/
public abstract function getPropertiesWithRange(Title $category);
/**
* Returns all domain categories for a given property.
*
* @param Title $propertyTitle
* @param SMWRequestOptions $reqfilter.
* @param string $bundleID Returns only pages which are part of the given bundle.
*
* @return array of Title
*
*/
public abstract function getDomainCategories($propertyTitle, $reqfilter = NULL, $bundleID = '');
/**
* Returns all direct subproperties of $property.
*
* @return array of (Title t, boolean isLeaf)
*/
public abstract function getDirectSubProperties(Title $property, $requestoptions = NULL);
/**
* Returns all direct superproperties of $property.
*
* @return array of Title
*/
public abstract function getDirectSuperProperties(Title $property, $requestoptions = NULL);
/**
* Returns all pages which are redirects to the given page.
*
* @param $title Target of redirects
*
* @return array of Title objects
*/
public abstract function getRedirectPages(Title $title);
/**
* Returns the redirect target, if $title is a redirect.
* Otherwise $title itsself is returned.
*
* @param $title possible redirect page
*
* @return Target of redirect or $title.
*/
public abstract function getRedirectTarget(Title $title);
/**
* Returns total number of usages of $property on arbitrary wiki pages.
*/
public abstract function getNumberOfUsage(Title $property);
/**
* Returns number of (direct and indirect) instances and number of subcategories.
*
* @param $category Title
* @return array($numOfInstance, $numOfCategories);
*/
public abstract function getNumberOfInstancesAndSubcategories(Title $category);
/**
* Returns number of properties for a $category.
*
* @param $category
*/
public abstract function getNumberOfProperties(Title $category);
/**
* Returns number of annotation which have $target as their target.
*
* @param $target Title
*/
public abstract function getNumberOfPropertiesForTarget(Title $target);
/**
* Returns number of pages of the given namespace.
*
* @param int $namespace
*/
public abstract function getNumber($namespace);
/**
* Returns all different units of annotations of a given type.
*
* @param Title $type
*
* @return array of strings
*/
public abstract function getDistinctUnits(Title $type);
/**
* Returns all annotations of the given user-defined type with the given unit.
*
* @param Title $type
* @param unit string
*
* @return array of (Title subject, Title property)
*/
public abstract function getAnnotationsWithUnit(Title $type, $unit);
/**
* Replaces redirect annotations, i.e. pages with annotations made with redirect
* property pages. Does also replace such annotations on template pages with the usual
* constraints. Modifies database!
*
* @param $verbose If true, method prints some output.
*/
public abstract function replaceRedirectAnnotations($verbose = false);
}
| gpl-2.0 |
iucn-whp/world-heritage-outlook | portlets/iucn-dbservice-portlet/docroot/WEB-INF/service/com/iucn/whp/dbservice/model/reinforced_monitoringSoap.java | 3285 | /**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.iucn.whp.dbservice.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* This class is used by SOAP remote services.
*
* @author alok.sen
* @generated
*/
public class reinforced_monitoringSoap implements Serializable {
public static reinforced_monitoringSoap toSoapModel(
reinforced_monitoring model) {
reinforced_monitoringSoap soapModel = new reinforced_monitoringSoap();
soapModel.setWhp_sites_reinforced_monitoring_id(model.getWhp_sites_reinforced_monitoring_id());
soapModel.setSite_id(model.getSite_id());
soapModel.setReinforced_date(model.getReinforced_date());
return soapModel;
}
public static reinforced_monitoringSoap[] toSoapModels(
reinforced_monitoring[] models) {
reinforced_monitoringSoap[] soapModels = new reinforced_monitoringSoap[models.length];
for (int i = 0; i < models.length; i++) {
soapModels[i] = toSoapModel(models[i]);
}
return soapModels;
}
public static reinforced_monitoringSoap[][] toSoapModels(
reinforced_monitoring[][] models) {
reinforced_monitoringSoap[][] soapModels = null;
if (models.length > 0) {
soapModels = new reinforced_monitoringSoap[models.length][models[0].length];
}
else {
soapModels = new reinforced_monitoringSoap[0][0];
}
for (int i = 0; i < models.length; i++) {
soapModels[i] = toSoapModels(models[i]);
}
return soapModels;
}
public static reinforced_monitoringSoap[] toSoapModels(
List<reinforced_monitoring> models) {
List<reinforced_monitoringSoap> soapModels = new ArrayList<reinforced_monitoringSoap>(models.size());
for (reinforced_monitoring model : models) {
soapModels.add(toSoapModel(model));
}
return soapModels.toArray(new reinforced_monitoringSoap[soapModels.size()]);
}
public reinforced_monitoringSoap() {
}
public long getPrimaryKey() {
return _whp_sites_reinforced_monitoring_id;
}
public void setPrimaryKey(long pk) {
setWhp_sites_reinforced_monitoring_id(pk);
}
public long getWhp_sites_reinforced_monitoring_id() {
return _whp_sites_reinforced_monitoring_id;
}
public void setWhp_sites_reinforced_monitoring_id(
long whp_sites_reinforced_monitoring_id) {
_whp_sites_reinforced_monitoring_id = whp_sites_reinforced_monitoring_id;
}
public long getSite_id() {
return _site_id;
}
public void setSite_id(long site_id) {
_site_id = site_id;
}
public Date getReinforced_date() {
return _reinforced_date;
}
public void setReinforced_date(Date reinforced_date) {
_reinforced_date = reinforced_date;
}
private long _whp_sites_reinforced_monitoring_id;
private long _site_id;
private Date _reinforced_date;
} | gpl-2.0 |
reactormonk/nmm | TESO/TESOLauncher.cs | 6609 | using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using Nexus.Client.Commands;
using Nexus.Client.Util;
namespace Nexus.Client.Games.TESO
{
/// <summary>
/// Launches TESO.
/// </summary>
public class TESOLauncher : GameLauncherBase
{
private string ESOLaunchPath;
#region Constructors
/// <summary>
/// A simple constructor that initializes the object with the given dependencies.
/// </summary>
/// <param name="p_gmdGameMode">>The game mode currently being managed.</param>
/// <param name="p_eifEnvironmentInfo">The application's envrionment info.</param>
public TESOLauncher(IGameMode p_gmdGameMode, IEnvironmentInfo p_eifEnvironmentInfo)
: base(p_gmdGameMode, p_eifEnvironmentInfo)
{
}
#endregion
/// <summary>
/// Initializes the game launch commands.
/// </summary>
protected override void SetupCommands()
{
Trace.TraceInformation("Launch Commands:");
Trace.Indent();
ClearLaunchCommands();
string strCommand = GetPlainLaunchCommand();
Trace.TraceInformation("Plain Command: {0} (IsNull={1})", strCommand, (strCommand == null));
Image imgIcon = File.Exists(strCommand) ? Icon.ExtractAssociatedIcon(strCommand).ToBitmap() : null;
AddLaunchCommand(new Command("PlainLaunch", "Launch The Elder Scrolls Online", "Launches plain The Elder Scrolls Online.", imgIcon, LaunchTESOPlain, true));
strCommand = GetESOLauncherLaunchCommand();
Trace.TraceInformation("ESO Launcher Command: {0} (IsNull={1})", strCommand, (strCommand == null));
if (File.Exists(strCommand))
{
imgIcon = Icon.ExtractAssociatedIcon(strCommand).ToBitmap();
AddLaunchCommand(new Command("ESOLauncher", "Launch the ESO Launcher", "Launches the ESO Launcher.", imgIcon, LaunchESOLauncher, true));
}
strCommand = GetCustomLaunchCommand();
Trace.TraceInformation("Custom Command: {0} (IsNull={1})", strCommand, (strCommand == null));
imgIcon = File.Exists(strCommand) ? Icon.ExtractAssociatedIcon(strCommand).ToBitmap() : null;
AddLaunchCommand(new Command("CustomLaunch", "Launch Custom The Elder Scrolls Online", "Launches The Elder Scrolls Online with custom command.", imgIcon, LaunchTESOCustom, true));
DefaultLaunchCommand = new Command("Launch the ESO Launcher", "Launches the ESO Launcher.", LaunchGame);
Trace.Unindent();
}
#region Launch Commands
#region Custom Command
/// <summary>
/// Launches the game with a custom command.
/// </summary>
private void LaunchTESOCustom()
{
Trace.TraceInformation("Launching Elder Scrolls Online (Custom)...");
Trace.Indent();
string strCommand = GetCustomLaunchCommand();
string strCommandArgs = EnvironmentInfo.Settings.CustomLaunchCommandArguments[GameMode.ModeId];
if (String.IsNullOrEmpty(strCommand))
{
Trace.TraceError("No custom launch command has been set.");
Trace.Unindent();
OnGameLaunched(false, "No custom launch command has been set.");
return;
}
Launch(strCommand, strCommandArgs);
}
/// <summary>
/// Gets the custom launch command.
/// </summary>
/// <returns>The custom launch command.</returns>
private string GetCustomLaunchCommand()
{
string strCommand = EnvironmentInfo.Settings.CustomLaunchCommands[GameMode.ModeId];
if (!String.IsNullOrEmpty(strCommand))
{
strCommand = Environment.ExpandEnvironmentVariables(strCommand);
strCommand = FileUtil.StripInvalidPathChars(strCommand);
if (!Path.IsPathRooted(strCommand))
strCommand = Path.Combine(GameMode.GameModeEnvironmentInfo.ExecutablePath, strCommand);
}
return strCommand;
}
#endregion
#region Vanilla Launch
/// <summary>
/// Launches the game without the launcher.
/// </summary>
private void LaunchTESOPlain()
{
Trace.TraceInformation("Launching Elder Scrolls Online (Plain)...");
Trace.Indent();
string strCommand = GetPlainLaunchCommand();
Trace.TraceInformation("Command: " + strCommand);
Launch(strCommand, null);
}
/// <summary>
/// Gets the plain launch command.
/// </summary>
/// <returns>The plain launch command.</returns>
private string GetPlainLaunchCommand()
{
string strCommand = Path.Combine(GameMode.ExecutablePath, "eso.exe");
return strCommand;
}
#endregion
#region Launcher
/// <summary>
/// Launches the ESO Launcher.
/// </summary>
private void LaunchESOLauncher()
{
Trace.TraceInformation("Launching ESO Launcher...");
Trace.Indent();
string strCommand = GetESOLauncherLaunchCommand();
Trace.TraceInformation("Command: " + strCommand);
if (!File.Exists(strCommand))
{
Trace.TraceError("ESO Launcher does not appear to be installed.");
Trace.Unindent();
OnGameLaunched(false, "ESO Launcher does not appear to be installed.");
return;
}
Launch(strCommand, null);
}
/// <summary>
/// Gets the ESO Launcher launch command.
/// </summary>
/// <returns>The ESO Launcher launch command.</returns>
private string GetESOLauncherLaunchCommand()
{
try
{
string strInstallPath = Path.GetDirectoryName(Path.GetDirectoryName(GameMode.ExecutablePath));
ESOLaunchPath = Path.Combine(Path.GetDirectoryName(strInstallPath), Path.Combine("Launcher", "Bethesda.net_Launcher.exe"));
return ESOLaunchPath;
}
catch
{
return String.Empty;
}
}
#endregion
/// <summary>
/// Launches the game, using the custom command or the launcher if present.
/// </summary>
private void LaunchGame()
{
if (!String.IsNullOrEmpty(EnvironmentInfo.Settings.CustomLaunchCommands[GameMode.ModeId]))
LaunchTESOCustom();
else if (File.Exists(ESOLaunchPath))
LaunchESOLauncher();
else
LaunchTESOPlain();
}
#endregion
}
}
| gpl-2.0 |
yangjes-github/test.wordpress | wp-content/themes/dux/modules/mo_post_link.php | 514 | <?php
function mo_post_link()
{
global $post;
$post_ID = $post->ID;
$link = get_post_meta($post_ID, "link", true);
if ($link) {
echo "<div class=\"post-linkto\"><a class=\"btn btn-primary\" href=\"" . $link . "\"" . (_hui("post_link_blank_s") ? " target=\"_blank\"" : "") . (_hui("post_link_nofollow_s") ? " rel=\"external nofollow\"" : "") . ">" . (is_single() ? "<i class=\"glyphicon glyphicon-share-alt\"></i>" : "") . _hui("post_link_h1") . " <i class=\"fa fa-hand-o-right\"></i></a></div>";
}
}
?>
| gpl-2.0 |
thekuoster/lytro_game | wp-content/plugins/advanced-wp-columns/js/jQueryUI/ui/minified/jquery.ui.tabs.min.js | 11534 | /*
* jQuery UI Tabs 1.9m3
*
* Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Tabs
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*/
(function(d,p){function u(){return++v}function w(){return++x}var v=0,x=0;d.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:false,cookie:null,collapsible:false,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading…</em>",tabTemplate:"<li><a href='#{href}'><span>#{label}</span></a></li>"},_create:function(){this._tabify(true)},_setOption:function(b,e){if(b=="selected")this.options.collapsible&&
e==this.options.selected||this.select(e);else{this.options[b]=e;this._tabify()}},_tabId:function(b){return b.title&&b.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF-]/g,"")||this.options.idPrefix+u()},_sanitizeSelector:function(b){return b.replace(/:/g,"\\:")},_cookie:function(){var b=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+w());return d.cookie.apply(null,[b].concat(d.makeArray(arguments)))},_ui:function(b,e){return{tab:b,panel:e,index:this.anchors.index(b)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var b=
d(this);b.html(b.data("label.tabs")).removeData("label.tabs")})},_tabify:function(b){function e(g,f){g.css("display","");!d.support.opacity&&f.opacity&&g[0].style.removeAttribute("filter")}var a=this,c=this.options,h=/^#.+/;this.list=this.element.find("ol,ul").eq(0);this.lis=d(" > li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return d("a",this)[0]});this.panels=d([]);this.anchors.each(function(g,f){var i=d(f).attr("href"),l=i.split("#")[0],q;if(l&&(l===location.toString().split("#")[0]||
(q=d("base")[0])&&l===q.href)){i=f.hash;f.href=i}if(h.test(i))a.panels=a.panels.add(a._sanitizeSelector(i));else if(i&&i!=="#"){d.data(f,"href.tabs",i);d.data(f,"load.tabs",i.replace(/#.*$/,""));i=a._tabId(f);f.href="#"+i;f=d("#"+i);if(!f.length){f=d(c.panelTemplate).attr("id",i).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(a.panels[g-1]||a.list);f.data("destroy.tabs",true)}a.panels=a.panels.add(f)}else c.disabled.push(g)});if(b){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all");
this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(c.selected===p){location.hash&&this.anchors.each(function(g,f){if(f.hash==location.hash){c.selected=g;return false}});if(typeof c.selected!=="number"&&c.cookie)c.selected=parseInt(a._cookie(),10);if(typeof c.selected!=="number"&&this.lis.filter(".ui-tabs-selected").length)c.selected=
this.lis.index(this.lis.filter(".ui-tabs-selected"));c.selected=c.selected||(this.lis.length?0:-1)}else if(c.selected===null)c.selected=-1;c.selected=c.selected>=0&&this.anchors[c.selected]||c.selected<0?c.selected:0;c.disabled=d.unique(c.disabled.concat(d.map(this.lis.filter(".ui-state-disabled"),function(g){return a.lis.index(g)}))).sort();d.inArray(c.selected,c.disabled)!=-1&&c.disabled.splice(d.inArray(c.selected,c.disabled),1);this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active");
if(c.selected>=0&&this.anchors.length){d(a._sanitizeSelector(a.anchors[c.selected].hash)).removeClass("ui-tabs-hide");this.lis.eq(c.selected).addClass("ui-tabs-selected ui-state-active");a.element.queue("tabs",function(){a._trigger("show",null,a._ui(a.anchors[c.selected],d(a._sanitizeSelector(a.anchors[c.selected].hash))))});this.load(c.selected)}d(window).bind("unload",function(){a.lis.add(a.anchors).unbind(".tabs");a.lis=a.anchors=a.panels=null})}else c.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"));
this.element[c.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible");c.cookie&&this._cookie(c.selected,c.cookie);b=0;for(var j;j=this.lis[b];b++)d(j)[d.inArray(b,c.disabled)!=-1&&!d(j).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");c.cache===false&&this.anchors.removeData("cache.tabs");this.lis.add(this.anchors).unbind(".tabs");if(c.event!=="mouseover"){var k=function(g,f){f.is(":not(.ui-state-disabled)")&&f.addClass("ui-state-"+g)},n=function(g,f){f.removeClass("ui-state-"+
g)};this.lis.bind("mouseover.tabs",function(){k("hover",d(this))});this.lis.bind("mouseout.tabs",function(){n("hover",d(this))});this.anchors.bind("focus.tabs",function(){k("focus",d(this).closest("li"))});this.anchors.bind("blur.tabs",function(){n("focus",d(this).closest("li"))})}var m,o;if(c.fx)if(d.isArray(c.fx)){m=c.fx[0];o=c.fx[1]}else m=o=c.fx;var r=o?function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.hide().removeClass("ui-tabs-hide").animate(o,o.duration||"normal",
function(){e(f,o);a._trigger("show",null,a._ui(g,f[0]))})}:function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.removeClass("ui-tabs-hide");a._trigger("show",null,a._ui(g,f[0]))},s=m?function(g,f){f.animate(m,m.duration||"normal",function(){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");e(f,m);a.element.dequeue("tabs")})}:function(g,f){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");a.element.dequeue("tabs")};
this.anchors.bind(c.event+".tabs",function(){var g=this,f=d(g).closest("li"),i=a.panels.filter(":not(.ui-tabs-hide)"),l=d(a._sanitizeSelector(g.hash));if(f.hasClass("ui-tabs-selected")&&!c.collapsible||f.hasClass("ui-state-disabled")||f.hasClass("ui-state-processing")||a.panels.filter(":animated").length||a._trigger("select",null,a._ui(this,l[0]))===false){this.blur();return false}c.selected=a.anchors.index(this);a.abort();if(c.collapsible)if(f.hasClass("ui-tabs-selected")){c.selected=-1;c.cookie&&
a._cookie(c.selected,c.cookie);a.element.queue("tabs",function(){s(g,i)}).dequeue("tabs");this.blur();return false}else if(!i.length){c.cookie&&a._cookie(c.selected,c.cookie);a.element.queue("tabs",function(){r(g,l)});a.load(a.anchors.index(this));this.blur();return false}c.cookie&&a._cookie(c.selected,c.cookie);if(l.length){i.length&&a.element.queue("tabs",function(){s(g,i)});a.element.queue("tabs",function(){r(g,l)});a.load(a.anchors.index(this))}else throw"jQuery UI Tabs: Mismatching fragment identifier.";
d.browser.msie&&this.blur()});this.anchors.bind("click.tabs",function(){return false})},_getIndex:function(b){if(typeof b=="string")b=this.anchors.index(this.anchors.filter("[href$="+b+"]"));return b},destroy:function(){var b=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var e=
d.data(this,"href.tabs");if(e)this.href=e;var a=d(this).unbind(".tabs");d.each(["href","load","cache"],function(c,h){a.removeData(h+".tabs")})});this.lis.unbind(".tabs").add(this.panels).each(function(){d.data(this,"destroy.tabs")?d(this).remove():d(this).removeClass("ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-hover ui-state-focus ui-state-disabled ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide")});b.cookie&&this._cookie(null,b.cookie);return this},add:function(b,
e,a){if(a===p)a=this.anchors.length;var c=this,h=this.options;e=d(h.tabTemplate.replace(/#\{href\}/g,b).replace(/#\{label\}/g,e));b=!b.indexOf("#")?b.replace("#",""):this._tabId(d("a",e)[0]);e.addClass("ui-state-default ui-corner-top").data("destroy.tabs",true);var j=d("#"+b);j.length||(j=d(h.panelTemplate).attr("id",b).data("destroy.tabs",true));j.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(a>=this.lis.length){e.appendTo(this.list);j.appendTo(this.list[0].parentNode)}else{e.insertBefore(this.lis[a]);
j.insertBefore(this.panels[a])}h.disabled=d.map(h.disabled,function(k){return k>=a?++k:k});this._tabify();if(this.anchors.length==1){h.selected=0;e.addClass("ui-tabs-selected ui-state-active");j.removeClass("ui-tabs-hide");this.element.queue("tabs",function(){c._trigger("show",null,c._ui(c.anchors[0],c.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[a],this.panels[a]));return this},remove:function(b){b=this._getIndex(b);var e=this.options,a=this.lis.eq(b).remove(),c=this.panels.eq(b).remove();
if(a.hasClass("ui-tabs-selected")&&this.anchors.length>1)this.select(b+(b+1<this.anchors.length?1:-1));e.disabled=d.map(d.grep(e.disabled,function(h){return h!=b}),function(h){return h>=b?--h:h});this._tabify();this._trigger("remove",null,this._ui(a.find("a")[0],c[0]));return this},enable:function(b){b=this._getIndex(b);var e=this.options;if(d.inArray(b,e.disabled)!=-1){this.lis.eq(b).removeClass("ui-state-disabled");e.disabled=d.grep(e.disabled,function(a){return a!=b});this._trigger("enable",null,
this._ui(this.anchors[b],this.panels[b]));return this}},disable:function(b){b=this._getIndex(b);var e=this.options;if(b!=e.selected){this.lis.eq(b).addClass("ui-state-disabled");e.disabled.push(b);e.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[b],this.panels[b]))}return this},select:function(b){b=this._getIndex(b);if(b==-1)if(this.options.collapsible&&this.options.selected!=-1)b=this.options.selected;else return this;this.anchors.eq(b).trigger(this.options.event+".tabs");return this},
load:function(b){b=this._getIndex(b);var e=this,a=this.options,c=this.anchors.eq(b)[0],h=d.data(c,"load.tabs");this.abort();if(!h||this.element.queue("tabs").length!==0&&d.data(c,"cache.tabs"))this.element.dequeue("tabs");else{this.lis.eq(b).addClass("ui-state-processing");if(a.spinner){var j=d("span",c);j.data("label.tabs",j.html()).html(a.spinner)}this.xhr=d.ajax(d.extend({},a.ajaxOptions,{url:h,success:function(k,n){d(e._sanitizeSelector(c.hash)).html(k);e._cleanup();a.cache&&d.data(c,"cache.tabs",
true);e._trigger("load",null,e._ui(e.anchors[b],e.panels[b]));try{a.ajaxOptions.success(k,n)}catch(m){}},error:function(k,n){e._cleanup();e._trigger("load",null,e._ui(e.anchors[b],e.panels[b]));try{a.ajaxOptions.error(k,n,b,c)}catch(m){}}}));e.element.dequeue("tabs");return this}},abort:function(){this.element.queue([]);this.panels.stop(false,true);this.element.queue("tabs",this.element.queue("tabs").splice(-2,2));if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup();return this},url:function(b,
e){this.anchors.eq(b).removeData("cache.tabs").data("load.tabs",e);return this},length:function(){return this.anchors.length}});d.extend(d.ui.tabs,{version:"1.9m3"});d.extend(d.ui.tabs.prototype,{rotation:null,rotate:function(b,e){var a=this,c=this.options,h=a._rotate||(a._rotate=function(j){clearTimeout(a.rotation);a.rotation=setTimeout(function(){var k=c.selected;a.select(++k<a.anchors.length?k:0)},b);j&&j.stopPropagation()});e=a._unrotate||(a._unrotate=!e?function(j){j.clientX&&a.rotate(null)}:
function(){t=c.selected;h()});if(b){this.element.bind("tabsshow",h);this.anchors.bind(c.event+".tabs",e);h()}else{clearTimeout(a.rotation);this.element.unbind("tabsshow",h);this.anchors.unbind(c.event+".tabs",e);delete this._rotate;delete this._unrotate}return this}})})(jQuery);
| gpl-2.0 |
georgejhunt/HaitiDictionary.activity | data/words/ab~one.js | 177 | showWord(["v.","Enskri pou vin manm pou resevwa yon piblikasyon osinon pou resevwa yon sèvis. Mwen abòne nan jounal nouvelis, chak maten yo vin delivre l devan lakay mwen."
]) | gpl-2.0 |
DmitryADP/diff_qc750 | frameworks/av/media/libstagefright/ASFExtractor.cpp | 13922 | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_NDEBUG 0
#define LOG_TAG "ASFExtractor"
#include <utils/Log.h>
#include "include/ASFExtractor.h"
#include <stdlib.h>
#include <string.h>
#include <media/stagefright/DataSource.h>
#include <OMX_Types.h>
#include <media/stagefright/MediaBuffer.h>
#include <media/stagefright/MediaBufferGroup.h>
#include <media/stagefright/MediaDebug.h>
#include <media/stagefright/MediaDefs.h>
#include <media/stagefright/MediaSource.h>
#include <media/stagefright/MetaData.h>
#include <media/stagefright/Utils.h>
#include "include/avc_utils.h"
#include <dlfcn.h>
namespace android {
class ASFSource : public MediaSource{
public:
// Caller retains ownership of both "dataSource" and "Parser Handle".
ASFSource(const sp<MetaData> &format,
const sp<DataSource> &dataSource,
uint32_t mTrackCount, size_t &index,
ASFExtractorData *extractor, NvParseHalImplementation nvAsfParseHalImpl,
void* NvAsfParserHalHandle);
virtual status_t start(MetaData *params = NULL);
virtual status_t stop();
virtual sp<MetaData> getFormat();
virtual void InitSource(size_t& index, ASFExtractorData *Extractor);
virtual status_t read(
MediaBuffer **buffer, const ReadOptions *options = NULL);
protected:
virtual ~ASFSource();
private:
sp<MetaData> mFormat;
sp<DataSource> mDataSource;
ASFExtractorData *m_hExtractor;
bool mStarted;
size_t mTrackIndex;
MediaBufferGroup *mGroup;
MediaBuffer *mBuffer;
uint32_t mTrackCount;
NvParseHalImplementation nvAsfParseHalImpl;
void* NvAsfParserHalHandle;
ASFSource(const ASFSource &);
ASFSource &operator=(const ASFSource &);
};
/**********************************************************************************************************************/
ASFExtractor :: ASFExtractor(const sp<DataSource> &source)
: mDataSource(source),
Extractor(NULL),
mHaveMetadata(false),
mDuration(0),
mFlags(0),
NvAsfParserHalLibHandle(NULL),
mFileMetaData(new MetaData) {
const char* error;
memset(&mTracks,0,sizeof(Track)*MAX_INPUT_STREAMS);
LOGV("ASFExtractor::ASFExtractor");
if(NvAsfParserHalLibHandle == NULL) {
// Clear the old errors, no need to handle return for clearing
dlerror();
NvAsfParserHalLibHandle = dlopen("libnvasfparserhal.so", RTLD_NOW);
if(NvAsfParserHalLibHandle == NULL) {
LOGE("Failed to libnvasfarserhal.so with error %s\n",dlerror());
return;
}
}
typedef void *(*GetInstanceFunc)(NvParseHalImplementation *);
// Clear the old errors, no need to handle return for clearing
dlerror();
GetInstanceFunc getInstanceFunc =
(GetInstanceFunc) dlsym(NvAsfParserHalLibHandle, "NvAsfParserHal_GetInstanceFunc");
error = dlerror();
if(error != NULL) {
LOGE("Failed to locate NvAsfParserHal_GetInstanceFunc in libnvasfarserhal.so ");
return;
} else {
getInstanceFunc(&nvAsfParseHalImpl);
}
}
/**********************************************************************************************************************/
ASFExtractor::~ASFExtractor() {
status_t err = OK;
LOGV("ASFExtractor::~ASFExtractor");
if((mFlags & IS_INITIALIZED) && !(mFlags & HAS_SHARED_HAL)) {
err = nvAsfParseHalImpl.nvParserHalDestroyFunc(NvAsfParserHalHandle);
NvAsfParserHalHandle = NULL;
CHECK_EQ(err,OK);
delete Extractor;
Extractor = NULL;
}
}
/**********************************************************************************************************************/
bool ASFExtractor::initParser() {
status_t err = OK;
char pFilename[128];
if(mFlags & IS_INITIALIZED)
return true;
if(NvAsfParserHalLibHandle == NULL) {
LOGE("Error in ASFExtractor::initParser");
return false;
}
LOGV("In ASFExtractor::initParser");
Extractor = new ASFExtractorData;
memset(Extractor,0,sizeof(ASFExtractorData));
sprintf((char *)pFilename,"stagefright://%x",(mDataSource.get()));
err = nvAsfParseHalImpl.nvParserHalCreateFunc(pFilename,&NvAsfParserHalHandle);
if(err != OK) {
LOGE("Error in ASFExtractor::initParser");
return false;
}
// Get number track count
mTrackCount = nvAsfParseHalImpl.nvParserHalGetStreamCountFunc(NvAsfParserHalHandle);
mFlags |= HAS_TRACK_COUNT | IS_INITIALIZED;
return true;
}
/**********************************************************************************************************************/
sp<MetaData> ASFExtractor::getMetaData() {
status_t err = OK;
LOGV("ASFExtractor::getMetaData ");
if(!(mFlags & IS_INITIALIZED)) {
if(!initParser()) {
return mFileMetaData;
}
}
if(mFlags & HAS_FILE_METADATA) {
return mFileMetaData;
}
err = nvAsfParseHalImpl.nvParserHalGetMetaDataFunc(NvAsfParserHalHandle,mFileMetaData);
if(err == OK) {
mFlags |= HAS_FILE_METADATA;
}
return mFileMetaData;
}
/**********************************************************************************************************************/
size_t ASFExtractor::countTracks() {
status_t err = OK;
LOGV("ASFExtractor::countTracks ");
if(!(mFlags & IS_INITIALIZED)) {
if(!initParser()) {
err = UNKNOWN_ERROR;
return 0;
}
}
if(!(mFlags & HAS_TRACK_COUNT)) {
mTrackCount = nvAsfParseHalImpl.nvParserHalGetStreamCountFunc(NvAsfParserHalHandle);
mFlags |= HAS_TRACK_COUNT;
}
return mTrackCount;
}
/**********************************************************************************************************************/
sp<MetaData> ASFExtractor::getTrackMetaData(
size_t index, uint32_t flags) {
status_t err = OK;
if((mTracks[index].has_meta_data == true) && (!(flags & kIncludeExtensiveMetaData))) {
return mTracks[index].meta;
}
LOGV("ASFExtractor::getTrackMetaData ");
if(!(flags & kIncludeExtensiveMetaData)) {
mTracks[index].meta = new MetaData;
mTracks[index].timescale = 0;
mTracks[index].includes_expensive_metadata = false;
} else {
mTracks[index].includes_expensive_metadata = true;
}
err = nvAsfParseHalImpl.nvParserHalGetTrackMetaDataFunc(NvAsfParserHalHandle, index, (flags & kIncludeExtensiveMetaData), mTracks[index].meta);
if(err == OK) {
err = nvAsfParseHalImpl.nvParserHalSetTrackHeaderFunc(NvAsfParserHalHandle,index,mTracks[index].meta);
mTracks[index].has_meta_data = true;
return mTracks[index].meta;
} else {
return NULL;
}
}
/**********************************************************************************************************************/
sp<MediaSource> ASFExtractor::getTrack(size_t index) {
Track track = mTracks[index];
mFlags |= HAS_SHARED_HAL;
LOGV("Returning Track index %d",index);
return new ASFSource(
track.meta, mDataSource, mTrackCount,index,Extractor,nvAsfParseHalImpl,NvAsfParserHalHandle);
}
/**********************************************************************************************************************
**********************************************************************************************************************/
ASFSource::ASFSource(
const sp<MetaData> &format,
const sp<DataSource> &dataSource,
uint32_t mTrackCount,size_t &index,
ASFExtractorData *extractor,
NvParseHalImplementation nvAsfParseHalImpl,
void* NvAsfParserHalHandle)
: mFormat(format),
mDataSource(dataSource),
mStarted(false),
mTrackIndex(index),
mGroup(NULL),
mBuffer(NULL),
mTrackCount(mTrackCount),
nvAsfParseHalImpl(nvAsfParseHalImpl),
NvAsfParserHalHandle(NvAsfParserHalHandle) {
InitSource(mTrackIndex,extractor);
m_hExtractor->mSourceCreated++;
}
/**********************************************************************************************************************/
void ASFSource::InitSource(size_t &index, ASFExtractorData *Extractor) {
status_t err = OK;
char pFilename[128];
LOGV("In ASFSource::InitSource");
if(Extractor == NULL) {
m_hExtractor = new ASFExtractorData;
memset(m_hExtractor,0,sizeof(ASFExtractorData));
sprintf((char *)pFilename,"stagefright://%x",(mDataSource.get()));
err = nvAsfParseHalImpl.nvParserHalCreateFunc(pFilename,&NvAsfParserHalHandle);
if(err != OK) {
return;
}
} else {
m_hExtractor = Extractor;
LOGV("Reusing ASF source %p",Extractor);
}
sp<MetaData> meta = mFormat;
err = nvAsfParseHalImpl.nvParserHalSetTrackHeaderFunc(NvAsfParserHalHandle,index,meta);
if(err != OK) {
return;
}
}
/**********************************************************************************************************************/
ASFSource::~ASFSource() {
LOGV("ASFSource::~ASFSource() ");
if(mStarted) {
stop();
}
if (m_hExtractor) {
m_hExtractor->mSourceCreated--;
if (m_hExtractor->mSourceCreated == 0 && NvAsfParserHalHandle) {
LOGV("%s[%d], destrying parser HAL",__FUNCTION__,__LINE__);
nvAsfParseHalImpl.nvParserHalDestroyFunc(NvAsfParserHalHandle);
NvAsfParserHalHandle = NULL;
//Free extractor memory
delete m_hExtractor;
m_hExtractor = NULL;
}
}
}
/**********************************************************************************************************************/
status_t ASFSource::start(MetaData *params) {
Mutex::Autolock autoLock(m_hExtractor->mMutex);
status_t err = OK;
int32_t max_size;
LOGV("enterd ASFSource start mTrackIndex %d ", mTrackIndex);
CHECK(!mStarted);
if(m_hExtractor == NULL) {
LOGV("ASFSource Probably Restarted !!!!");
InitSource(mTrackIndex, NULL);
}
// Check Once again
if(m_hExtractor == NULL) {
LOGE("Serious Allocation Error");
return UNKNOWN_ERROR;
}
mGroup = new MediaBufferGroup;
CHECK(mFormat->findInt32(kKeyMaxInputSize, &max_size));
mGroup->add_buffer(new MediaBuffer(max_size));
mStarted = true;
return OK;
}
/**********************************************************************************************************************/
status_t ASFSource::stop() {
Mutex::Autolock autoLock(m_hExtractor->mMutex);
LOGV("ASFSource Stop--------");
status_t err = OK;
mStarted = false;
if(mBuffer != NULL) {
mBuffer->release();
mBuffer = NULL;
}
delete mGroup;
mGroup = NULL;
return err;
}
/**********************************************************************************************************************/
sp<MetaData> ASFSource::getFormat() {
return mFormat;
}
/**********************************************************************************************************************/
status_t ASFSource::read(
MediaBuffer **out, const ReadOptions *options) {
Mutex::Autolock autoLock(m_hExtractor->mMutex);
status_t err = OK;
int32_t decoderFlags = 0;
CHECK(mStarted);
*out = NULL;
err = mGroup->acquire_buffer(&mBuffer);
if (err != OK) {
CHECK_EQ(mBuffer, NULL);
return err;
}
err = nvAsfParseHalImpl.nvParserHalReadFunc(NvAsfParserHalHandle,mTrackIndex, mBuffer, options);
if(err != OK) {
goto cleanup;
}
// Check if buffer contains codec config data
mBuffer->meta_data()->findInt32(kKeyDecoderFlags, &decoderFlags);
if(decoderFlags & OMX_BUFFERFLAG_CODECCONFIG) {
sp<MetaData> meta = mFormat;
uint8_t * temp = (uint8_t *)mBuffer->data();
meta->setData(kKeyHeader, kTypeHeader, temp, mBuffer->range_length());
/*Do not pass options this time as seek is already done in previous function call */
err = nvAsfParseHalImpl.nvParserHalReadFunc(NvAsfParserHalHandle,mTrackIndex, mBuffer, NULL);
if(err != OK) {
goto cleanup;
}
}
if(mBuffer->range_length() == 0) {
LOGV("Read is returing zero sized buffer ");
}
cleanup:
if(err == OK) {
*out = mBuffer;
} else {
*out = NULL;
if(mBuffer) {
mBuffer->release();
}
}
mBuffer = NULL;
return err;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
bool SniffASF(const sp<DataSource> &source, String8 *mimeType,
float *confidence, sp<AMessage> *meta) {
uint8_t header[16];
ssize_t n = source->readAt(0, header, sizeof(header));
if(n < (ssize_t)sizeof(header)) {
return false;
}
if(!memcmp(header, ASF_HEADER_GUID, 16)) {
*mimeType = MEDIA_MIMETYPE_CONTAINER_ASF;
*confidence = 1.0;
LOGV ("asf is identified ####");
return true;
}
return false;
}
} // namespace android
| gpl-2.0 |
piaolinzhi/fight | webservice/rest/jax-rs2-guide/sample/common/src/main/java/com/example/exception/Jaxrs2GuideNotFoundException.java | 422 | package com.example.exception;
import javax.ws.rs.WebApplicationException;
public class Jaxrs2GuideNotFoundException extends WebApplicationException {
private static final long serialVersionUID = 1L;
public Jaxrs2GuideNotFoundException() {
super(javax.ws.rs.core.Response.Status.NOT_FOUND);
}
public Jaxrs2GuideNotFoundException(String message) {
super(message);
}
}
| gpl-2.0 |
jomizrahi92/SYPulse-Wordpress-Site | wp-content/themes/AllNews/sidebar-top.php | 178 |
<div id="sidebar-right">
<div class="sidebar-top">
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('top-sidebar') ) : ?>
<?php endif; ?>
</div>
</div> | gpl-2.0 |
zhang123shuo/javamop | src/javamop/logicpluginshells/javapda/parser/ParseException.java | 6385 | /* Generated By:JavaCC: Do not edit this line. ParseException.java Version 5.0 */
/* JavaCCOptions:KEEP_LINE_COL=null */
package javamop.logicpluginshells.javapda.parser;
/**
* This exception is thrown when parse errors are encountered.
* You can explicitly create objects of this exception type by
* calling the method generateParseException in the generated
* parser.
*
* You can modify this class to customize your error reporting
* mechanisms so long as you retain the public fields.
*/
public class ParseException extends Exception {
/**
* The version identifier for this Serializable class.
* Increment only if the <i>serialized</i> form of the
* class changes.
*/
private static final long serialVersionUID = 1L;
/**
* This constructor is used by the method "generateParseException"
* in the generated parser. Calling this constructor generates
* a new object of this type with the fields "currentToken",
* "expectedTokenSequences", and "tokenImage" set.
*/
public ParseException(Token currentTokenVal,
int[][] expectedTokenSequencesVal,
String[] tokenImageVal
)
{
super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));
currentToken = currentTokenVal;
expectedTokenSequences = expectedTokenSequencesVal;
tokenImage = tokenImageVal;
}
/**
* The following constructors are for use by you for whatever
* purpose you can think of. Constructing the exception in this
* manner makes the exception behave in the normal way - i.e., as
* documented in the class "Throwable". The fields "errorToken",
* "expectedTokenSequences", and "tokenImage" do not contain
* relevant information. The JavaCC generated code does not use
* these constructors.
*/
public ParseException() {
super();
}
/** Constructor with message. */
public ParseException(String message) {
super(message);
}
/**
* This is the last token that has been consumed successfully. If
* this object has been created due to a parse error, the token
* followng this token will (therefore) be the first error token.
*/
public Token currentToken;
/**
* Each entry in this array is an array of integers. Each array
* of integers represents a sequence of tokens (by their ordinal
* values) that is expected at this point of the parse.
*/
public int[][] expectedTokenSequences;
/**
* This is a reference to the "tokenImage" array of the generated
* parser within which the parse error occurred. This array is
* defined in the generated ...Constants interface.
*/
public String[] tokenImage;
/**
* It uses "currentToken" and "expectedTokenSequences" to generate a parse
* error message and returns it. If this object has been created
* due to a parse error, and you do not catch it (it gets thrown
* from the parser) the correct error message
* gets displayed.
*/
private static String initialise(Token currentToken,
int[][] expectedTokenSequences,
String[] tokenImage) {
String eol = System.getProperty("line.separator", "\n");
StringBuffer expected = new StringBuffer();
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected.append("...");
}
expected.append(eol).append(" ");
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += " " + tokenImage[tok.kind];
retval += " \"";
retval += add_escapes(tok.image);
retval += " \"";
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected.toString();
return retval;
}
/**
* The end of line string for this machine.
*/
protected String eol = System.getProperty("line.separator", "\n");
/**
* Used to convert raw characters to their escaped version
* when these raw version cannot be used as part of an ASCII
* string literal.
*/
static String add_escapes(String str) {
StringBuffer retval = new StringBuffer();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i))
{
case 0 :
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
continue;
}
}
return retval.toString();
}
}
/* JavaCC - OriginalChecksum=c924c8705a7ecc1823c45c8aa0947e82 (do not edit this line) */
| gpl-2.0 |
wayde191/kylin | wp-content/themes/photoria/js/dropdown.js | 2416 | /*********************
//* jQuery Multi Level CSS Menu #2- By Dynamic Drive: http://www.dynamicdrive.com/
//* Last update: Nov 7th, 08': Limit # of queued animations to minmize animation stuttering
//* Menu avaiable at DD CSS Library: http://www.dynamicdrive.com/style/
*********************/
//Update: April 12th, 10: Fixed compat issue with jquery 1.4x
//Specify full URL to down and right arrow images (23 is padding-right to add to top level LIs with drop downs):
var arrowimages={down:['downarrowclass'], right:['rightarrowclass']}
var jqueryslidemenu={
animateduration: {over: 200, out: 100}, //duration of slide in/ out animation, in milliseconds
buildmenu:function(menuid, arrowsvar){
jQuery(document).ready(function($){
var $mainmenu=$("#"+menuid+">ul")
var $headers=$mainmenu.find("ul").parent()
$headers.each(function(i){
var $curobj=$(this)
var $subul=$(this).find('ul:eq(0)')
this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
this.istopheader=$curobj.parents("ul").length==1? true : false
$subul.css({top:this.istopheader? this._dimensions.h+"px" : 0})
$curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: arrowsvar.down[2]} : {}).append(
'<span class="' + (this.istopheader? arrowsvar.down[0] : arrowsvar.right[0])
+ '" style="border:0;"></span>'
)
$curobj.hover(
function(e){
var $targetul=$(this).children("ul:eq(0)")
this._offsets={left:$(this).offset().left, top:$(this).offset().top}
var menuleft=this.istopheader? 0 : this._dimensions.w
menuleft=(this._offsets.left+menuleft+this._dimensions.subulw>$(window).width())? (this.istopheader? -this._dimensions.subulw+this._dimensions.w : -this._dimensions.w) : menuleft
if ($targetul.queue().length<=1) //if 1 or less queued animations
$targetul.css({left:menuleft+"px", width:this._dimensions.subulw+'px'}).slideDown(jqueryslidemenu.animateduration.over)
},
function(e){
var $targetul=$(this).children("ul:eq(0)")
$targetul.slideUp(jqueryslidemenu.animateduration.out)
}
) //end hover
$curobj.click(function(){
$(this).children("ul:eq(0)").hide()
})
}) //end $headers.each()
$mainmenu.find("ul").css({display:'none', visibility:'visible'})
}) //end document.ready
}
}
//build menu with ID="menu" on page:
jqueryslidemenu.buildmenu("menu", arrowimages) | gpl-2.0 |
rjbaniel/upoor | wp-content/themes/Glider/includes/functions/comments.php | 1524 | <?php if ( ! function_exists( 'et_custom_comments_display' ) ) :
function et_custom_comments_display($comment, $args, $depth) {
$GLOBALS['comment'] = $comment; ?>
<li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
<div id="comment-<?php comment_ID(); ?>" class="comment-body clearfix">
<div class="avatar">
<?php echo get_avatar($comment,$size='57'); ?>
<span class="overlay"></span>
</div>
<div class="comment-wrap">
<div class="comment-author vcard">
<?php printf('<span class="fn">%s</span>', get_comment_author_link()) ?> |<span class="comment-meta commentmetadata"> <a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ) ?>"><?php echo(get_comment_date()) ?></a><?php edit_comment_link(esc_html__('(Edit)','Glider'),' ','') ?></span>
</div>
<?php if ($comment->comment_approved == '0') : ?>
<em class="moderation"><?php esc_html_e('Your comment is awaiting moderation.','Glider') ?></em>
<br />
<?php endif; ?>
<div class="comment-content"><?php comment_text() ?></div> <!-- end comment-content-->
<?php
$et_comment_reply_link = get_comment_reply_link( array_merge( $args, array('reply_text' => esc_attr__('Reply','Glider'),'depth' => $depth, 'max_depth' => $args['max_depth'])) );
if ( $et_comment_reply_link ) echo '<div class="reply-container">' . $et_comment_reply_link . '</div>';
?>
</div> <!-- end comment-wrap-->
</div> <!-- end comment-body-->
<?php }
endif; ?> | gpl-2.0 |
akranga/chucknorris | src/main/java/com/github/akranga/ChuckNorrisApplication.java | 427 | package com.github.akranga;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@EnableAutoConfiguration
@SpringBootApplication
public class ChuckNorrisApplication {
public static void main(String[] args) {
SpringApplication.run(ChuckNorrisApplication.class, args);
}
}
| gpl-2.0 |
JonHoy/FEA-Code | FEA/FEA.Mesher/Quadrilateral.cs | 3212 | using System;
using ManagedCuda.VectorTypes;
using System.Collections.Generic;
namespace FEA.Mesher
{
public class Quadrilateral
{
public Quadrilateral(double3 PointA, double3 PointB, double3 PointC, double3 PointD)
{
A = PointA;
B = PointB;
C = PointC;
D = PointD;
}
// TODO account for nans by turning quadrilateral into triangle
public double3 Intersection(double3 O, double3 D) {
// to break up the quadrilateral into two triangles
// Since a quadrilateral with two equal points is a triangle,
// we have to figure out which (if any) of the points are equal
var AB = A - B;
if (AB.Length == 0)
return ReturnTriIntersect(1, O, D);
var BC = B - C;
if (BC.Length == 0)
return ReturnTriIntersect(2, O, D);
var CD = C - D;
if (CD.Length == 0)
return ReturnTriIntersect(3, O, D);
var DA = D - A;
if (DA.Length == 0)
return ReturnTriIntersect(4, O, D);
var AC = A - C;
if (AC.Length == 0)
return ReturnTriIntersect(1, O, D);
var BD = B - D;
if (BD.Length == 0)
return ReturnTriIntersect(2, O, D);
var Ans = ReturnTriIntersect(1, O, D);
if (double.IsNaN(Ans.x))
Ans = ReturnTriIntersect(3, O, D);
return Ans;
}
private double3 ReturnTriIntersect(int Exclude, double3 O, double3 D) {
Triangle Tri;
if (Exclude == 1)
Tri = new Triangle(B,C,D);
else if (Exclude == 2)
Tri = new Triangle(A,C,D);
else if (Exclude == 3)
Tri = new Triangle(A,B,D);
else if (Exclude == 4)
Tri = new Triangle(A,B,C);
else
throw new Exception("Internal Error");
var t = Tri.Intersection(O, D);
return O + t * D;
}
public List<Triangle> Split() {
// split this quadrilateral up into two non intersecting triangles
// there is two possible valid configurations for the split,
// the configuration chosen is the one with the maximum area/ perimeter ratio
var Tri1 = new Triangle(A,B,C);
var Tri2 = new Triangle(A, D, C);
var Ratio1 = Tri1.Area() / Tri1.Perimeter() + Tri2.Area() / Tri2.Perimeter();
var Tri3 = new Triangle(A, B, D);
var Tri4 = new Triangle(C, B, D);
var Ratio2 = Tri3.Area() / Tri3.Perimeter() + Tri4.Area() / Tri4.Perimeter();
var Tris = new List<Triangle>(2);
if (Ratio1 >= Ratio2)
{
Tris.Add(Tri1);
Tris.Add(Tri2);
}
else
{
Tris.Add(Tri3);
Tris.Add(Tri4);
}
return Tris;
}
public double3 A;
public double3 B;
public double3 C;
public double3 D;
}
}
| gpl-2.0 |
Fat-Zer/tdebase | kicker/applets/minipager/pagerapplet.cpp | 28745 | /*****************************************************************
Copyright (c) 1996-2000 the kicker authors. See file AUTHORS.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************/
#include <tqpainter.h>
#include <tqtooltip.h>
#include <tqlineedit.h>
#include <tqpopupmenu.h>
#include <tqlayout.h>
#include <tqbuttongroup.h>
#include <dcopref.h>
#include <tdeglobalsettings.h>
#include <twin.h>
#include <twinmodule.h>
#include <tdeapplication.h>
#include <tdeglobal.h>
#include <tdelocale.h>
#include <kdebug.h>
#include <kprocess.h>
#include <tdepopupmenu.h>
#include <kstandarddirs.h>
#include <kiconloader.h>
#include <dcopclient.h>
#include <netwm.h>
#include <kmanagerselection.h>
#include "global.h"
#include "kickertip.h"
#include "kickerSettings.h"
#include "kshadowengine.h"
#include "kshadowsettings.h"
#include "paneldrag.h"
#include "taskmanager.h"
#include "pagerapplet.h"
#include "pagerapplet.moc"
#ifdef FocusOut
#undef FocusOut
#endif
const int knDesktopPreviewSize = 12;
const int knBtnSpacing = 1;
// The previews tend to have a 4/3 aspect ratio
static const int smallHeight = 32;
static const int smallWidth = 42;
// config menu id offsets
static const int rowOffset = 2000;
static const int labelOffset = 200;
static const int bgOffset = 300;
extern "C"
{
KDE_EXPORT KPanelApplet* init(TQWidget *parent, const TQString& configFile)
{
TDEGlobal::locale()->insertCatalogue("kminipagerapplet");
return new KMiniPager(configFile, KPanelApplet::Normal, 0, parent, "kminipagerapplet");
}
}
KMiniPager::KMiniPager(const TQString& configFile, Type type, int actions,
TQWidget *parent, const char *name)
: KPanelApplet( configFile, type, actions, parent, name ),
m_layout(0),
m_desktopLayoutOwner( NULL ),
m_shadowEngine(0),
m_contextMenu(0),
m_settings( new PagerSettings(sharedConfig()) )
{
setBackgroundOrigin( AncestorOrigin );
int scnum = TQApplication::desktop()->screenNumber(this);
TQRect desk = TQApplication::desktop()->screenGeometry(scnum);
if (desk.width() <= 800)
{
TDEConfigSkeleton::ItemBool* item = dynamic_cast<TDEConfigSkeleton::ItemBool*>(m_settings->findItem("Preview"));
if (item)
{
item->setDefaultValue(false);
}
}
m_settings->readConfig();
m_windows.setAutoDelete(true);
if (m_settings->preview())
{
TaskManager::the()->trackGeometry();
}
m_group = new TQButtonGroup(this);
m_group->setBackgroundOrigin(AncestorOrigin);
m_group->setFrameStyle(TQFrame::NoFrame);
m_group->setExclusive( true );
setFont( TDEGlobalSettings::taskbarFont() );
m_twin = new KWinModule(TQT_TQOBJECT(this));
m_activeWindow = m_twin->activeWindow();
m_curDesk = m_twin->currentDesktop();
if (m_curDesk == 0) // twin not yet launched
{
m_curDesk = 1;
}
desktopLayoutOrientation = Qt::Horizontal;
desktopLayoutX = -1;
desktopLayoutY = -1;
TQSize s(m_twin->numberOfViewports(m_twin->currentDesktop()));
m_useViewports = s.width() * s.height() > 1;
drawButtons();
connect( m_twin, TQT_SIGNAL( currentDesktopChanged(int)), TQT_SLOT( slotSetDesktop(int) ) );
connect( m_twin, TQT_SIGNAL( currentDesktopViewportChanged(int, const TQPoint&)), TQT_SLOT(slotSetDesktopViewport(int, const TQPoint&)));
connect( m_twin, TQT_SIGNAL( numberOfDesktopsChanged(int)), TQT_SLOT( slotSetDesktopCount(int) ) );
connect( m_twin, TQT_SIGNAL( desktopGeometryChanged(int)), TQT_SLOT( slotRefreshViewportCount(int) ) );
connect( m_twin, TQT_SIGNAL( activeWindowChanged(WId)), TQT_SLOT( slotActiveWindowChanged(WId) ) );
connect( m_twin, TQT_SIGNAL( windowAdded(WId) ), this, TQT_SLOT( slotWindowAdded(WId) ) );
connect( m_twin, TQT_SIGNAL( windowRemoved(WId) ), this, TQT_SLOT( slotWindowRemoved(WId) ) );
connect( m_twin, TQT_SIGNAL( windowChanged(WId,unsigned int) ), this, TQT_SLOT( slotWindowChanged(WId,unsigned int) ) );
connect( m_twin, TQT_SIGNAL( desktopNamesChanged() ), this, TQT_SLOT( slotDesktopNamesChanged() ) );
connect( kapp, TQT_SIGNAL(backgroundChanged(int)), TQT_SLOT(slotBackgroundChanged(int)) );
if (kapp->authorizeTDEAction("kicker_rmb") && kapp->authorizeControlModule("tde-kcmtaskbar.desktop"))
{
m_contextMenu = new TQPopupMenu();
connect(m_contextMenu, TQT_SIGNAL(aboutToShow()), TQT_SLOT(aboutToShowContextMenu()));
connect(m_contextMenu, TQT_SIGNAL(activated(int)), TQT_SLOT(contextMenuActivated(int)));
setCustomMenu(m_contextMenu);
}
TQValueList<WId>::ConstIterator it;
TQValueList<WId>::ConstIterator itEnd = m_twin->windows().end();
for ( it = m_twin->windows().begin(); it != itEnd; ++it)
{
slotWindowAdded( (*it) );
}
slotSetDesktop( m_curDesk );
updateLayout();
}
KMiniPager::~KMiniPager()
{
TDEGlobal::locale()->removeCatalogue("kminipagerapplet");
delete m_contextMenu;
delete m_settings;
delete m_shadowEngine;
}
void KMiniPager::slotBackgroundChanged(int desk)
{
unsigned numDesktops = m_twin->numberOfDesktops();
if (numDesktops != m_desktops.count())
{
slotSetDesktopCount(numDesktops);
}
if (desk < 1 || (unsigned) desk > m_desktops.count())
{
// should not happen, but better to be paranoid than crash
return;
}
m_desktops[desk - 1]->backgroundChanged();
}
void KMiniPager::slotSetDesktop(int desktop)
{
if (m_twin->numberOfDesktops() > static_cast<int>(m_desktops.count()))
{
slotSetDesktopCount( m_twin->numberOfDesktops() );
}
if (!m_useViewports && (desktop != KWin::currentDesktop()))
{
// this can happen when the user clicks on a desktop,
// holds down the key combo to switch desktops, lets the
// mouse go but keeps the key combo held. the desktop will switch
// back to the desktop associated with the key combo and then it
// becomes a race condition between twin's signal and the button's
// signal. usually twin wins.
return;
}
m_curDesk = desktop;
if (m_curDesk < 1)
{
m_curDesk = 1;
}
KMiniPagerButton* button = m_desktops[m_curDesk - 1];
if (!button->isOn())
{
button->toggle();
}
}
void KMiniPager::slotSetDesktopViewport(int desktop, const TQPoint& viewport)
{
// ###
Q_UNUSED(desktop);
TQSize s(m_twin->numberOfViewports(m_twin->currentDesktop()));
slotSetDesktop((viewport.y()-1) * s.width() + viewport.x() );
}
void KMiniPager::slotButtonSelected( int desk )
{
if (m_twin->numberOfViewports(m_twin->currentDesktop()).width() *
m_twin->numberOfViewports(m_twin->currentDesktop()).height() > 1)
{
TQPoint p;
p.setX( (desk-1) * TQApplication::desktop()->width());
p.setY( 0 );
KWin::setCurrentDesktopViewport(m_twin->currentDesktop(), p);
}
else
KWin::setCurrentDesktop( desk );
slotSetDesktop( desk );
}
int KMiniPager::widthForHeight(int h) const
{
if (orientation() == Qt::Vertical)
{
return width();
}
int deskNum = m_twin->numberOfDesktops() * m_twin->numberOfViewports(0).width()
* m_twin->numberOfViewports(0).height();
int rowNum = m_settings->numberOfRows();
if (rowNum == 0)
{
if (h <= 32 || deskNum <= 1)
{
rowNum = 1;
}
else
{
rowNum = 2;
}
}
int deskCols = deskNum/rowNum;
if(deskNum == 0 || deskNum % rowNum != 0)
deskCols += 1;
int bw = (h / rowNum);
if( m_settings->labelType() != PagerSettings::EnumLabelType::LabelName )
{
if (desktopPreview() || m_settings->backgroundType() == PagerSettings::EnumBackgroundType::BgLive)
{
bw = (int) ( bw * (double) TQApplication::desktop()->width() / TQApplication::desktop()->height() );
}
}
else
{
// scale to desktop width as a minimum
bw = (int) (bw * (double) TQApplication::desktop()->width() / TQApplication::desktop()->height());
TQFontMetrics fm = fontMetrics();
for (int i = 1; i <= deskNum; i++)
{
int sw = fm.width( m_twin->desktopName( i ) ) + 8;
if (sw > bw)
{
bw = sw;
}
}
}
// we add one to the width for the spacing in between the buttons
// however, the last button doesn't have a space on the end of it (it's
// only _between_ buttons) so we then remove that one pixel
return (deskCols * (bw + 1)) - 1;
}
int KMiniPager::heightForWidth(int w) const
{
if (orientation() == Qt::Horizontal)
{
return height();
}
int deskNum = m_twin->numberOfDesktops() * m_twin->numberOfViewports(0).width()
* m_twin->numberOfViewports(0).height();
int rowNum = m_settings->numberOfRows(); // actually these are columns now... oh well.
if (rowNum == 0)
{
if (w <= 48 || deskNum == 1)
{
rowNum = 1;
}
else
{
rowNum = 2;
}
}
int deskCols = deskNum/rowNum;
if(deskNum == 0 || deskNum % rowNum != 0)
{
deskCols += 1;
}
int bh = (w/rowNum) + 1;
if ( desktopPreview() )
{
bh = (int) ( bh * (double) TQApplication::desktop()->height() / TQApplication::desktop()->width() );
}
else if ( m_settings->labelType() == PagerSettings::EnumLabelType::LabelName )
{
bh = fontMetrics().lineSpacing() + 8;
}
// we add one to the width for the spacing in between the buttons
// however, the last button doesn't have a space on the end of it (it's
// only _between_ buttons) so we then remove that one pixel
int nHg = (deskCols * (bh + 1)) - 1;
return nHg;
}
void KMiniPager::updateDesktopLayout(int o, int x, int y)
{
if ((desktopLayoutOrientation == o) &&
(desktopLayoutX == x) &&
(desktopLayoutY == y))
{
return;
}
desktopLayoutOrientation = o;
desktopLayoutX = x;
desktopLayoutY = y;
if( x == -1 ) // do-the-maths-yourself is encoded as 0 in the wm spec
x = 0;
if( y == -1 )
y = 0;
if( m_desktopLayoutOwner == NULL )
{ // must own manager selection before setting global desktop layout
int screen = DefaultScreen( tqt_xdisplay());
m_desktopLayoutOwner = new TDESelectionOwner( TQString( "_NET_DESKTOP_LAYOUT_S%1" ).arg( screen ).latin1(),
screen, TQT_TQOBJECT(this) );
if( !m_desktopLayoutOwner->claim( false ))
{
delete m_desktopLayoutOwner;
m_desktopLayoutOwner = NULL;
return;
}
}
NET::Orientation orient = o == Qt::Horizontal ? NET::OrientationHorizontal : NET::OrientationVertical;
NETRootInfo i( tqt_xdisplay(), 0 );
i.setDesktopLayout( orient, x, y, NET::DesktopLayoutCornerTopLeft );
}
void KMiniPager::resizeEvent(TQResizeEvent*)
{
bool horiz = orientation() == Qt::Horizontal;
int deskNum = m_desktops.count();
int rowNum = m_settings->numberOfRows();
if (rowNum == 0)
{
if (((horiz && height()<=32)||(!horiz && width()<=48)) || deskNum <= 1)
rowNum = 1;
else
rowNum = 2;
}
int deskCols = deskNum/rowNum;
if(deskNum == 0 || deskNum % rowNum != 0)
deskCols += 1;
if (m_layout)
{
delete m_layout;
m_layout = 0;
}
int nDX, nDY;
if (horiz)
{
nDX = rowNum;
nDY = deskCols;
updateDesktopLayout(Qt::Horizontal, -1, nDX);
}
else
{
nDX = deskCols;
nDY = rowNum;
updateDesktopLayout(Qt::Horizontal, nDY, -1);
}
// 1 pixel spacing.
m_layout = new TQGridLayout(this, nDX, nDY, 0, 1);
TQValueList<KMiniPagerButton*>::Iterator it = m_desktops.begin();
TQValueList<KMiniPagerButton*>::Iterator itEnd = m_desktops.end();
int c = 0,
r = 0;
while( it != itEnd ) {
c = 0;
while( (it != itEnd) && (c < nDY) ) {
m_layout->addWidget( *it, r, c );
++it;
++c;
}
++r;
}
m_layout->activate();
updateGeometry();
}
void KMiniPager::wheelEvent( TQWheelEvent* e )
{
int newDesk;
int desktops = KWin::numberOfDesktops();
if(cycleWindow()){
if (m_twin->numberOfViewports(0).width() * m_twin->numberOfViewports(0).height() > 1 )
desktops = m_twin->numberOfViewports(0).width() * m_twin->numberOfViewports(0).height();
if (e->delta() < 0)
{
newDesk = m_curDesk % desktops + 1;
}
else
{
newDesk = (desktops + m_curDesk - 2) % desktops + 1;
}
slotButtonSelected(newDesk);
}
}
void KMiniPager::drawButtons()
{
int deskNum = m_twin->numberOfDesktops();
KMiniPagerButton *desk;
int count = 1;
int i = 1;
do
{
TQSize viewportNum = m_twin->numberOfViewports(i);
for (int j = 1; j <= viewportNum.width() * viewportNum.height(); ++j)
{
TQSize s(m_twin->numberOfViewports(m_twin->currentDesktop()));
TQPoint viewport( (j-1) % s.width(), (j-1) / s.width());
desk = new KMiniPagerButton( count, m_useViewports, viewport, this );
if ( m_settings->labelType() != PagerSettings::EnumLabelType::LabelName )
{
TQToolTip::add( desk, desk->desktopName() );
}
m_desktops.append( desk );
m_group->insert( desk, count );
connect(desk, TQT_SIGNAL(buttonSelected(int)),
TQT_SLOT(slotButtonSelected(int)) );
connect(desk, TQT_SIGNAL(showMenu(const TQPoint&, int )),
TQT_SLOT(slotShowMenu(const TQPoint&, int )) );
desk->show();
++count;
}
}
while ( ++i <= deskNum );
}
void KMiniPager::slotSetDesktopCount( int )
{
TQSize s(m_twin->numberOfViewports(m_twin->currentDesktop()));
m_useViewports = s.width() * s.height() > 1;
TQValueList<KMiniPagerButton*>::ConstIterator it;
TQValueList<KMiniPagerButton*>::ConstIterator itEnd = m_desktops.end();
for( it = m_desktops.begin(); it != itEnd; ++it )
{
delete (*it);
}
m_desktops.clear();
drawButtons();
m_curDesk = m_twin->currentDesktop();
if ( m_curDesk == 0 )
{
m_curDesk = 1;
}
resizeEvent(0);
updateLayout();
}
void KMiniPager::slotRefreshViewportCount( int )
{
TQSize s(m_twin->numberOfViewports(m_twin->currentDesktop()));
m_useViewports = s.width() * s.height() > 1;
TQValueList<KMiniPagerButton*>::ConstIterator it;
TQValueList<KMiniPagerButton*>::ConstIterator itEnd = m_desktops.end();
for( it = m_desktops.begin(); it != itEnd; ++it )
{
delete (*it);
}
m_desktops.clear();
drawButtons();
m_curDesk = m_twin->currentDesktop();
if ( m_curDesk == 0 )
{
m_curDesk = 1;
}
resizeEvent(0);
updateLayout();
}
void KMiniPager::slotActiveWindowChanged( WId win )
{
if (desktopPreview())
{
KWin::WindowInfo* inf1 = m_activeWindow ? info( m_activeWindow ) : NULL;
KWin::WindowInfo* inf2 = win ? info( win ) : NULL;
m_activeWindow = win;
TQValueList<KMiniPagerButton*>::ConstIterator it;
TQValueList<KMiniPagerButton*>::ConstIterator itEnd = m_desktops.end();
for ( it = m_desktops.begin(); it != itEnd; ++it)
{
if ( ( inf1 && (*it)->shouldPaintWindow(inf1)) ||
( inf2 && (*it)->shouldPaintWindow(inf2)) )
{
(*it)->windowsChanged();
}
}
}
}
void KMiniPager::slotWindowAdded( WId win)
{
if (desktopPreview())
{
KWin::WindowInfo* inf = info( win );
if (inf->state() & NET::SkipPager)
{
return;
}
TQValueList<KMiniPagerButton*>::ConstIterator it;
TQValueList<KMiniPagerButton*>::ConstIterator itEnd = m_desktops.end();
for ( it = m_desktops.begin(); it != itEnd; ++it)
{
if ( (*it)->shouldPaintWindow(inf) )
{
(*it)->windowsChanged();
}
}
}
}
void KMiniPager::slotWindowRemoved(WId win)
{
if (desktopPreview())
{
KWin::WindowInfo* inf = info(win);
bool onAllDesktops = inf->onAllDesktops();
bool onAllViewports = inf->hasState(NET::Sticky);
bool skipPager = inf->state() & NET::SkipPager;
int desktop = inf->desktop();
if (win == m_activeWindow)
m_activeWindow = 0;
m_windows.remove((long) win);
if (skipPager)
{
return;
}
TQValueList<KMiniPagerButton*>::ConstIterator it;
TQValueList<KMiniPagerButton*>::ConstIterator itEnd = m_desktops.end();
for (it = m_desktops.begin(); it != itEnd; ++it)
{
if (onAllDesktops || onAllViewports || desktop == (*it)->desktop())
{
(*it)->windowsChanged();
}
}
}
else
{
m_windows.remove(win);
return;
}
}
void KMiniPager::slotWindowChanged( WId win , unsigned int properties )
{
if ((properties & (NET::WMState | NET::XAWMState | NET::WMDesktop)) == 0 &&
(!desktopPreview() || (properties & NET::WMGeometry) == 0) &&
!(desktopPreview() && windowIcons() &&
(properties & NET::WMIcon | NET::WMIconName | NET::WMVisibleIconName) == 0))
{
return;
}
if (desktopPreview())
{
KWin::WindowInfo* inf = m_windows[win];
bool skipPager = inf->hasState(NET::SkipPager);
TQMemArray<bool> old_shouldPaintWindow(m_desktops.size());
TQValueList<KMiniPagerButton*>::ConstIterator it;
TQValueList<KMiniPagerButton*>::ConstIterator itEnd = m_desktops.end();
int i = 0;
for ( it = m_desktops.begin(); it != itEnd; ++it)
{
old_shouldPaintWindow[i++] = (*it)->shouldPaintWindow(inf);
}
m_windows.remove(win);
inf = info(win);
if (inf->hasState(NET::SkipPager) || skipPager)
{
return;
}
for ( i = 0, it = m_desktops.begin(); it != itEnd; ++it)
{
if ( old_shouldPaintWindow[i++] || (*it)->shouldPaintWindow(inf))
{
(*it)->windowsChanged();
}
}
}
else
{
m_windows.remove(win);
return;
}
}
KWin::WindowInfo* KMiniPager::info( WId win )
{
if (!m_windows[win])
{
KWin::WindowInfo* info = new KWin::WindowInfo( win,
NET::WMWindowType | NET::WMState | NET::XAWMState | NET::WMDesktop | NET::WMGeometry | NET::WMKDEFrameStrut, 0 );
m_windows.insert(win, info);
return info;
}
return m_windows[win];
}
KTextShadowEngine* KMiniPager::shadowEngine()
{
if (!m_shadowEngine)
m_shadowEngine = new KTextShadowEngine();
return m_shadowEngine;
}
void KMiniPager::refresh()
{
TQValueList<KMiniPagerButton*>::ConstIterator it;
TQValueList<KMiniPagerButton*>::ConstIterator itEnd = m_desktops.end();
for ( it = m_desktops.begin(); it != itEnd; ++it)
{
(*it)->update();
}
}
void KMiniPager::aboutToShowContextMenu()
{
m_contextMenu->clear();
m_contextMenu->insertItem(SmallIcon("kpager"), i18n("&Launch Pager"), LaunchExtPager);
m_contextMenu->insertSeparator();
m_contextMenu->insertItem(i18n("&Rename Desktop \"%1\"")
.arg(twin()->desktopName(m_rmbDesk)), RenameDesktop);
m_contextMenu->insertSeparator();
TDEPopupMenu* showMenu = new TDEPopupMenu(m_contextMenu);
showMenu->setCheckable(true);
showMenu->insertTitle(i18n("Pager Layout"));
TQPopupMenu* rowMenu = new TQPopupMenu(showMenu);
rowMenu->setCheckable(true);
rowMenu->insertItem(i18n("&Automatic"), 0 + rowOffset);
rowMenu->insertItem(i18n("one row or column", "&1"), 1 + rowOffset);
rowMenu->insertItem(i18n("two rows or columns", "&2"), 2 + rowOffset);
rowMenu->insertItem( i18n("three rows or columns", "&3"), 3 + rowOffset);
connect(rowMenu, TQT_SIGNAL(activated(int)), TQT_SLOT(contextMenuActivated(int)));
showMenu->insertItem((orientation()==Qt::Horizontal) ? i18n("&Rows"):
i18n("&Columns"),
rowMenu);
showMenu->insertItem(i18n("&Window Thumbnails"), WindowThumbnails);
showMenu->insertItem(i18n("&Window Icons"), WindowIcons);
showMenu->insertItem(i18n("&Cycle on Wheel"), Cycle);
showMenu->insertTitle(i18n("Text Label"));
showMenu->insertItem(i18n("Desktop N&umber"),
PagerSettings::EnumLabelType::LabelNumber + labelOffset);
showMenu->insertItem(i18n("Desktop N&ame"),
PagerSettings::EnumLabelType::LabelName + labelOffset);
showMenu->insertItem(i18n("N&o Label"),
PagerSettings::EnumLabelType::LabelNone + labelOffset);
showMenu->insertTitle(i18n("Background"));
showMenu->insertItem(i18n("&Elegant"),
PagerSettings::EnumBackgroundType::BgPlain + bgOffset);
showMenu->insertItem(i18n("&Transparent"),
PagerSettings::EnumBackgroundType::BgTransparent + bgOffset);
if (m_useViewports == false) {
showMenu->insertItem(i18n("&Desktop Wallpaper"),
PagerSettings::EnumBackgroundType::BgLive + bgOffset);
}
connect(showMenu, TQT_SIGNAL(activated(int)), TQT_SLOT(contextMenuActivated(int)));
m_contextMenu->insertItem(i18n("&Pager Options"),showMenu);
m_contextMenu->insertItem(SmallIcon("configure"),
i18n("&Configure Desktops..."),
ConfigureDesktops);
rowMenu->setItemChecked(m_settings->numberOfRows() + rowOffset, true);
m_contextMenu->setItemChecked(m_settings->labelType() + labelOffset, showMenu);
m_contextMenu->setItemChecked(m_settings->backgroundType() + bgOffset, showMenu);
m_contextMenu->setItemChecked(WindowThumbnails, m_settings->preview());
m_contextMenu->setItemChecked(WindowIcons, m_settings->icons());
m_contextMenu->setItemChecked(Cycle, m_settings->cycle());
m_contextMenu->setItemEnabled(WindowIcons, m_settings->preview());
m_contextMenu->setItemEnabled(RenameDesktop,
m_settings->labelType() ==
PagerSettings::EnumLabelType::LabelName);
}
void KMiniPager::slotShowMenu(const TQPoint& pos, int desktop)
{
if (!m_contextMenu)
{
return;
}
m_rmbDesk = desktop;
m_contextMenu->exec(pos);
m_rmbDesk = -1;
}
void KMiniPager::contextMenuActivated(int result)
{
if (result < 1)
{
return;
}
switch (result)
{
case LaunchExtPager:
showPager();
return;
case ConfigureDesktops:
kapp->startServiceByDesktopName("desktop");
return;
case RenameDesktop:
m_desktops[(m_rmbDesk == -1) ? m_curDesk - 1 : m_rmbDesk - 1]->rename();
return;
}
if (result >= rowOffset)
{
m_settings->setNumberOfRows(result - rowOffset);
resizeEvent(0);
}
switch (result)
{
case WindowThumbnails:
m_settings->setPreview(!m_settings->preview());
TaskManager::the()->trackGeometry();
break;
case Cycle:
m_settings->setCycle(!m_settings->cycle());
break;
case WindowIcons:
m_settings->setIcons(!m_settings->icons());
break;
case PagerSettings::EnumBackgroundType::BgPlain + bgOffset:
m_settings->setBackgroundType(PagerSettings::EnumBackgroundType::BgPlain);
break;
case PagerSettings::EnumBackgroundType::BgTransparent + bgOffset:
m_settings->setBackgroundType(PagerSettings::EnumBackgroundType::BgTransparent);
break;
case PagerSettings::EnumBackgroundType::BgLive + bgOffset:
{
if (m_useViewports == false) {
m_settings->setBackgroundType(PagerSettings::EnumBackgroundType::BgLive);
TQValueList<KMiniPagerButton*>::ConstIterator it;
TQValueList<KMiniPagerButton*>::ConstIterator itEnd = m_desktops.end();
for( it = m_desktops.begin(); it != itEnd; ++it )
{
(*it)->backgroundChanged();
}
}
else {
m_settings->setBackgroundType(PagerSettings::EnumBackgroundType::BgTransparent);
}
break;
}
case PagerSettings::EnumLabelType::LabelNone + labelOffset:
m_settings->setLabelType(PagerSettings::EnumLabelType::LabelNone);
break;
case PagerSettings::EnumLabelType::LabelNumber + labelOffset:
m_settings->setLabelType(PagerSettings::EnumLabelType::LabelNumber);
break;
case PagerSettings::EnumLabelType::LabelName + labelOffset:
m_settings->setLabelType(PagerSettings::EnumLabelType::LabelName);
break;
}
m_settings->writeConfig();
updateGeometry();
refresh();
}
void KMiniPager::slotDesktopNamesChanged()
{
TQValueList<KMiniPagerButton*>::ConstIterator it = m_desktops.begin();
TQValueList<KMiniPagerButton*>::ConstIterator itEnd = m_desktops.end();
for (int i = 1; it != itEnd; ++it, ++i)
{
TQString name = m_twin->desktopName(i);
(*it)->setDesktopName(name);
(*it)->repaint();
TQToolTip::remove((*it));
TQToolTip::add((*it), name);
}
updateLayout();
}
void KMiniPager::showPager()
{
DCOPClient *dcop=kapp->dcopClient();
if (dcop->isApplicationRegistered("kpager"))
{
showKPager(true);
}
else
{
// Let's run kpager if it isn't running
connect( dcop, TQT_SIGNAL( applicationRegistered(const TQCString &) ), this, TQT_SLOT(applicationRegistered(const TQCString &)) );
dcop->setNotifications(true);
TQString strAppPath(locate("exe", "kpager"));
if (!strAppPath.isEmpty())
{
TDEProcess process;
process << strAppPath;
process << "--hidden";
process.start(TDEProcess::DontCare);
}
}
}
void KMiniPager::showKPager(bool toggleShow)
{
TQPoint pt;
switch ( position() )
{
case pTop:
pt = mapToGlobal( TQPoint(x(), y() + height()) );
break;
case pLeft:
pt = mapToGlobal( TQPoint(x() + width(), y()) );
break;
case pRight:
case pBottom:
default:
pt=mapToGlobal( TQPoint(x(), y()) );
}
DCOPClient *dcop=kapp->dcopClient();
TQByteArray data;
TQDataStream arg(data, IO_WriteOnly);
arg << pt.x() << pt.y() ;
if (toggleShow)
{
dcop->send("kpager", "KPagerIface", "toggleShow(int,int)", data);
}
else
{
dcop->send("kpager", "KPagerIface", "showAt(int,int)", data);
}
}
void KMiniPager::applicationRegistered( const TQCString & appName )
{
if (appName == "kpager")
{
disconnect( kapp->dcopClient(), TQT_SIGNAL( applicationRegistered(const TQCString &) ),
this, TQT_SLOT(applicationRegistered(const TQCString &)) );
showKPager(false);
}
}
| gpl-2.0 |
bfay/maniacal-kitten | wp-content/themes/smartbox-theme-1.01/inc/core/admin/assets/js/shortcodes/shortcodes.js | 7941 | /* Oxygenna Shortcode Generator Javascript ver 0.1 */
(function( $ ){
$.fn.scGenerator = function( options ) {
// Create some defaults, extending them with any options that were provided
var settings = $.extend( {
'shortcode-select' : '#shortcode'
}, options
);
var codes = {
// layout : createColumns,
// tabs : createTabs,
// accordion_section : createAccordion,
// heading : createHeading,
// services : createServices
};
var lineBreak;
$.fn.extend({
getCode : function() {
var sc = null;
var $code = $(settings['shortcode-select']);
var code = $code.val();
if( '' != code ) {
// check for special code
if( 'function' === typeof codes[code] ) {
sc = codes[code].apply( this , [code] );
}
else { // simple standard code
sc = createCode( code );
}
}
return sc;
}
});
function createCode( name ) {
// start shortcode
var sc = '[' + name;
// fetch attribute inputs except content one
var inputs = $(':input[name^="' + name + '_"]').not( ':input[id="' + name + '_content"]' );
// create attributes
inputs.each( function() {
sc += createAttribute( $(this), name );
});
// check for content
sc += createContent( name );
return sc;
}
function createAttribute( $input, name ) {
var value = getInputValue( $input );
// if value is the default value then we skip it to
// keep shortcodes short
if( $input.attr( 'data-default' ) == value ) {
value = null;
}
if( null !== value ) {
var name = $input.attr('name').replace( name + '_', '' ).replace( '[]', '');
return ' ' + name + '="' + value + '"';
}
else {
return '';
}
}
function getInputValue( $input ) {
var value = null;
if( $input.is( 'select' ) ) {
if( $input.attr( 'multiple' ) == 'multiple' ) {
value = $input.val() || [];
value = value.join(',');
}
else {
value = $input.val();
}
}
else if( $input.is( 'input[type="radio"]' ) ) {
if( $input.is( ':checked' ) ) {
value = $input.val();
}
}
else {
value = $input.val();
}
return value;
}
function createContent( name ) {
var content = $( '#' + name + '_content' );
var returnVal = ']';
if( content.length > 0 ) {
content = getInputValue( content );
// if name has postfix _content then use as content
if( content !== null ) {
// create content
returnVal = ']' + content.replace(/\n/g,lineBreak) + '[/' + name + ']';
}
}
return returnVal;
}
function createColumns( name ) {
var number = $( '#' + name + '_columns' ).val();
var sc = '';
for( var i = 1 ; i <= number ; i++ ) {
// create code then remove postfix (half_col1 goes to half)
var input = $( '#' + name + '_' + i );
sc += '[' + input.attr('data-shortcode') + ']' + input.val() + '[/' + input.attr('data-shortcode') + ']';
}
return sc;
}
function createTabs( name ) {
var number = $( '#tabs_details' ).val();
var sc = '[tabs]' + lineBreak;
for( var i = 1 ; i <= number ; i++ ) {
var title = $( ':input[name="tabs_details_title' + i + '"]:enabled' );
var content = $( ':input[name="tabs_details_content' + i + '"]:enabled' );
sc += '[tab title="' + title.val() + '"]' + lineBreak;
sc += content.val();
sc += lineBreak + '[/tab]' + lineBreak;
}
sc += '[/tabs]';
return sc;
}
function createAccordion( name ) {
var number = $( '#accordion_details' ).val();
var sc = '[accordions]' + lineBreak;
for( var i = 1 ; i <= number ; i++ ) {
var title = $( ':input[name="accordion_details_title' + i + '"]:enabled' );
var content = $( ':input[name="accordion_details_content' + i + '"]:enabled' );
sc += '[accordion title="' + title.val() + '"]' + lineBreak;
sc += content.val();
sc += lineBreak + '[/accordion]' + lineBreak;
}
sc += '[/accordions]';
return sc;
}
function createHeading( name ) {
// get size of heading
var size = jQuery('input[name="heading_size"]:checked').val();
// get extra attributes
var line = createAttribute( jQuery('input[name="heading_line"]:checked') , 'heading' );
var align = createAttribute( jQuery('input[name="heading_align"]:checked') , 'heading' );
var background = createAttribute( jQuery('input[name="heading_icon_background"]:checked') , 'heading' );
var icon = createAttribute( jQuery('input[name="heading_icon_content"]') , 'heading' );
var font = createAttribute( jQuery('select[name="heading_icon_font"]') , 'heading' );
var colour = createAttribute( jQuery('input[name="heading_icon_colour"]') , 'heading' );
var sc = '[h' + size + line + align + icon + background + font + colour + ']' + $( '#heading_content' ).val() + '[/h' + size + ']';
return sc;
}
function createServices( name ) {
var number = $( '#services_count' ).val();
var sc = '[services]' + lineBreak;
for( var i = 1 ; i <= number ; i++ ) {
var title = $( 'input[name="services_details_title' + i + '"]:enabled' );
var icon = $( 'input[name="services_details_icon' + i + '"]:enabled' );
var content = $( 'textarea[name="services_details_content' + i + '"]:enabled' );
var font = $( 'select[name="services_details_icon' + i + '_font"]:enabled' );
sc += '[service title="' + title.val() + '" icon="' + icon.val() + '" font="' + font.val() + '"]' + lineBreak;
sc += content.val();
sc += lineBreak + '[/service]' + lineBreak;
}
sc += '[/services]';
return sc;
}
return this.each(function() {
var $this = $(this);
lineBreak = hasMCE ? '<br />' : '\n';
//set title of tinymcepopup
if( hasMCE ) {
document.title = tinyMCEPopup.getWindowArg("title_param");
}
$this.bind( 'submit', function() {
var code = $this.getCode();
if( null !== code ) {
if( hasMCE ) {
tinyMCEPopup.execCommand( 'mceInsertContent', false, code );
}
else {
var win = window.dialogArguments || opener || parent || top;
win.send_to_editor( code );
}
closeWindow();
}
return false;
});
});
};
})( jQuery ); | gpl-2.0 |
hubnedav/PrintABrick | src/AppBundle/Model/SetSearch.php | 1444 | <?php
namespace AppBundle\Model;
use AppBundle\Entity\Rebrickable\Theme;
class SetSearch
{
/** @var string */
protected $query;
/** @var NumberRange */
protected $year;
/** @var NumberRange */
protected $partCount;
/** @var Theme */
protected $theme;
/**
* SetSearch constructor.
*
* @param string $query
*/
public function __construct($query = '')
{
$this->query = $query;
}
/**
* @return string
*/
public function getQuery()
{
return $this->query;
}
/**
* @param string $query
*/
public function setQuery($query)
{
$this->query = $query;
}
/**
* @return NumberRange
*/
public function getYear()
{
return $this->year;
}
/**
* @param NumberRange $year
*/
public function setYear($year)
{
$this->year = $year;
}
/**
* @return NumberRange
*/
public function getPartCount()
{
return $this->partCount;
}
/**
* @param NumberRange $partCount
*/
public function setPartCount($partCount)
{
$this->partCount = $partCount;
}
/**
* @return Theme
*/
public function getTheme()
{
return $this->theme;
}
/**
* @param Theme $theme
*/
public function setTheme($theme)
{
$this->theme = $theme;
}
}
| gpl-2.0 |
elbeardmorez/quodlibet | quodlibet/tests/test_cli.py | 854 | # -*- coding: utf-8 -*-
# Copyright 2014 Nick Boultbee
#
# 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.
from .helper import capture_output
from quodlibet import cli
from tests import TestCase
class Tcli(TestCase):
def test_process_no_arguments_works(self):
with capture_output() as (out, err):
cli.process_arguments(["myprog"])
self.assertFalse(out.getvalue())
self.assertFalse(err.getvalue())
def test_process_arguments_errors_on_invalid_opt(self):
with self.assertRaises(SystemExit):
with capture_output():
cli.process_arguments(["myprog", "--wrong-thing"])
| gpl-2.0 |
jilgue/ownWebAppServices | DB/classes/DBObject.php | 3396 | <?php
/**
* DB Object
*/
abstract class DBObject extends ObjectPersistent {
static $table;
protected function __construct($params = array()) {
parent::__construct($params);
$this->_loadObj();
}
private function _loadObj() {
if (!$this->ok) {
return;
}
$table = DBObject::stGetTableName(get_class($this));
$dbObj = DBMySQLConnection::stVirtualConstructor($table)->getObj(array($this->fieldId => $this->objectId));
$fields = DBObject::stDBToObjFields($table);
foreach ($dbObj as $dbField => $data) {
$this->$fields[$dbField] = $data;
}
}
/**
* Convert the format a DB field (separation with low bar) to Obj field (camelcase)
* Inverse to stObjFieldToDBField
*/
static function stDBFieldToObjField($field) {
$pieces = explode("_", $field);
$ret = "";
foreach ($pieces as $piece) {
$ret = $ret . ucfirst($piece);
}
return lcfirst($ret);
}
/**
* Convert the format a Obj field to DB field
* Inverse to stDBFieldToObjField
*/
static function stObjFieldToDBField($field) {
if (!preg_match_all('/((?:^|[A-Z])([a-z]|[0-9])+)/', $field, $matches)) {
return $field;
}
$ret = "";
foreach (reset($matches) as $piece) {
$ret = $ret . "_" . lcfirst($piece);
}
return substr($ret, 1);
}
private static function _stGetTableFields($table) {
$conn = DBMySQLConnection::stVirtualConstructor(array("table" => $table));
return $conn->describeTableFields();
}
static function stDBToObjFields($table) {
$fields = DBObject::_stGetTableFields($table);
$ret = array();
foreach ($fields as $row) {
$field = $row["Field"];
$ret[$field] = DBObject::stDBFieldToObjField($field);
}
return $ret;
}
static function stObjToDBFields($table) {
return array_flip(DBObject::stDBToObjFields($table));
}
static function stGetTableName($class) {
// TODO mirar si se hace de otra manera
return strtolower($class);
}
/**
* Es publica porque también lo usan clases "hermanas" como DBObjectSearch
*/
static function _stGetMySQLParams() {
$class = get_called_class();
$fieldId = $class::stGetFieldConfigFiltered(array("identifier" => true));
$table = DBObject::stGetTableName($class);
return array("table" => $table,
"fieldId" => $fieldId);
}
protected static function _stExists($objId) {
$mysqlParams = static::_stGetMySQLParams();
return (bool) DBMySQLConnection::stVirtualConstructor($mysqlParams)->existObj($objId);
}
protected static function _stCreate($params) {
$class = get_called_class();
$dbObj = array();
foreach ($params as $field => $value) {
if (isset($params[$field])) {
$dbObj[DBObject::stObjFieldToDBField($field)] = $value;
}
}
$mysqlParams = static::_stGetMySQLParams();
return DBMySQLConnection::stVirtualConstructor($mysqlParams)->createObj($dbObj);
}
protected function _save() {
$dbObj = array();
// TODO usar stObjToDBFields
foreach ($this->_getStoredParams() as $field => $value) {
$dbObj[DBObject::stObjFieldToDBField($field)] = $value;
}
$mysqlParams = static::_stGetMySQLParams();
return (bool) DBMySQLConnection::stVirtualConstructor($mysqlParams)->updateObj($dbObj, $this->_getObjectId());
}
protected function _delete() {
$mysqlParams = static::_stGetMySQLParams();
return (bool) DBMySQLConnection::stVirtualConstructor($mysqlParams)->deleteObj($this->_getObjectId());
}
}
| gpl-2.0 |
tud-stg-lang/caesar-compiler | src/org/caesarj/runtime/perobject/AspectPerThisDeployer.java | 2215 | package org.caesarj.runtime.perobject;
import org.caesarj.runtime.PerThisDeployable;
import org.caesarj.runtime.aspects.AbstractAspectRegistry;
import org.caesarj.runtime.aspects.AspectContainerIfc;
import org.caesarj.runtime.aspects.AspectRegistryIfc;
import org.caesarj.runtime.aspects.BasicAspectDeployer;
public class AspectPerThisDeployer extends BasicAspectDeployer {
protected Object _deployKey = null;
/**
* Sets current key for deployment
*
* @param key Object, used as key for deployment
*/
protected void setDeployKey(Object key)
{
_deployKey = key;
}
/**
* Deploy aspect on object
*
* @param aspObj aspect object
* @param key deployment key object
*/
public synchronized void deployOnObject(PerThisDeployable aspObj, Object key)
{
setDeployKey(key);
$deployOn(aspObj.$getAspectRegistry(), aspObj);
}
/**
* Undeploy aspect from object
*
* @param aspObj aspect object
* @param key deployment key object
*/
public synchronized void undeployFromObject(PerThisDeployable aspObj, Object key)
{
setDeployKey(key);
$undeployFrom(aspObj.$getAspectRegistry(), aspObj);
}
/**
* Create specific container object
*
* @return New container object
*/
public AspectContainerIfc createContainer(AspectRegistryIfc reg) {
return new AspectThisObjectMapper(getContId(), (AbstractAspectRegistry)reg);
}
/**
* Deploy object on the container
*
* @param cont Aspect container
* @param aspectObj Object to be deployed
* @param reg Aspect registry (for read-only usage)
*/
public void deployOnContainer(AspectContainerIfc cont, Object aspectObj, AspectRegistryIfc reg) {
AspectThisObjectMapper objectMapper = (AspectThisObjectMapper)cont;
objectMapper.deployObject(aspectObj, _deployKey);
}
/**
* Undeploy object from the container
*
* @param cont Aspect container
* @param aspectObj Object to be undeployed
* @param reg Aspect registry (for read-only usage)
*/
public void undeployFromContainer(AspectContainerIfc cont, Object aspectObj, AspectRegistryIfc reg) {
AspectThisObjectMapper objectMapper = (AspectThisObjectMapper)cont;
objectMapper.undeployObject(aspectObj, _deployKey);
}
}
| gpl-2.0 |
hungdinh/t3v3 | plugins/system/jat3v3/includes/depend/tpls/profile.php | 3540 | <?php
/**
* $JA#COPYRIGHT$
*/
// no direct access
defined ( '_JEXEC' ) or die ( 'Restricted access' );
?>
<script type="text/javascript">
!function($){
var JAFileConfig = window.JAFileConfig || {};
JAFileConfig.profiles = <?php echo json_encode($jsonData)?>;
JAFileConfig.mod_url = '<?php echo JURI::base(true); ?>/modules/<?php echo $module; ?>/helper.php';
JAFileConfig.template = '<?php echo $template?>';
JAFileConfig.langs = <?php json_encode(array(
confirmCancel: JText::_('ARE_YOUR_SURE_TO_CANCEL'),
enterName: JText::_('ENTER_PROFILE_NAME'),
correctName: JText::_('PROFILE_NAME_NOT_EMPTY'),
confirmDelete: JText::_('CONFIRM_DELETE_PROFILE')
)); ?>;
$(window).on('load', function(){
JAFileConfig.initialize('jformparams<?php echo str_replace('holder', '', $this->fieldname);?>');
JAFileConfig.changeProfile($('jformparams<?php echo str_replace('holder', '', $this->fieldname);?>').val());
});
}(window.$ja || window.jQuery);
</script>
<div class="ja-profile">
<label class="hasTip" for="jform_params_<?php echo $this->field_name?>" id="jform_params_<?php echo $this->field_name?>-lbl" title="<?php echo JText::_($this->element['description'])?>"><?php echo JText::_($this->element["label"])?></label>
<?php echo $profileHTML; ?>
<div class="profile_action">
<span class="clone">
<a href="javascript:void(0)" onclick="JAFileConfig.cloneProfile()" title="<?php echo JText::_('CLONE_DESC')?>"><?php echo JText::_('Clone')?></a>
</span>
|
<span class="delete">
<a href="javascript:void(0)" onclick="JAFileConfig.deleteProfile()" title="<?php echo JText::_('DELETE_DESC')?>"><?php echo JText::_('Delete')?></a>
</span>
</div>
</div>
</div>
<?php
$fieldSets = $jaform->getFieldsets('params');
foreach ($fieldSets as $name => $fieldSet) :
if (isset($fieldSet->description) && trim($fieldSet->description)){
echo '<p class="tip">'.JText::_($fieldSet->description).'</p>';
}
$hidden_fields = '';
foreach ($jaform->getFieldset($name) as $field) :
if (!$field->hidden) : ?>
<div class="control-group">
<div class="control-label">
<?php echo $jaform->getLabel($field->fieldname,$field->group); ?>
</div>
<div class="controls">
<?php echo $jaform->getInput($field->fieldname,$field->group); ?>
</div>
</div>
<?php
else :
$hidden_fields .= $jaform->getInput($field->fieldname,$field->group);
endif;
endforeach;
echo $hidden_fields;
endforeach;
?>
<div class="control-group hide">
<div class="control-label"></div>
<div class="controls">
<script type="text/javascript">
// <![CDATA[
window.addEvent('load', function(){
Joomla.submitbutton = function(task){
if (task == 'module.cancel' || document.formvalidator.isValid(document.id('module-form'))) {
if(task != 'module.cancel' && document.formvalidator.isValid(document.id('module-form'))){
JAFileConfig.saveProfile(task);
}else if(task == 'module.cancel' || document.formvalidator.isValid(document.id('module-form'))){
Joomla.submitform(task, document.getElementById('module-form'));
}
if (self != top) {
window.top.setTimeout('window.parent.SqueezeBox.close()', 1000);
}
} else {
alert('Invalid form');
}
}
});
// ]]>
</script>
</div>
</div>
<div class="control-group hide">
<div class="control-label"></div>
<div class="controls"> | gpl-2.0 |
zhangbojr/ICB | DAL/ICaiban.DAL/Merchant/Tab_Seat_SettingDAL.cs | 6614 | /*=====================================================================
* Copyright © 2014 www.icaiban.com All Rights Reserved.
* CLR版本: 4.0.30319.18444
* 类名称: Tab_Seat_SettingDAL:餐台功能设置数据处理
* 创建人: jimmy
* 创建时间:2014/10/11 9:44:27
* 修改人:
* 修改时间:
* 修改备注:
* 版本:@version 1.0
===================================================================== */
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using ICaiBan.DAL.Common;
using ICaiBan.Framework.DB;
using ICaiBan.Framework.ORM;
using ICaiBan.ModelBL.Enums;
using ICaiBan.ModelBL.Merchant;
using ICaiBan.ModelDB;
namespace ICaiBan.DAL
{
public class Tab_Seat_SettingDAL
{
internal static EntityDbContext<Tab_Seat_Setting> caiBanDbContext=EntityDbContext<Tab_Seat_Setting>.GetInstance(Config.ConnString);
#region 查询
/// <summary>
/// 通过餐台Id查询座位功能
/// </summary>
/// <param name="seatId">餐台Id</param>
/// <returns>返回座位功能</returns>
/// <remarks>addded by jimmy,2014-10-11</remarks>
public static List<CallType> GetSeatFunction(decimal seatId)
{
List<CallType> list=null;
DataSet ds=SqlDbHelper.Execute(Config.ConnString, CommandType.Text, "SELECT Seat_Function from Tab_Seat_Setting where Seat_Id = @Seat_Id", new SqlParameter("@Seat_Id", seatId));
if(ds!=null && ds.Tables.Count > 0)
{
list=new List<CallType>();
DataTable dt=ds.Tables[0];
for (int i=0; i < dt.Rows.Count; i++)
{
list.Add((CallType) ConvertObjectData.ConvertToDecimal(dt.Rows[i]["Seat_Function"]));
}
}
return list;
}
#endregion
#region 新增餐台功能设置
/// <summary>
/// 新增餐台功能设置
/// </summary>
/// <param name="bl">餐台功能</param>
/// <param name="newid">自动增长Id</param>
/// <returns>返回true时,表示新增成功;反之,则表示新增失败</returns>
/// <remarks>added by jimmy,2014-10-11</remarks>
public static bool Add(SeatSettingBL bl, out string newid)
{
Tab_Seat_Setting model=new Tab_Seat_Setting();
model.Seat_Id=bl.SeatId;
model.Seat_Function=(decimal) bl.SeatFunction;
model.Create_Time=bl.CreateTime;
model.Modify_Time=bl.ModifyTime;
return caiBanDbContext.Insert(model, out newid);
}
#endregion
#region 更新或添加座位功能设置
/// <summary>
/// 更新或添加座位功能设置
/// </summary>
/// <param name="seatId">餐台ID</param>
/// <param name="proList">餐台功能集合</param>
/// <param name="msg">返回消息</param>
/// <returns>更新是否成功</returns>
/// <remarks>addded by jimmy,2014-10-11</remarks>
public static bool UpdateOrAdd(decimal seatId, List<SeatSettingBL> SeatSettingList, out string msg)
{
//先删除相关座位功能的设置
SqlDbHelper.ExecuteNonQuery(Config.ConnString, CommandType.Text, "delete from Tab_Seat_Setting where Seat_Id = @Seat_Id", new SqlParameter("@Seat_Id", seatId));
if(SeatSettingList==null || SeatSettingList.Count < 1)
{
msg="更新成功!";
return true;
}
int flag=0;
string sql=@"SELECT * from Tab_Seat_Setting where Seat_Id = @Seat_Id";
SqlDataAdapter da;
DataSet ds=SqlDbHelper.Execute(Config.ConnString, CommandType.Text, sql, out da, new SqlParameter("@Seat_Id", seatId));
if(ds!=null && ds.Tables.Count > 0)
{
DataTable dt=ds.Tables[0];
foreach(var item in SeatSettingList)
{
DataRow dr=dt.NewRow();
dr["Seat_Setting_Id"]=item.SeatSettingId;
dr["Seat_Id"]=seatId;
dr["Seat_Function"]=(decimal) item.SeatFunction;
dr["Create_Time"]=item.CreateTime;
dr["Modify_Time"]=item.CreateTime;
dt.Rows.Add(dr);
}
flag=SqlDbHelper.ExecuteUpdates(Config.ConnString, ds, da);
if(flag==-1)
{
msg="更新前,数据已被删除!";
}
else if(flag > 0)
msg="更新成功";
else
msg="更新失败";
}
else
msg="没有要更新的数据!";
return flag > 0;
}
#endregion
#region 集合转换
static List<SeatSettingBL> ConvertDataTable(DataTable dt)
{
List<SeatSettingBL> list=null;
if(dt!=null && dt.Rows.Count > 0)
{
list=new List<SeatSettingBL>();
SeatSettingBL bl;
for (int i=0; i < dt.Rows.Count; i++)
{
bl=new SeatSettingBL();
#region 取值
if(dt.Columns.Contains("Seat_Setting_Id"))
{
bl.SeatSettingId=ConvertObjectData.ConvertToDecimal(dt.Rows[i]["Seat_Setting_Id"]);
}
if(dt.Columns.Contains("Seat_Id"))
{
bl.SeatId=ConvertObjectData.ConvertToDecimal(dt.Rows[i]["Seat_Id"]);
}
if(dt.Columns.Contains("Seat_Function"))
{
bl.SeatFunction=(CallType) ConvertObjectData.ConvertToDecimal(dt.Rows[i]["Seat_Function"]);
}
if(dt.Columns.Contains("Create_Time"))
{
bl.CreateTime=ConvertObjectData.ConvertToDateTime(dt.Rows[i]["Create_Time"]);
}
if(dt.Columns.Contains("Modify_Time"))
{
bl.ModifyTime=ConvertObjectData.ConvertToDateTimeNull(dt.Rows[i]["Modify_Time"]);
}
list.Add(bl);
#endregion
}
}
return list;
}
#endregion
}
} | gpl-2.0 |
wangguodong577/qqj-backend | core/src/main/java/com/qqj/org/controller/legacy/pojo/LoginResponse.java | 728 | package com.qqj.org.controller.legacy.pojo;
import com.qqj.error.RestError;
/**
* User: xudong
* Date: 3/2/15
* Time: 3:34 PM
*/
public class LoginResponse extends RestError {
private Long userId;
private String username;
private String userNumber;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserNumber() {
return userNumber;
}
public void setUserNumber(String userNumber) {
this.userNumber = userNumber;
}
}
| gpl-2.0 |
themesbros/mosalon | misc/loop-meta.php | 2122 | <?php if ( ! is_mosalon_landing_page() ) : ?>
<div <?php hybrid_attr( 'loop-meta' ); ?>>
<?php $img = esc_url( get_theme_mod( 'loop_img', trailingslashit( get_template_directory_uri() ) . 'images/sep.png' ) ); ?>
<?php if ( ! empty( $img ) ) : ?>
<div class="loop-img"></div>
<?php endif; ?>
<?php if ( is_front_page() || is_page() ) :
$title = get_theme_mod( 'loop_title_page', __( 'Company Info', 'mosalon' ) );
$desc = get_theme_mod( 'loop_subtitle_page', __( 'Company slogan', 'mosalon' ) );
elseif ( function_exists( "is_woocommerce" ) && is_woocommerce() ) :
$title = get_theme_mod( 'loop_title_page', __( 'Company Info', 'mosalon' ) );
$desc = get_theme_mod( 'loop_subtitle_page', __( 'Company slogan', 'mosalon' ) );
elseif ( is_home() || is_singular() ) :
$title = get_theme_mod( 'loop_title', __( 'From the blog', 'mosalon' ) );
$desc = get_theme_mod( 'loop_subtitle', __( 'Latest posts from our blog', 'mosalon' ) );
elseif ( is_404() ) :
$title = __( 'Nothing Found', 'mosalon' );
$desc = __( 'Apologies, but no entries were found.', 'mosalon' );
else :
$title = esc_attr( get_the_archive_title() );
$desc = esc_attr( get_the_archive_description() );
if ( empty( $desc ) ) {
// If there's no category description.
if ( is_category() ) {
$text = __( 'You are browsing the category', 'mosalon' );
$desc = $text . ' '. esc_html( $title );
}
if ( is_author() )
$desc = __( 'All posts by this author page' , 'mosalon' );
if ( is_tag() )
$desc = __( 'You are browsing posts tagged with' , 'mosalon' ) . ' ' . esc_html( $title ) . '.';
}
endif; ?>
<?php if ( $title ) : ?>
<h1 <?php hybrid_attr( 'loop-title' ); ?>><?php echo esc_html( $title ); ?></h1>
<?php endif; ?>
<?php if ( $desc ) : ?>
<div <?php hybrid_attr( 'loop-description' ); ?>>
<p><?php echo esc_html( $desc ); ?></p>
</div><!-- .loop-description -->
<?php endif; ?>
</div><!-- .loop-meta -->
<?php endif; // End check if is Mosalon's landing page. ?> | gpl-2.0 |
peifu/tests | python/rsa/backup/rsa.py | 1185 | #!/usr/bin/env python
#
# Copyright (C) 2018 Spacetime Studio, Inc. All rights reserved.
#
#
# DMC Violation Register Parser
#
# Author: jiangpeifu@gmail.com
# Version: 0.1
#
from Crypto.PublicKey import RSA
from Crypto.Signature.pkcs1_15 import PKCS115_SigScheme
from Crypto.Hash import SHA256
import binascii
# Generate 1024-bit RSA key pair (private + public key)
keyPair = RSA.generate(bits=1024)
pubKey = keyPair.publickey()
# Sign the message using the PKCS#1 v1.5 signature scheme (RSASP1)
msg = b'Message for RSA signing'
hash = SHA256.new(msg)
signer = PKCS115_SigScheme(keyPair)
signature = signer.sign(hash)
print("Signature:", binascii.hexlify(signature))
# Verify valid PKCS#1 v1.5 signature (RSAVP1)
msg = b'Message for RSA signing'
hash = SHA256.new(msg)
verifier = PKCS115_SigScheme(pubKey)
try:
verifier.verify(hash, signature)
print("Signature is valid.")
except:
print("Signature is invalid.")
# Verify invalid PKCS#1 v1.5 signature (RSAVP1)
msg = b'A tampered message'
hash = SHA256.new(msg)
verifier = PKCS115_SigScheme(pubKey)
try:
verifier.verify(hash, signature)
print("Signature is valid.")
except:
print("Signature is invalid.")
| gpl-2.0 |
InnovaLangues/innovalangues.fr | wp-content/themes/Sterling-Child-Theme/footer.php | 10158 | </section><!-- END content-container -->
<?php
// Retrieve values from Site Options Panel.
global $ttso;
$truethemes_scrolltoplink = $ttso->st_scrolltoplink;
$truethemes_scrolltoptext = stripslashes( $ttso->st_scrolltoptext );
$truethemes_footer_columns = $ttso->st_footer_columns;
$truethemes_footer_callout = $ttso->st_footer_callout;
$truethemes_footer_callout_text = stripslashes( $ttso->st_footer_callout_text );
$truethemes_footer_callout_button = stripslashes( $ttso->st_footer_callout_button );
$truethemes_footer_callout_button_url = $ttso->st_footer_callout_button_url;
$truethemes_footer_callout_button_target = $ttso->st_footer_callout_button_target;
$truethemes_footer_callout_button_color = $ttso->st_footer_callout_button_color;
$truethemes_footer_callout_button_size = $ttso->st_footer_callout_button_size;
$truethemes_copyright = stripslashes( $ttso->st_footer_copyright );
$blog_pinterest = $ttso->st_blog_pinterest;
$truethemes_jslide_effect = $ttso->st_jslide_effect;
$truethemes_jslide_speed = $ttso->st_jslide_speed;
$truethemes_jslide_delay = $ttso->st_jslide_delay;
$truethemes_jslide_randomize = $ttso->st_jslide_randomize;
$truethemes_jslide_pause_hover = $ttso->st_jslide_pause_hover;
$truethemes_jslide_nav_arrows = $ttso->st_jslide_navarrows;
$boxedlayout = $ttso->st_boxedlayout;
?>
<?php if ( 'true' == $truethemes_footer_callout ) { ?>
<div class="footer-callout clearfix">
<div class="center-wrap tt-relative">
<?php if ( 'true' == $truethemes_footer_callout ) { ?>
<div class="footer-callout clearfix">
<div class="center-wrap tt-relative">
<div class="partenaires">LES PARTENAIRES</div>
<div class="center-wrap tt-relative" id="footer-links">
<ul>
<li class="sito1"><a href="http://www.u-grenoble3.fr/" target="_blank"></a></li>
<li class="sito2"><a href="https://portail.umons.ac.be/FR/Pages/default.aspx" target="_blank"></a></li>
<li class="sito3"><a href="http://www.totemis.fr/" target="_blank"></a></li>
<li class="sito4"><a href="http://www.lend.it/italia/" target="_blank"></a></li>
<li class="sito5"><a href="http://www.real-association.eu/fr" target="_blank"></a></li>
</ul>
</div>
</div><!-- end .center-wrap -->
</div><!-- end .footer-callout -->
<?php } //end footer callout ?>
</div><!-- end .center-wrap -->
</div><!-- end .footer-callout -->
<?php } //end footer callout ?>
<footer>
<div class="center-wrap tt-relative">
<div class="footer-content clearfix">
<div class="half_footer">
<?php dynamic_sidebar( 'First Footer Column' ); ?>
</div>
<div class="half_footer_right">
<div class="widget-1 widget-first widget-last widget-odd sidebar-widget social_widget">
<ul class="social_icons">
<li><a href="http://www.scoop.it/t/innovalangues" onclick="window.open(this.href);return false;" class="rss">Scoop.it</a></li>
<li><a href="https://twitter.com/innovalangues" class="twitter" onclick="window.open(this.href);return false;">Twitter</a></li>
</ul>
</div> </div>
<?php /*dynamic_sidebar( 'Second Footer Column' );*/ ?>
</div>
<?php
/*
add_filter( 'pre_get_posts', 'wploop_exclude' );
if ( is_page_template( 'page-template-under-construction.php' ) ) { ?>
<div class="construction-default-one">
<?php dynamic_sidebar( 'First Under Construction Column' ); ?>
</div><!-- end .construction-default-one -->
<div class="construction-default-two">
<?php dynamic_sidebar( 'Second Under Construction Column' ); ?>
</div><!-- end .construction-default-two -->
<div class="construction-default-three">
<?php dynamic_sidebar( 'Third Under Construction Column' ); ?>
</div><!-- end .construction-default-three -->
<?php } else if ('Default-Layout' == $truethemes_footer_columns ) { ?>
<div class="footer-default-one">
<?php dynamic_sidebar( 'First Footer Column' ); ?>
</div><!-- end .footer-default-one -->
<div class="footer-default-two">
<?php dynamic_sidebar( 'Second Footer Column' ); ?>
</div><!-- end .footer-default-two -->
<div class="footer-default-three">
<?php dynamic_sidebar( 'Third Footer Column' ); ?>
</div><!-- end .footer-default-three -->
<?php } else {
$footer_columns = range( 1, $truethemes_footer_columns );
$footer_count = 1;
$sidebar = 7;
foreach ( $footer_columns as $footer => $column ) {
switch ( $truethemes_footer_columns ) {
case 1 :
$class = '';
break;
case 2 :
$class = 'one_half';
break;
case 3 :
$class = 'one_third';
break;
case 4 :
$class = 'one_fourth';
break;
case 5 :
$class = 'one_fifth';
break;
case 6 :
$class = 'one_sixth';
break;
}
?>
<div class="<?php echo $class; ?>">
<?php dynamic_sidebar( $sidebar ); ?>
</div>
<?php $footer_count++; $sidebar++;
}
}
*/
?>
</div><!-- end .footer-content -->
</div><!-- end .center-wrap -->
<?php
if ( ! is_page_template( 'page-template-under-construction.php' ) ) { ?>
<div class="footer-copyright clearfix">
<div class="center-wrap clearfix">
<div class="foot-copy">
<p><?php echo html_entity_decode( $truethemes_copyright); ?></p>
</div><!-- end .foot-copy -->
<?php if ( 'true' == $truethemes_scrolltoplink ) { ?>
<a href="#" id="scroll_to_top" class="link-top"><?php echo esc_html( $truethemes_scrolltoptext ); ?></a>
<?php } ?>
<?php if ( has_nav_menu( 'Footer Menu' ) ) { ?>
<ul class="footer-nav">
<?php wp_nav_menu( array( 'container' => false, 'theme_location' => 'Footer Menu', 'depth' => 0 ) ); ?>
</ul>
<?php } ?>
<div class="clear"></div>
<p id="credits"><a href="http://web16.themarkcomgroup.com/mentions-legales/">Mentions légales</a></p>
<p id="copyright">Projected and designed by <a href="http://www.themarkcomgroup.com" target="_blank">The MarkCom Group</a></p>
</div><!-- end .center-wrap -->
</div><!-- end .footer-copyright -->
<?php }
?>
<div class="shadow top"></div>
<div class="tt-overlay"></div>
</footer>
<?php if ( 'true' == $boxedlayout ) {echo '</div><!-- end .tt-boxed-layout -->';}else{echo '</div><!-- end .tt-wide-layout -->';} ?>
<?php wp_footer(); ?>
<?php if ( is_page_template( 'page-template-home-jquery.php' ) || is_page_template( 'page-template-home-jquery-sidebar.php' ) ) { ?>
<script type="text/javascript">
jQuery(document).ready(function($){
// Homepage slider setup. Issued in the footer to accept user-set variables.
$('#slides').slides({
preload: false,
//preloadImage: 'http://files.truethemes.net/themes/sterling-wp/ajax-loader.gif',
autoHeight: true,
effect: '<?php echo $truethemes_jslide_effect; ?>',
slideSpeed: <?php echo $truethemes_jslide_speed; ?>,
play: <?php echo $truethemes_jslide_delay; ?>,
randomize: <?php echo $truethemes_jslide_randomize; ?>,
hoverPause: <?php echo $truethemes_jslide_pause_hover; ?>,
pause: <?php echo $truethemes_jslide_delay; ?>,
generateNextPrev: <?php echo $truethemes_jslide_nav_arrows; ?>
});
// Allows for custom nav buttons to remain outside of #slides container.
$('.banner-slider .next').click(function(){
$('#slides .next').click();
});
$('.banner-slider .prev').click(function(){
$('#slides .prev').click();
});
});
</script>
<?php } ?>
<?php if ( ( is_home() || is_single() || is_archive() ) && 'true' == $blog_pinterest ) { ?>
<script type="text/javascript">
(function(){
window.PinIt = window.PinIt || { loaded : false };
if ( window.PinIt.loaded ) return;
window.PinIt.loaded = true;
function async_load(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://assets.pinterest.com/js/pinit.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
}
if (window.attachEvent)
window.attachEvent('onload', async_load);
else
window.addEventListener('load', async_load, false);
})();
</script>
<?php } ?>
</body>
</html> | gpl-2.0 |
Wikicrimes/Wikicrimes | src/main/java/org/wikicrimes/service/impl/CredibilidadeServiceImpl.java | 513 | package org.wikicrimes.service.impl;
import org.wikicrimes.dao.CredibilidadeDao;
import org.wikicrimes.service.CredibilidadeService;
public class CredibilidadeServiceImpl extends GenericCrudServiceImpl implements
CredibilidadeService {
private CredibilidadeDao credibilidadeDao;
/** Gets and Sets **/
public CredibilidadeDao getCredibilidadeDao() {
return credibilidadeDao;
}
public void setCredibilidadeDao(CredibilidadeDao credibilidadeDao) {
this.credibilidadeDao = credibilidadeDao;
}
}
| gpl-2.0 |
lamsfoundation/lams | lams_tool_leader/src/java/org/lamsfoundation/lams/tool/leaderselection/web/forms/MonitoringForm.java | 2183 | /****************************************************************
* Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org)
* =============================================================
* License Information: http://lamsfoundation.org/licensing/lams/2.0/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2.0
* 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
*
* http://www.gnu.org/licenses/gpl.txt
* ****************************************************************
*/
package org.lamsfoundation.lams.tool.leaderselection.web.forms;
/**
*
*/
public class MonitoringForm {
private static final long serialVersionUID = 9096908688391850595L;
boolean teacherVisible;
Long toolSessionID;
// editing message page.
Long messageUID;
String messageBody;
boolean messageHidden;
public String getMessageBody() {
return messageBody;
}
public void setMessageBody(String messageBody) {
this.messageBody = messageBody;
}
public Long getMessageUID() {
return messageUID;
}
public void setMessageUID(Long messageUID) {
this.messageUID = messageUID;
}
public Long getToolSessionID() {
return toolSessionID;
}
public void setToolSessionID(Long toolSessionID) {
this.toolSessionID = toolSessionID;
}
public boolean isTeacherVisible() {
return teacherVisible;
}
public void setTeacherVisible(boolean visible) {
this.teacherVisible = visible;
}
public boolean isMessageHidden() {
return messageHidden;
}
public void setMessageHidden(boolean messageHidden) {
this.messageHidden = messageHidden;
}
}
| gpl-2.0 |
seavan/smoltoday | trunk/src/meridian.smolensk/controller_impl/admin_action_categories.cs | 613 | /* Automatically generated codefile, Meridian
* Generated by magic, please do not interfere
* Please sleep well and do not smoke. Love, Sam */
using System;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
using meridian.smolensk;
using meridian.smolensk.system;
using meridian.smolensk.proto;
using admin.web.common;
namespace meridian.smolensk.controller
{
public partial class admin_action_categoriesController : meridian_action_categories
{
public admin_action_categoriesController()
{
}
}
}
| gpl-2.0 |
vipero07/useful-snippits | humanReadable.js | 625 | //big type is for big numbers i.e. 1234 = 1.2k, 1234567890 = 1.2B
//bit is for bits/bytes to kb, mb, gb, etc, defaults to bit
function humanReadable(number, type){
var prefix = ' kMGTPEZYXWVU', kilo = 1024;
if(type && type=='big'){
prefix = prefix.replace('G','B');
kilo = 1000;
}
var retValue = 0;
if (typeof number == "number") {
if (number < kilo) {
retValue = number.toString();
} else {
var e = (Math.log(number) / Math.log(kilo)) | 0;
retValue = Number((number / Math.pow(kilo, e)).toString().slice(0, 3)) + prefix.charAt(e);
}
}
return retValue;
}
| gpl-2.0 |
3imsinn/akeplog | wp-content/themes/future/search.php | 1241 | <?php get_header(); ?>
<?php get_template_part( 'loop-meta' ); ?>
<div class="<?php future_cs_layout( array( 'cs_layout_bone' => 'content_sidebar_wrapper_class' ) ); ?>">
<div class="container">
<div class="row">
<div class="<?php future_cs_layout( array( 'cs_layout_bone' => 'content_column_class' ) ); ?>">
<main class="content" role="main" itemprop="mainContentOfPage" itemscope="itemscope" itemtype="http://schema.org/Blog">
<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
if( get_post_type() == 'page' ) {
get_template_part( 'content-search', 'page' );
} else {
get_template_part( 'content', get_post_format() );
}
?>
<?php endwhile; ?>
<?php else : ?>
<?php get_template_part( 'loop-error' ); ?>
<?php endif; ?>
<?php future_loop_nav(); ?>
</main>
</div>
<?php get_sidebar(); ?>
</div>
</div>
</div>
<?php get_footer(); ?> | gpl-2.0 |
cria/microSICol | po/find_unused_html_labels.py | 3064 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os
import re
from update_potfile_in import get_file_list
search_dirs = ["html"]
exclude_dirs = [".svn"]
extensions = ["html"]
python_file = "../py/modules/labels.py"
python_regexp = re.compile(r"""^\s*['"](.*?)['"]\s*:""", re.MULTILINE | re.UNICODE)
html_regexp = re.compile(r"""\%\(([a-zA-Z0-9_]*?)\)s""", re.MULTILINE | re.UNICODE)
def main(*argv):
if "all" in argv:
mode = "all"
else:
mode = "normal"
file_list = get_file_list(search_dirs, exclude_dirs, extensions, sep= os.path.sep, append_nl = False)
python_labels_text = open(python_file, "rt").read().decode("utf-8")
python_labels = {}
out = ''
for match in python_regexp.finditer(python_labels_text):
label = match.groups()[0]
line_number = python_labels_text.count("\n", 0, match.start()) + 1
if not python_labels.has_key (label):
python_labels[label] = []
python_labels[label].append("Python Labels: %d - %s" % (line_number, label))
html_labels = {}
for html_file in file_list:
file_content = open(os.path.join("..", html_file), "rt").read().decode("utf-8")
for match in html_regexp.finditer(file_content):
label = match.groups()[0]
line_number = file_content.count("\n", 0, match.start()) + 1
if not html_labels.has_key (label):
html_labels[label] = []
html_labels[label].append("\t%s:%d" % (html_file, line_number))
if not "reverse" in argv:
for label in sorted(python_labels.keys()):
if mode == "all" or (mode=="normal" and not html_labels.has_key(label)) or len(python_labels[label]) > 1:
if len(python_labels[label]) > 1:
out += "DUPLICATE LABEL on python side:"
for l in python_labels[label]:
out += l
if html_labels.has_key(label):
for l in html_labels[label]:
out += l
out += '\n'
else:
for label in sorted(html_labels.keys()):
if mode == "all" or not python_labels.has_key(label):
out += "%s:" % label
if python_labels.has_key(label):
for l in python_labels[label]:
out += l
for l in html_labels[label]:
out += l
out += '\n'
arq = file("output.txt", 'wb')
arq.write(out)
arq.close()
if __name__ == "__main__":
if "help" in sys.argv:
print """\
find_unused_html_labels [all] [reverse]
Use this script to find out labels in py/modules/labels.py which are
not used in the html templates under html/*html
all: list all labels, even if they are used in the html templates
reverse: list exitng html labels wich do not have a counterpart
in the labels.py file
"""
sys.exit(0)
main(*sys.argv)
| gpl-2.0 |
ijgomez/workspace-test | template-dashboard/src/app/views/security/users/users-list/users-list.component.ts | 2857 | import { Component, OnInit } from '@angular/core';
import { DataTablePagination } from '../../../components/datatable/datatable-pagination.component';
import { Observable } from 'rxjs/Rx';
import { ModalOptions } from '../../../components/modal/modal-options';
import { UsersService } from '../../../../services/security/users.service';
import { Modal } from '../../../components/modal/modal';
import { UserCriteria } from '../../../../domain/security/user-criteria';
import { UserComponent } from '../user/user.component';
import { ModalRef } from '../../../components/modal/modal-ref';
import { User } from '../../../../domain/security/user';
@Component({
selector: 'app-users-list',
templateUrl: './users-list.component.html',
styleUrls: ['./users-list.component.css']
})
export class UsersListComponent extends DataTablePagination implements OnInit {
private options: ModalOptions = { size: 'lg'};
constructor(private usersService: UsersService, private modalService: Modal) {
super('username', 'ASC');
}
ngOnInit() {
this.reload();
}
handlerDoFilter(): Observable<any> {
return this.usersService.findByCriteria(this.buildCriteria());
}
handlerDoCount(): Observable<number> {
return this.usersService.countByCriteria(this.buildCriteria());
}
handlerBuildCriteria() {
let criteria: UserCriteria;
criteria = new UserCriteria();
// TODO Pendiente de Implementar
return criteria;
}
handlerExport(): Observable<any> {
return this.usersService.export(this.buildCriteria());
}
add(): void {
const modal: ModalRef = this.modalService.open(UserComponent, this.options);
modal.result.then(
(result) => {
this.reload();
},
(reason) => { }
);
}
update(user: User): void {
let id: number;
if (user == null) {
id = this.selectedItem.id;
} else {
this.selectedRow(user);
id = user.id;
}
this.usersService.read(id).subscribe(
response => {
this.selectedItem = null;
const modal: ModalRef = this.modalService.open(UserComponent, this.options);
(<UserComponent>modal.componentInstance).user = response;
modal.result.then(
(result) => {
this.reload();
},
(reason) => { }
);
},
this.handlerError
);
// TODO Pendiente de Implementar
}
delete(user: User): void {
const modal: ModalRef = this.modalService.confirm('User Delete', 'Delete the user. Are you sure?');
modal.result.then(
(result) => {
this.usersService.delete(this.selectedItem).subscribe(
response => {
this.reload();
},
this.handlerError
);
this.selectedItem = null;
},
(reason) => {
console.log('execute: reason');
}
);
}
}
| gpl-2.0 |
gbonacini/tssh | include/anyexcept.hpp | 1015 | // -----------------------------------------------------------------
// Tssh - A ssh test client.
// Copyright (C) 2016-2021 Gabriele Bonacini
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
// -----------------------------------------------------------------
#ifndef ANYEXCEPT_H
#define ANYEXCEPT_H
#define anyexcept noexcept(false)
#endif
| gpl-2.0 |
stefanoborini/kmonodim | src/eigenlistview.cpp | 7406 | #include <qpushbutton.h>
#include <kcolordialog.h>
#include <qlabel.h>
#include "eigenlistview.h"
#include "mylistviewitem.h"
#include "eigenvalue.h"
#include "project.h"
#include "palette.h"
#include "color.h"
#include "system.h"
#include "potential.h"
#include "eigenvalue.h"
class EigenData {
public:
double eigenvalue;
double extrapolatedEigenvalue;
double meanPosition;
double meanKinetic;
double meanPotential;
bool wrongLimits;
bool isEigenvalue;
};
/*
* Constructs a EigenListView which is a child of 'parent', with the
* name 'name' and widget flags set to 'f'
*/
EigenListView::EigenListView( Project *project, QWidget *parent, const char* name, WFlags fl )
: EigenListViewBase( parent, name, fl )
{
m_project = project;
m_listView->setSelectionMode(QListView::Single);
m_listView->setRootIsDecorated(true);
m_listView->setTreeStepSize(10);
m_allActive=true;
m_setActiveButton->setText("Disable all");
m_eigenvalue_label->setText("-");
m_extrapolatedEigenvalue_label->setText("-");
enableRichardsonLabel(false);
enableWrongLimitsLabel(false);
m_meanPotential_label->setText("-");
m_meanKinetic_label->setText("-");
m_meanPosition_label->setText("-");
m_dataDict.setAutoDelete(true);
QObject::connect(m_listView,SIGNAL(clicked(QListViewItem *, const QPoint &, int)), this,SLOT(slotItemClicked(QListViewItem *, const QPoint &, int)));
QObject::connect(m_listView,SIGNAL(selectionChanged(QListViewItem *)), this,SLOT(slotSelectionChanged(QListViewItem *)));
QObject::connect(m_setActiveButton,SIGNAL(clicked()), this,SLOT(slotActivateAll()));
QObject::connect(m_setUniqueColorButton,SIGNAL(clicked()), this,SLOT(slotSetUniqueColor()));
}
void EigenListView::slotFetchData() {
register unsigned int i;
double min;
System *system;
Palette *palette;
Eigenvalue *e;
QListViewItem *select = NULL;
QString str;
int digits;
m_listView->clear();
m_dataDict.clear();
system = m_project->system();
palette = m_project->palette();
enableRichardsonLabel(system->hasExtrapolation());
Color col = palette->color(0);
str.sprintf("Potential");
MyListViewItem *rootitem = new MyListViewItem(m_listView, 0, str, col, col.active(), false);
EigenData *data = new EigenData;
data->isEigenvalue = false;
m_dataDict.insert(0,data);
for ( i = 0; i < system->eigenNumber(); i++ ) {
e = system->eigenvalue( i );
col = palette->color( i + 1 );
str.sprintf("%d",(int)e->eigenvalue());
digits = str.length();
digits += 6;
str.sprintf("%.*g",digits,e->eigenvalue());
MyListViewItem *item = new MyListViewItem(rootitem, i + 1, str, col, col.active(),e->hasWrongIntegrationLimits());
if (!i) select = item;
data = new EigenData;
data->eigenvalue = e->eigenvalue();
data->extrapolatedEigenvalue = e->extrapolatedEigenvalue();
data->meanPotential = e->meanPotential();
data->meanKinetic = e->meanKinetic();
data->meanPosition = e->meanPosition();
data->wrongLimits = e->hasWrongIntegrationLimits();
data->isEigenvalue = true;
m_dataDict.insert(i+1, data);
}
m_listView->setOpen(rootitem,true);
m_listView->setSorting(0,false);
if (select) m_listView->setSelected(select,true);
}
void EigenListView::slotItemClicked(QListViewItem *item, const QPoint &point, int c) {
if (!item) return;
int index;
int result;
MyListViewItem *it = (MyListViewItem *)item;
Palette *palette = m_project->palette();
Color col;
KColorDialog coldlg(this,"colordialog",TRUE);
index = it->getDataIndex();
col = palette->color(index);
switch (c) {
case 1: // clicked on the color
coldlg.setColor(col);
if (coldlg.exec() == KColorDialog::Accepted) {
col = coldlg.color();
palette->setColor( index, col );
}
palette->reportChanges();
break;
case 2: // clicked on the active spot
col.setActive(!col.active());
palette->setColor( index, col );
palette->reportChanges();
break;
}
}
void EigenListView::slotSelectionChanged(QListViewItem *item) {
if (!item) return;
QString str;
MyListViewItem *it = (MyListViewItem *)item;
int index = it->getDataIndex();
int digits;
EigenData *data;
data = m_dataDict[index];
if (data && data->isEigenvalue) {
str.sprintf("%d",(int)data->eigenvalue);
digits = str.length();
digits += 6;
str.sprintf("%.*g",digits,data->eigenvalue);
m_eigenvalue_label->setText(str);
str.sprintf("%d",(int)data->extrapolatedEigenvalue);
digits = str.length();
digits += 6;
str.sprintf("%.*g",digits,data->extrapolatedEigenvalue);
m_extrapolatedEigenvalue_label->setText(str);
str.sprintf("%d",(int)data->meanPotential);
digits = str.length();
digits += 6;
str.sprintf("%.*g",digits,data->meanPotential);
m_meanPotential_label->setText(str);
str.sprintf("%d",(int)data->meanKinetic);
digits = str.length();
digits += 6;
str.sprintf("%.*g",digits,data->meanKinetic);
m_meanKinetic_label->setText(str);
str.sprintf("%d",(int)data->meanPosition);
digits = str.length();
digits += 6;
str.sprintf("%.*g",digits,data->meanPosition);
m_meanPosition_label->setText(str);
enableWrongLimitsLabel(data->wrongLimits);
} else {
m_eigenvalue_label->setText("-");
m_extrapolatedEigenvalue_label->setText("-");
m_meanPotential_label->setText("-");
m_meanKinetic_label->setText("-");
m_meanPosition_label->setText("-");
}
}
void EigenListView::slotRefreshPalette() {
MyListViewItem *item;
int index;
QListViewItemIterator it(m_listView);
Palette *palette = m_project->palette();
for (; item = (MyListViewItem *)it.current(); ++it) {
index = item->getDataIndex();
if (palette->changed(index)) {
Color col = palette->color( index );
item->setActive(col.active());
item->setColor(col);
}
}
}
void EigenListView::slotActivateAll() {
QListViewItemIterator it(m_listView);
MyListViewItem *item;
Palette *palette = m_project->palette();
Color col;
unsigned int index;
m_allActive=!m_allActive;
for (; it.current() ; ++it) {
item = (MyListViewItem *)it.current();
index = item->getDataIndex();
col = palette->color(index);
col.setActive(m_allActive);
palette->setColor( index, col );
}
palette->reportChanges();
m_allActive ? m_setActiveButton->setText("Disable all") : m_setActiveButton->setText("Enable all");
}
void EigenListView::slotSetUniqueColor() {
QListViewItemIterator it(m_listView);
MyListViewItem *item;
Color col;
QColor newcol;
unsigned int index;
Palette *palette = m_project->palette();
int result;
if ( KColorDialog::getColor( newcol ) == KColorDialog::Accepted ) {
for (; it.current() ; ++it) {
item = (MyListViewItem *)it.current();
index = item->getDataIndex();
col = palette->color(index);
col.setColor(newcol);
palette->setColor(index,col);
}
}
palette->reportChanges();
}
void EigenListView::enableRichardsonLabel(bool enable) {
qDebug("enableRichardsonLabel called");
if (enable) {
qDebug("enable label");
m_extrapolatedEigenvalue_label->show();
m_extrapolatedEigenvalue_name_label->show();
resize(sizeHint());
} else {
qDebug("disable label");
m_extrapolatedEigenvalue_label->hide();
m_extrapolatedEigenvalue_name_label->hide();
resize(sizeHint());
}
}
void EigenListView::enableWrongLimitsLabel(bool enable) {
if (enable) m_wrongLimits_label->show();
else m_wrongLimits_label->hide();
}
#include "eigenlistview.moc"
#include "eigenlistviewbase.moc"
| gpl-2.0 |
ethanwilkins/simplr | db/migrate/20200111202533_add_phone_number_to_users.rb | 128 | class AddPhoneNumberToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :phone_number, :string
end
end
| gpl-2.0 |
jillbot/tsp | wp-content/themes/minimatica/content-audio.php | 1143 | <?php
/**
* Displays the content of posts with audio format
*
* @package WordPress
* @subpackage Minimatica
* @since Minimatica 1.0
*/
?>
<div id="content">
<section class="entry-content">
<?php the_post_thumbnail( 'homepage-thumb' ); ?>
<?php minimatica_post_audio(); ?>
<?php the_content(); ?>
<div class="clear"></div>
<?php wp_link_pages( array( 'before' => '<p class="pagination">' . __( 'Pages' ) . ': ' ) ); ?>
</section><!-- .entry-content -->
<div class="entry-header">
<aside class="entry-meta">
<ul>
<li><?php _e( 'Posted by', 'minimatica' ); ?> <?php the_author_posts_link(); ?></li>
<li><?php _e( 'on', 'minimatica' ); ?> <time datetime="<?php the_time( 'Y-m-d' ); ?>"><?php the_time( get_option( 'date_format' ) ); ?></time></li>
<li><?php _e( 'Filed under', 'minimatica' ); ?> <?php the_category( ', ' ); ?></li>
</ul>
<?php the_tags( '<div class="entry-tags">', ' ', '</div>' ); ?>
</aside><!-- .entry-meta -->
<div class="clear"></div>
</div><!-- .entry-header -->
<?php comments_template(); ?>
<div class="clear"></div>
</div><!-- #content --> | gpl-2.0 |
rex-xxx/mt6572_x201 | packages/apps/Mms/src/com/android/mms/ui/HeightChangedLinearLayout.java | 5086 | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*/
/* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import com.mediatek.encapsulation.MmsLog;
/** M:
* HeightChangedLinearLayout
*/
public class HeightChangedLinearLayout extends LinearLayout {
private final static String TAG = "Mms/ChangedLayout";
private LayoutSizeChangedListener mLayoutSizeChangedListener;
public HeightChangedLinearLayout(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public HeightChangedLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
MmsLog.d(TAG, "onLayout(): changed = " + changed + ", left = " + l
+ ",top = " + t + ", right = " + r + ", bottom = " + b);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
MmsLog.d(TAG, "onMeasure(): widthMeasureSpec = " + widthMeasureSpec
+ ", heightMeasureSpec = " + heightMeasureSpec);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
MmsLog.d(TAG, "onSizeChanged(): oldw = " + oldw + ", oldh = " + oldh
+ ",w = " + w + ", h = " + h);
final int fw = w;
final int fh = h;
final int foldw = oldw;
final int foldh = oldh;
new Thread(new Runnable() {
@Override
public void run() {
if (mLayoutSizeChangedListener != null) {
mLayoutSizeChangedListener.onLayoutSizeChanged(fw, fh, foldw, foldh);
}
}
}).start();
}
public interface LayoutSizeChangedListener {
public void onLayoutSizeChanged(int w, int h, int oldw, int oldh);
}
public void setLayoutSizeChangedListener(LayoutSizeChangedListener l) {
mLayoutSizeChangedListener = l;
}
}
| gpl-2.0 |
xiaolu6t6t/NFinal | WebMvc/NFinal/Compile/PageSqlAnalyse.cs | 5649 | using System;
using System.Collections.Generic;
using System.Web;
using System.Text.RegularExpressions;
namespace NFinal.Compile
{
public class PageSqlAnalyse
{
public string pageSql;
public string countSql;
public string sql;
public NFinal.DB.DBType dbType;
public PageSqlAnalyse(string sql, NFinal.DB.DBType dbType)
{
this.sql = sql;
this.dbType = dbType;
}
public void Parse()
{
string temp=string.Empty;
string selectFromParttern = @"select\s+([\s\S]+)\s+from\s+";
Regex selectFromReg = new Regex(selectFromParttern, RegexOptions.IgnoreCase);
Match mat = selectFromReg.Match(sql);
if (mat.Success)
{
countSql = sql.Remove(mat.Groups[1].Index, mat.Groups[1].Length);
countSql = countSql.Insert(mat.Groups[1].Index,"count(*)");
}
bool hasOrderBy = true;
string orderBy = @" order by ";
Regex orderByReg = new Regex(orderBy, RegexOptions.IgnoreCase);
Match orderByMat = orderByReg.Match(sql);
if (orderByMat.Success)
{
hasOrderBy = true;
}
//如果数据库是sqlserver
if (dbType == DB.DBType.SqlServer)
{
string selectParttern = @"\s*(select)\s+";
Regex selectReg = new Regex(selectParttern, RegexOptions.IgnoreCase);
Match selectMat = selectReg.Match(sql);
string whereParttern = @"\s+(where|from)\s+";
Regex whereReg = new Regex(whereParttern,RegexOptions.IgnoreCase|RegexOptions.RightToLeft);
Match whereMat = whereReg.Match(sql);
//如果是select语句必定有select和from语句
if (selectMat.Success && whereMat.Success)
{
//如果是select from where 的形式
if (whereMat.Groups[1].Value.ToLower() == "where")
{
//如果没有order by排序
if (!hasOrderBy)
{
pageSql = sql.Insert(selectMat.Index + selectMat.Length,
" top {0} ");
temp = "select top {1} id " + sql.Substring(whereMat.Groups[1].Index);
pageSql += string.Format(" and id not in({0})", temp);
}
//如果有order by排序,则要把orderby语句放在最后面
else
{
string deleteOrderBySql=sql.Remove(orderByMat.Index);
pageSql =sql.Insert(selectMat.Index +selectMat.Length," top {0} ");
temp ="select top {1} id "+sql.Substring(whereMat.Groups[1].Index);
pageSql+= string.Format(" and id not in ({0}) {1}",temp,orderByMat.Groups[1].Value);
}
}
//如果是select from 的形式
else
{
//如果没有order by排序
if(!hasOrderBy)
{
pageSql = sql.Insert(selectMat.Index + selectMat.Length,
" top {0} ");
temp = "select top {1} id " + sql.Substring(whereMat.Groups[1].Index);
pageSql += string.Format(" where id not in({0})", temp);
}
//如果有order by排序,则要把orderby语句放在最后面
else
{
string deleteOrderBySql=sql.Remove(orderByMat.Index);
pageSql =sql.Insert(selectMat.Index +selectMat.Length," top {0} ");
temp ="select top {1} id "+ sql.Substring(whereMat.Groups[1].Index);
pageSql +=string.Format(" where id not in ({0}) {1}",temp,orderByMat.Groups[1].Value);
}
}
}
}
//如果数据库是mysql
else if (dbType == DB.DBType.MySql)
{
pageSql =sql+ " limit {0},{1}";
}
//如果数据库是sqlite
else if (dbType == DB.DBType.Sqlite)
{
pageSql =sql+ " Limit {0} Offset {1}";
}
}
public string GetSql(string pageSql,string countSql,int pageIndex,int pageSize,int totalSize,NFinal.DB.DBType dbType)
{
int pageCount = (totalSize % pageSize==0)?totalSize/pageSize:totalSize/pageSize+1;
if (pageIndex > pageCount)
{
pageIndex = pageCount;
}
if (pageIndex < 1)
{
pageIndex = 1;
}
if (dbType == NFinal.DB.DBType.SqlServer)
{
pageSql = string.Format(pageSql, pageIndex * pageSize, (pageIndex - 1) * pageSize);
}
else if (dbType == NFinal.DB.DBType.MySql)
{
pageSql = string.Format(pageSql, (pageIndex - 1) * pageSize, pageSize);
}
else if(dbType ==NFinal.DB.DBType.Sqlite)
{
pageSql = string.Format(pageSql, pageSize, (pageIndex - 1) * pageSize);
}
return pageSql;
}
}
} | gpl-2.0 |
gear20056/theNewBostonCPP_Tutorials_myPractices | _ch3_printing text/testOne/main.cpp | 415 | #include <iostream>
using namespace std;
int main()
{
/*
cout << "boy i love bacon ";
cout << "and ham";
*/
/*
cout << "boy i love bacon " << endl;
cout << "and ham";
*/
/*
cout << "boy i love bacon \n";
cout << "and ham";
*/
/*
cout << "boy i love bacon \n\n";
cout << "and ham";
*/
cout << "boy \n i \n love \n bacon \n";
return 0;
}
| gpl-2.0 |
Frodox/buildbot | master/buildbot/db/builders.py | 5881 | # This file is part of Buildbot. Buildbot 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., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import absolute_import
from __future__ import print_function
import sqlalchemy as sa
from twisted.internet import defer
from buildbot.db import base
class BuildersConnectorComponent(base.DBConnectorComponent):
def findBuilderId(self, name, autoCreate=True):
tbl = self.db.model.builders
name_hash = self.hashColumns(name)
return self.findSomethingId(
tbl=tbl,
whereclause=(tbl.c.name_hash == name_hash),
insert_values=dict(
name=name,
name_hash=name_hash,
), autoCreate=autoCreate)
@defer.inlineCallbacks
def updateBuilderInfo(self, builderid, description, tags):
# convert to tag IDs first, as necessary
def toTagid(tag):
if isinstance(tag, type(1)):
return defer.succeed(tag)
ssConnector = self.master.db.tags
return ssConnector.findTagId(tag)
tagsids = [r[1] for r in (yield defer.DeferredList(
[toTagid(tag) for tag in tags],
fireOnOneErrback=True,
consumeErrors=True))]
def thd(conn):
builders_tbl = self.db.model.builders
builders_tags_tbl = self.db.model.builders_tags
transaction = conn.begin()
q = builders_tbl.update(
whereclause=(builders_tbl.c.id == builderid))
conn.execute(q, description=description).close()
# remove previous builders_tags
conn.execute(builders_tags_tbl.delete(
whereclause=((builders_tags_tbl.c.builderid == builderid)))).close()
# add tag ids
if tagsids:
conn.execute(builders_tags_tbl.insert(),
[dict(builderid=builderid, tagid=tagid)
for tagid in tagsids]).close()
transaction.commit()
defer.returnValue((yield self.db.pool.do(thd)))
def getBuilder(self, builderid):
d = self.getBuilders(_builderid=builderid)
@d.addCallback
def first(bldrs):
if bldrs:
return bldrs[0]
return None
return d
def addBuilderMaster(self, builderid=None, masterid=None):
def thd(conn, no_recurse=False):
try:
tbl = self.db.model.builder_masters
q = tbl.insert()
conn.execute(q, builderid=builderid, masterid=masterid)
except (sa.exc.IntegrityError, sa.exc.ProgrammingError):
pass
return self.db.pool.do(thd)
def removeBuilderMaster(self, builderid=None, masterid=None):
def thd(conn, no_recurse=False):
tbl = self.db.model.builder_masters
conn.execute(tbl.delete(
whereclause=((tbl.c.builderid == builderid) &
(tbl.c.masterid == masterid))))
return self.db.pool.do(thd)
def getBuilders(self, masterid=None, _builderid=None):
def thd(conn):
bldr_tbl = self.db.model.builders
bm_tbl = self.db.model.builder_masters
j = bldr_tbl.outerjoin(bm_tbl)
# if we want to filter by masterid, we must join to builder_masters
# again, so we can still get the full set of masters for each
# builder
if masterid is not None:
limiting_bm_tbl = bm_tbl.alias('limiting_bm')
j = j.join(limiting_bm_tbl,
onclause=(bldr_tbl.c.id == limiting_bm_tbl.c.builderid))
q = sa.select(
[bldr_tbl.c.id, bldr_tbl.c.name,
bldr_tbl.c.description, bm_tbl.c.masterid],
from_obj=[j],
order_by=[bldr_tbl.c.id, bm_tbl.c.masterid])
if masterid is not None:
# filter the masterid from the limiting table
q = q.where(limiting_bm_tbl.c.masterid == masterid)
if _builderid is not None:
q = q.where(bldr_tbl.c.id == _builderid)
# now group those by builderid, aggregating by masterid
rv = []
last = None
for row in conn.execute(q).fetchall():
# pylint: disable=unsubscriptable-object
if not last or row['id'] != last['id']:
last = self._thd_row2dict(conn, row)
rv.append(last)
if row['masterid']:
last['masterids'].append(row['masterid'])
return rv
return self.db.pool.do(thd)
def _thd_row2dict(self, conn, row):
# get tags
builders_tags = self.db.model.builders_tags
tags = self.db.model.tags
from_clause = tags
from_clause = from_clause.join(builders_tags)
q = sa.select([tags.c.name],
(builders_tags.c.builderid == row.id)).select_from(from_clause)
tags = [r.name for r in
conn.execute(q).fetchall()]
return dict(id=row.id, name=row.name, masterids=[],
description=row.description,
tags=tags)
| gpl-2.0 |
dailycavalier/brighterchildren | wp-content/themes/Believe_Theme/404.php | 1100 | <?php
/**
* The template for displaying 404 pages (Not Found).
*
* @package WordPress
* @subpackage Believe
*/
get_header();
$title_404 = get_option(SHORTNAME . '_404_title', "This is somewhat embarrassing, isn't it?");
$title_msg = get_option(SHORTNAME . '_404_message', "It seems we can’t find what you’re looking for. Perhaps searching, or one of the links below, can help.");
?>
<div class="white-bg">
<div>
<h1 class="page-title">
<?php
if ( !is_front_page() && !is_home() ) {
echo ch_breadcrumbs();
} ?>
<?php echo $title_404; ?></h1>
<p><?php echo $title_msg; ?></p>
<p> </p>
<div class="widget">
<h4><?php _e('Most Used Categories', 'ch'); ?></h4>
<ul>
<?php wp_list_categories(array('orderby' => 'count', 'order' => 'DESC', 'show_count' => 1, 'title_li' => '', 'number' => 10)); ?>
</ul>
</div>
<div class="msg_404_img">
<img src="<?php echo get_template_directory_uri() . '/images/404_msg.png'; ?>" alt="Page not Found" />
</div>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
<?php get_footer(); | gpl-2.0 |
OpenDBDiff/OpenDBDiff | OpenDBDiff.SqlServer.Schema/Model/Dependencies.cs | 5717 | using OpenDBDiff.Abstractions.Schema;
using OpenDBDiff.Abstractions.Schema.Model;
using System;
using System.Collections.Generic;
using System.Linq;
namespace OpenDBDiff.SqlServer.Schema.Model
{
internal class Dependencies : List<Dependency>
{
public Database Database { get; private set; }
public void Add(Database database, int tableId, int columnId, int ownerTableId, int typeId, ISchemaBase constraint)
{
Dependency dependency = new Dependency();
dependency.SubObjectId = columnId;
dependency.ObjectId = tableId;
dependency.OwnerTableId = ownerTableId;
dependency.FullName = constraint.FullName;
dependency.Type = constraint.ObjectType;
dependency.DataTypeId = typeId;
this.Database = database;
base.Add(dependency);
}
public void Add(Database database, int objectId, ISchemaBase objectSchema)
{
Dependency dependency = new Dependency();
dependency.ObjectId = objectId;
dependency.FullName = objectSchema.FullName;
dependency.Type = objectSchema.ObjectType;
this.Database = database;
base.Add(dependency);
}
/// <summary>
/// Devuelve todos las constraints dependientes de una tabla.
/// </summary>
public List<ISchemaBase> FindNotOwner(int tableId, ObjectType type)
{
try
{
List<ISchemaBase> cons = new List<ISchemaBase>();
this.ForEach(dependency =>
{
if (dependency.Type == type)
{
ISchemaBase item = (ISchemaBase)Database.Find(dependency.FullName);
if (dependency.Type == ObjectType.Constraint)
{
if ((dependency.ObjectId == tableId) && (((Constraint)item).Type == Constraint.ConstraintType.ForeignKey))
cons.Add(item);
}
else
if (dependency.ObjectId == tableId)
cons.Add(item);
}
});
return cons;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Devuelve todos las constraints dependientes de una tabla.
/// </summary>
/*public void Set(int tableId, Constraint constraint)
{
this.ForEach(item =>
{
if (item.Type == ObjectType.Constraint)
if ((item.ObjectId == tableId) && (item.ObjectSchema.Name.Equals(constraint.Name)))
item.ObjectSchema = constraint;
});
}*/
/// <summary>
/// Devuelve todos las constraints dependientes de una tabla.
/// </summary>
public List<ISchemaBase> Find(int tableId)
{
return Find(tableId, 0, 0);
}
public int DependenciesCount(int objectId, ObjectType type)
{
Dictionary<int, bool> depencyTracker = new Dictionary<int, bool>();
return DependenciesCount(objectId, type, depencyTracker);
}
private int DependenciesCount(int tableId, ObjectType type, Dictionary<int, bool> depencyTracker)
{
int count = 0;
bool putItem = false;
int relationalTableId;
List<ISchemaBase> constraints = this.FindNotOwner(tableId, type);
for (int index = 0; index < constraints.Count; index++)
{
ISchemaBase cons = constraints[index];
if (cons.ObjectType == type)
{
if (type == ObjectType.Constraint)
{
relationalTableId = ((Constraint)cons).RelationalTableId;
putItem = (relationalTableId == tableId);
}
}
if (putItem)
{
if (!depencyTracker.ContainsKey(tableId))
{
depencyTracker.Add(tableId, true);
count += 1 + DependenciesCount(cons.Parent.Id, type, depencyTracker);
}
}
}
return count;
}
/// <summary>
/// Devuelve todos las constraints dependientes de una tabla y una columna.
/// </summary>
public List<ISchemaBase> Find(int tableId, int columnId, int dataTypeId)
{
List<string> cons = new List<string>();
List<ISchemaBase> real = new List<ISchemaBase>();
cons = (from depends in this
where (depends.Type == ObjectType.Constraint || depends.Type == ObjectType.Index) &&
((depends.DataTypeId == dataTypeId || dataTypeId == 0) && (depends.SubObjectId == columnId || columnId == 0) && (depends.ObjectId == tableId))
select depends.FullName)
.Concat(from depends in this
where (depends.Type == ObjectType.View || depends.Type == ObjectType.Function) &&
(depends.ObjectId == tableId)
select depends.FullName).ToList();
cons.ForEach(item =>
{
ISchemaBase schema = Database.Find(item);
if (schema != null) real.Add(schema);
}
);
return real;
}
}
}
| gpl-2.0 |
acappellamaniac/eva_website | sites/all/modules/civicrm/CRM/Core/Payment/AuthorizeNetIPN.php | 13113 | <?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.6 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2015
* $Id$
*
*/
class CRM_Core_Payment_AuthorizeNetIPN extends CRM_Core_Payment_BaseIPN {
/**
* Constructor function.
*
* @param array $inputData
* contents of HTTP REQUEST.
*
* @throws CRM_Core_Exception
*/
public function __construct($inputData) {
$this->setInputParameters($inputData);
parent::__construct();
}
/**
* @param string $component
*
* @return bool|void
*/
public function main($component = 'contribute') {
//we only get invoice num as a key player from payment gateway response.
//for ARB we get x_subscription_id and x_subscription_paynum
$x_subscription_id = $this->retrieve('x_subscription_id', 'String');
if ($x_subscription_id) {
//Approved
$ids = $objects = array();
$input['component'] = $component;
// load post vars in $input
$this->getInput($input, $ids);
// load post ids in $ids
$this->getIDs($ids, $input);
$paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType',
'AuthNet', 'id', 'name'
);
if (!$this->validateData($input, $ids, $objects, TRUE, $paymentProcessorID)) {
return FALSE;
}
if ($component == 'contribute' && $ids['contributionRecur']) {
// check if first contribution is completed, else complete first contribution
$first = TRUE;
if ($objects['contribution']->contribution_status_id == 1) {
$first = FALSE;
}
return $this->recur($input, $ids, $objects, $first);
}
}
return TRUE;
}
/**
* @param array $input
* @param array $ids
* @param array $objects
* @param $first
*
* @return bool
*/
public function recur(&$input, &$ids, &$objects, $first) {
$this->_isRecurring = TRUE;
$recur = &$objects['contributionRecur'];
// do a subscription check
if ($recur->processor_id != $input['subscription_id']) {
CRM_Core_Error::debug_log_message("Unrecognized subscription.");
echo "Failure: Unrecognized subscription<p>";
return FALSE;
}
// At this point $object has first contribution loaded.
// Lets do a check to make sure this payment has the amount same as that of first contribution.
if ($objects['contribution']->total_amount != $input['amount']) {
CRM_Core_Error::debug_log_message("Subscription amount mismatch.");
echo "Failure: Subscription amount mismatch<p>";
return FALSE;
}
$contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$transaction = new CRM_Core_Transaction();
$now = date('YmdHis');
// fix dates that already exist
$dates = array('create_date', 'start_date', 'end_date', 'cancel_date', 'modified_date');
foreach ($dates as $name) {
if ($recur->$name) {
$recur->$name = CRM_Utils_Date::isoToMysql($recur->$name);
}
}
//load new contribution object if required.
if (!$first) {
// create a contribution and then get it processed
$contribution = new CRM_Contribute_BAO_Contribution();
$contribution->contact_id = $ids['contact'];
$contribution->financial_type_id = $objects['contributionType']->id;
$contribution->contribution_page_id = $ids['contributionPage'];
$contribution->contribution_recur_id = $ids['contributionRecur'];
$contribution->receive_date = $now;
$contribution->currency = $objects['contribution']->currency;
$contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
$contribution->amount_level = $objects['contribution']->amount_level;
$contribution->address_id = $objects['contribution']->address_id;
$contribution->campaign_id = $objects['contribution']->campaign_id;
$objects['contribution'] = &$contribution;
}
$objects['contribution']->invoice_id = md5(uniqid(rand(), TRUE));
$objects['contribution']->total_amount = $input['amount'];
$objects['contribution']->trxn_id = $input['trxn_id'];
// since we have processor loaded for sure at this point,
// check and validate gateway MD5 response if present
$this->checkMD5($ids, $input);
if ($input['response_code'] == 1) {
// Approved
if ($first) {
$recur->start_date = $now;
$recur->trxn_id = $recur->processor_id;
$this->_isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_START;
}
$statusName = 'In Progress';
if (($recur->installments > 0) &&
($input['subscription_paynum'] >= $recur->installments)
) {
// this is the last payment
$statusName = 'Completed';
$recur->end_date = $now;
$this->_isFirstOrLastRecurringPayment = CRM_Core_Payment::RECURRING_PAYMENT_END;
}
$recur->modified_date = $now;
$recur->contribution_status_id = array_search($statusName, $contributionStatus);
$recur->save();
}
else {
// Declined
// failed status
$recur->contribution_status_id = array_search('Failed', $contributionStatus);
$recur->cancel_date = $now;
$recur->save();
$message = ts("Subscription payment failed - %1", array(1 => htmlspecialchars($input['response_reason_text'])));
CRM_Core_Error::debug_log_message($message);
// the recurring contribution has declined a payment or has failed
// so we just fix the recurring contribution and not change any of
// the existing contributions
// CRM-9036
return TRUE;
}
// check if contribution is already completed, if so we ignore this ipn
if ($objects['contribution']->contribution_status_id == 1) {
$transaction->commit();
CRM_Core_Error::debug_log_message("Returning since contribution has already been handled.");
echo "Success: Contribution has already been handled<p>";
return TRUE;
}
$this->completeTransaction($input, $ids, $objects, $transaction, $recur);
}
/**
* @param $input
* @param $ids
*
* @return bool
*/
public function getInput(&$input, &$ids) {
$input['amount'] = $this->retrieve('x_amount', 'String');
$input['subscription_id'] = $this->retrieve('x_subscription_id', 'Integer');
$input['response_code'] = $this->retrieve('x_response_code', 'Integer');
$input['MD5_Hash'] = $this->retrieve('x_MD5_Hash', 'String', FALSE, '');
$input['response_reason_code'] = $this->retrieve('x_response_reason_code', 'String', FALSE);
$input['response_reason_text'] = $this->retrieve('x_response_reason_text', 'String', FALSE);
$input['subscription_paynum'] = $this->retrieve('x_subscription_paynum', 'Integer', FALSE, 0);
$input['trxn_id'] = $this->retrieve('x_trans_id', 'String', FALSE);
if ($input['trxn_id']) {
$input['is_test'] = 0;
}
else {
$input['is_test'] = 1;
$input['trxn_id'] = md5(uniqid(rand(), TRUE));
}
if (!$this->getBillingID($ids)) {
return FALSE;
}
$billingID = $ids['billing'];
$params = array(
'first_name' => 'x_first_name',
'last_name' => 'x_last_name',
"street_address-{$billingID}" => 'x_address',
"city-{$billingID}" => 'x_city',
"state-{$billingID}" => 'x_state',
"postal_code-{$billingID}" => 'x_zip',
"country-{$billingID}" => 'x_country',
"email-{$billingID}" => 'x_email',
);
foreach ($params as $civiName => $resName) {
$input[$civiName] = $this->retrieve($resName, 'String', FALSE);
}
}
/**
* @param $ids
* @param $input
*/
public function getIDs(&$ids, &$input) {
$ids['contact'] = $this->retrieve('x_cust_id', 'Integer', FALSE, 0);
$ids['contribution'] = $this->retrieve('x_invoice_num', 'Integer');
// joining with contribution table for extra checks
$sql = "
SELECT cr.id, cr.contact_id
FROM civicrm_contribution_recur cr
INNER JOIN civicrm_contribution co ON co.contribution_recur_id = cr.id
WHERE cr.processor_id = '{$input['subscription_id']}' AND
(cr.contact_id = {$ids['contact']} OR co.id = {$ids['contribution']})
LIMIT 1";
$contRecur = CRM_Core_DAO::executeQuery($sql);
$contRecur->fetch();
$ids['contributionRecur'] = $contRecur->id;
if ($ids['contact'] != $contRecur->contact_id) {
$message = ts("Recurring contribution appears to have been re-assigned from id %1 to %2, continuing with %2.", array(1 => $ids['contact'], 2 => $contRecur->contact_id));
CRM_Core_Error::debug_log_message($message);
$ids['contact'] = $contRecur->contact_id;
}
if (!$ids['contributionRecur']) {
$message = ts("Could not find contributionRecur id: %1", array(1 => htmlspecialchars(print_r($input, TRUE))));
CRM_Core_Error::debug_log_message($message);
echo "Failure: $message<p>";
exit();
}
// get page id based on contribution id
$ids['contributionPage'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
$ids['contribution'],
'contribution_page_id'
);
if ($input['component'] == 'event') {
// FIXME: figure out fields for event
}
else {
// get the optional ids
// Get membershipId. Join with membership payment table for additional checks
$sql = "
SELECT m.id
FROM civicrm_membership m
INNER JOIN civicrm_membership_payment mp ON m.id = mp.membership_id AND mp.contribution_id = {$ids['contribution']}
WHERE m.contribution_recur_id = {$ids['contributionRecur']}
LIMIT 1";
if ($membershipId = CRM_Core_DAO::singleValueQuery($sql)) {
$ids['membership'] = $membershipId;
}
// FIXME: todo related_contact and onBehalfDupeAlert. Check paypalIPN.
}
}
/**
* @param string $name
* Parameter name.
* @param string $type
* Parameter type.
* @param bool $abort
* Abort if not present.
* @param null $default
* Default value.
*
* @throws CRM_Core_Exception
* @return mixed
*/
public function retrieve($name, $type, $abort = TRUE, $default = NULL) {
$value = CRM_Utils_Type::validate(
empty($this->_inputParameters[$name]) ? $default : $this->_inputParameters[$name],
$type,
FALSE
);
if ($abort && $value === NULL) {
throw new CRM_Core_Exception("Could not find an entry for $name");
}
return $value;
}
/**
* @param $ids
* @param $input
*
* @return bool
*/
public function checkMD5($ids, $input) {
$paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($ids['paymentProcessor'],
$input['is_test'] ? 'test' : 'live'
);
$paymentObject = CRM_Core_Payment::singleton($input['is_test'] ? 'test' : 'live', $paymentProcessor);
if (!$paymentObject->checkMD5($input['MD5_Hash'], $input['trxn_id'], $input['amount'], TRUE)) {
CRM_Core_Error::debug_log_message("MD5 Verification failed.");
echo "Failure: Security verification failed<p>";
exit();
}
return TRUE;
}
}
| gpl-2.0 |
PixelDevLabs/Ezia-Cleaner_Build-934afd57b26a | RSPiX/Src/ORANGE/Parse/testBatch.cpp | 1192 | ////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 RWS Inc, All Rights Reserved
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of version 2 of the GNU General Public License as published by
// the Free Software Foundation
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#include "simplebatch.h"
main()
{
RBatch ftest("testBatch.in");
ftest.configure(" \t,","~");
while (ftest.GetLine() != EOF)
{
// Dump info:
TRACE("Line %ld has %hd tokens:\n",ftest.m_lCurrentLine,ftest.m_sNumTokens);
for (int16_t i=0;i<ftest.m_sNumTokens;i++)
{
TRACE("\tToken #%hd at char %hd = {%s}\n",i,
ftest.m_sLinePos[i],ftest.m_pszTokenList[i]);
}
}
return 0;
}
| gpl-2.0 |
thuctoa/bienbac | wp-content/themes/vietmoz-wp/framework/resources/bootstrap/js/bootstrap.js | 69233 | /*!
* Bootstrap v3.3.2 (http://getbootstrap.com)
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
/*!
* Generated using the Bootstrap Customizer (http://getbootstrap.com/customize/?id=398872442a30c2aaaee4)
* Config saved to config.json and https://gist.github.com/398872442a30c2aaaee4
*/
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery')
}
+function ($) {
'use strict';
var version = $.fn.jquery.split(' ')[0].split('.')
if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1)) {
throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher')
}
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.3.2
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.2'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.3.2
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.3.2'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state = state + 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
$el[val](data[state] == null ? this.options[state] : data[state])
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
}
if (changed) this.$element.toggleClass('active')
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
e.preventDefault()
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.3.2
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused =
this.sliding =
this.interval =
this.$active =
this.$items = null
this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.3.2'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true,
keyboard: true
}
Carousel.prototype.keydown = function (e) {
if (/input|textarea/i.test(e.target.tagName)) return
switch (e.which) {
case 37: this.prev(); break
case 39: this.next(); break
default: return
}
e.preventDefault()
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function (item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function (direction, active) {
var activeIndex = this.getItemIndex(active)
var willWrap = (direction == 'prev' && activeIndex === 0)
|| (direction == 'next' && activeIndex == (this.$items.length - 1))
if (willWrap && !this.options.wrap) return active
var delta = direction == 'prev' ? -1 : 1
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var that = this
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
var clickHandler = function (e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
}
$(document)
.on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
.on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.3.2
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.3.2'
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger('shown.bs.dropdown', relatedTarget)
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if ((!isActive && e.which != 27) || (isActive && e.which == 27)) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.divider):visible a'
var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc)
if (!$items.length) return
var index = $items.index(e.target)
if (e.which == 38 && index > 0) index-- // up
if (e.which == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function () {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
})
}
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '[role="menu"]', Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '[role="listbox"]', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.3.2
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$backdrop =
this.isShown = null
this.scrollbarWidth = 0
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.2'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
if (that.options.backdrop) that.adjustBackdrop()
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$element.find('.modal-dialog') // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
.off('click.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function () {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.prependTo(this.$element)
.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus.call(this.$element[0])
: this.hide.call(this)
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function () {
if (this.options.backdrop) this.adjustBackdrop()
this.adjustDialog()
}
Modal.prototype.adjustBackdrop = function () {
this.$backdrop
.css('height', 0)
.css('height', this.$element[0].scrollHeight)
}
Modal.prototype.adjustDialog = function () {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function () {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function () {
this.bodyIsOverflowing = document.body.scrollHeight > document.documentElement.clientHeight
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', '')
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.3.2
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type =
this.options =
this.enabled =
this.timeout =
this.hoverState =
this.$element = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.3.2'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport)
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (self && self.$tip && self.$tip.is(':visible')) {
self.hoverState = 'in'
return
}
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var $container = this.options.container ? $(this.options.container) : this.$element.parent()
var containerDim = this.getPosition($container)
placement = placement == 'bottom' && pos.bottom + actualHeight > containerDim.bottom ? 'top' :
placement == 'top' && pos.top - actualHeight < containerDim.top ? 'bottom' :
placement == 'right' && pos.right + actualWidth > containerDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < containerDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function () {
var prevHoverState = that.hoverState
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
if (prevHoverState == 'out') that.leave(that)
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top = offset.top + marginTop
offset.left = offset.left + marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var isVertical = /top|bottom/.test(placement)
var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, isHorizontal) {
this.arrow()
.css(isHorizontal ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
.css(isHorizontal ? 'top' : 'left', '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function (callback) {
var that = this
var $tip = this.tip()
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element
.removeAttr('aria-describedby')
.trigger('hidden.bs.' + that.type)
callback && callback()
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function ($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var elRect = el.getBoundingClientRect()
if (elRect.width == null) {
// width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
}
var elOffset = isBody ? { top: 0, left: 0 } : $element.offset()
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.width) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function (prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function () {
return (this.$tip = this.$tip || $(this.options.template))
}
Tooltip.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
Tooltip.prototype.destroy = function () {
var that = this
clearTimeout(this.timeout)
this.hide(function () {
that.$element.off('.' + that.type).removeData('bs.' + that.type)
})
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.3.2
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.3.2'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
Popover.prototype.tip = function () {
if (!this.$tip) this.$tip = $(this.options.template)
return this.$tip
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.3.2
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
this.element = $(element)
}
Tab.VERSION = '3.3.2'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var $previous = $ul.find('.active:last a')
var hideEvent = $.Event('hide.bs.tab', {
relatedTarget: $this[0]
})
var showEvent = $.Event('show.bs.tab', {
relatedTarget: $previous[0]
})
$previous.trigger(hideEvent)
$this.trigger(showEvent)
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function () {
$previous.trigger({
type: 'hidden.bs.tab',
relatedTarget: $this[0]
})
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: $previous[0]
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& (($active.length && $active.hasClass('fade')) || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', false)
element
.addClass('active')
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element
.closest('li.dropdown')
.addClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
var clickHandler = function (e) {
e.preventDefault()
Plugin.call($(this), 'show')
}
$(document)
.on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
.on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.3.2
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed =
this.unpin =
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.3.2'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && scrollTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = $('body').height()
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
if (data.offsetTop != null) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.3.2
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.$trigger = $(this.options.trigger).filter('[href="#' + element.id + '"], [data-target="#' + element.id + '"]')
this.transitioning = null
if (this.options.parent) {
this.$parent = this.getParent()
} else {
this.addAriaAndCollapsedClass(this.$element, this.$trigger)
}
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.3.2'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true,
trigger: '[data-toggle="collapse"]'
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var activesData
var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
if (actives && actives.length) {
activesData = actives.data('bs.collapse')
if (activesData && activesData.transitioning) return
}
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
if (actives && actives.length) {
Plugin.call(actives, 'hide')
activesData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
.attr('aria-expanded', true)
this.$trigger
.removeClass('collapsed')
.attr('aria-expanded', true)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
.attr('aria-expanded', false)
this.$trigger
.addClass('collapsed')
.attr('aria-expanded', false)
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.removeClass('collapsing')
.addClass('collapse')
.trigger('hidden.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
Collapse.prototype.getParent = function () {
return $(this.options.parent)
.find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
.each($.proxy(function (i, element) {
var $element = $(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
}, this))
.end()
}
Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
var isOpen = $element.hasClass('in')
$element.attr('aria-expanded', isOpen)
$trigger
.toggleClass('collapsed', !isOpen)
.attr('aria-expanded', isOpen)
}
function getTargetFromTrigger($trigger) {
var href
var target = $trigger.attr('data-target')
|| (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
return $(target)
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && option == 'show') options.toggle = false
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var $this = $(this)
if (!$this.attr('data-target')) e.preventDefault()
var $target = getTargetFromTrigger($this)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $.extend({}, $this.data(), { trigger: this })
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.3.2
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
var process = $.proxy(this.process, this)
this.$body = $('body')
this.$scrollElement = $(element).is('body') ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', process)
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.3.2'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
var offsetMethod = 'offset'
var offsetBase = 0
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
var self = this
this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[$href[offsetMethod]().top + offsetBase, href]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
this.clear()
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
ScrollSpy.prototype.clear = function () {
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.3.2
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
| gpl-2.0 |
seecr/meresco-lucene | test/org/meresco/lucene/suggestion/SuggestionNGramKeysFilterTest.java | 1772 | /* begin license *
*
* "Meresco Lucene" is a set of components and tools to integrate Lucene (based on PyLucene) into Meresco
*
* Copyright (C) 2016 Seecr (Seek You Too B.V.) https://seecr.nl
*
* This file is part of "Meresco Lucene"
*
* "Meresco Lucene" 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.
*
* "Meresco Lucene" 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 "Meresco Lucene"; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* end license */
package org.meresco.lucene.suggestion;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.io.IOException;
import org.apache.lucene.util.FixedBitSet;
import org.junit.Test;
public class SuggestionNGramKeysFilterTest {
@Test
public void testEquals() throws IOException {
FixedBitSet keys = new FixedBitSet(5);
keys.set(2);
FixedBitSet otherKeys = new FixedBitSet(4);
SuggestionNGramKeysFilter keySetFilter = new SuggestionNGramKeysFilter(keys, "__key__");
assertFalse(new SuggestionNGramKeysFilter(keys, "__other_key__").equals(keySetFilter));
assertFalse(new SuggestionNGramKeysFilter(otherKeys, "__key__").equals(keySetFilter));
assertEquals(new SuggestionNGramKeysFilter(keys, "__key__"), keySetFilter);
}
}
| gpl-2.0 |
glye/ezpublish-kernel | eZ/Publish/Core/FieldType/Tests/XmlText/Gateway/LegacyStorageTest.php | 19796 | <?php
/**
* File containing the LegacyStorageTest for XmlText FieldType
*
* @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\Core\Repository\Tests\FieldType\XmlText\Gateway;
use eZ\Publish\SPI\Persistence\Content\VersionInfo;
use eZ\Publish\SPI\Persistence\Content\Field;
use eZ\Publish\SPI\Persistence\Content\FieldValue;
use DOMDocument;
use PHPUnit_Framework_TestCase;
/**
* Tests the LegacyStorage
* Class LegacyStorageTest
* @package eZ\Publish\Core\Repository\Tests\FieldType\XmlText\Gateway
*/
class LegacyStorageTest extends PHPUnit_Framework_TestCase
{
/**
* @return \PHPUnit_Framework_MockObject_MockObject|\eZ\Publish\Core\FieldType\XmlText\XmlTextStorage\Gateway\LegacyStorage
*/
protected function getPartlyMockedLegacyStorage( array $testMethods = null )
{
return $this->getMock( 'eZ\Publish\Core\FieldType\XmlText\XmlTextStorage\Gateway\LegacyStorage', $testMethods );
}
/**
* @return array
*/
public function providerForTestStoreFieldData()
{
/**
* 1. Input XML
* 2. Use of getLinksId() in form of array( array $arguments, array $return ), empty means no call
* 3. Use of getObjectId() in form of array( array $arguments, array $return ), empty means no call
* 4. Use of insertLink() in form of array( $argument, $return ), empty means no call
* 5. Expected return value
* 6. Resulting XML
*/
return array(
// LINK
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url="/test">object link</link>.</paragraph></section>
',
array( array( '/test' ), array( '/test' => 55 ) ),
array( array(), array() ),
array(),
true,
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url_id="55">object link</link>.</paragraph></section>
',
),
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url="/test">object link</link><link url="/test">object link</link>.</paragraph></section>
',
array( array( '/test' ), array( '/test' => 55 ) ),
array( array(), array() ),
array(),
true,
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url_id="55">object link</link><link url_id="55">object link</link>.</paragraph></section>
',
),
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link object_remote_id="34oi5ne5tj5iojte8oj58otehj5tjheo8">object link</link>.</paragraph></section>
',
array( array(), array() ),
array( array( '34oi5ne5tj5iojte8oj58otehj5tjheo8' ), array( '34oi5ne5tj5iojte8oj58otehj5tjheo8' => 55 ) ),
array(),
true,
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link object_id="55">object link</link>.</paragraph></section>
',
),
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link object_remote_id="34oi5ne5tj5iojte8oj58otehj5tjheo8">object link</link><embed object_remote_id="34oi5ne5tj5iojte8oj58otehj5tjheo8">object link</embed>.</paragraph></section>
',
array( array(), array() ),
array( array( '34oi5ne5tj5iojte8oj58otehj5tjheo8' ), array( '34oi5ne5tj5iojte8oj58otehj5tjheo8' => 55 ) ),
array(),
true,
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link object_id="55">object link</link><embed object_id="55">object link</embed>.</paragraph></section>
',
),
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url="/newUrl">object link</link>.</paragraph></section>
',
array( array( '/newUrl' ), array() ),
array( array(), array() ),
array( '/newUrl', 66 ),
true,
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url_id="66">object link</link>.</paragraph></section>
',
),
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url_id="55">object link</link>.</paragraph></section>
',
array(),
array(),
array(),
false,
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url_id="55">object link</link>.</paragraph></section>
',
),
// EMBED
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <embed object_remote_id="34oi5ne5tj5iojte8oj58otehj5tjheo8">object embed</embed>.</paragraph></section>
',
array( array(), array() ),
array( array( '34oi5ne5tj5iojte8oj58otehj5tjheo8' ), array( '34oi5ne5tj5iojte8oj58otehj5tjheo8' => 55 ) ),
array(),
true,
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <embed object_id="55">object embed</embed>.</paragraph></section>
',
),
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <embed object_id="55">object embed</embed>.</paragraph></section>
',
array(),
array(),
array(),
false,
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <embed object_id="55">object embed</embed>.</paragraph></section>
',
),
// EMBED-INLINE
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <embed-inline object_remote_id="34oi5ne5tj5iojte8oj58otehj5tjheo8">object embed</embed-inline>.</paragraph></section>
',
array( array(), array() ),
array( array( '34oi5ne5tj5iojte8oj58otehj5tjheo8' ), array( '34oi5ne5tj5iojte8oj58otehj5tjheo8' => 55 ) ),
array(),
true,
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <embed-inline object_id="55">object embed</embed-inline>.</paragraph></section>
',
),
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <embed-inline object_id="55">object embed</embed-inline>.</paragraph></section>
',
array(),
array(),
array(),
false,
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <embed-inline object_id="55">object embed</embed-inline>.</paragraph></section>
',
),
);
}
/**
* @dataProvider providerForTestStoreFieldData
*/
public function testStoreFieldData(
$inputXML,
$getLinksIdData,
$getObjectIdData,
$insertLinkData,
$expectedReturnValue,
$expectedResultXML
)
{
$inputDomDocument = new DOMDocument;
$inputDomDocument->loadXML( $inputXML );
$versionInfo = new VersionInfo;
$field = new Field( array( 'value' => new FieldValue( array( 'data' => $inputDomDocument ) ) ) );
$legacyStorage = $this->getPartlyMockedLegacyStorage( array( 'getLinksId', 'getObjectId', 'insertLink' ) );
foreach (
array(
'getLinksId' => $getLinksIdData,
'getObjectId' => $getObjectIdData,
'insertLink' => $insertLinkData
) as $method => $data
)
{
if ( empty( $data ) )
{
$legacyStorage->expects( $this->never() )
->method( $method );
}
else
{
$legacyStorage->expects( $this->once() )
->method( $method )
->with( $this->equalTo( $data[0] ) )
->will( $this->returnValue( $data[1] ) );
}
}
$this->assertEquals( $expectedReturnValue, $legacyStorage->storeFieldData( $versionInfo, $field ) );
$this->assertEquals( $expectedResultXML, $field->value->data->saveXML() );
}
/**
* @return array
*/
public function providerForTestStoreFieldDataException()
{
/**
* 1. Input XML
* 2. Use of getLinksId() in form of array( array $arguments, array $return ), empty means no call
* 3. Use of getObjectId() in form of array( array $arguments, array $return ), empty means no call
* 4. Use of insertLink() in form of array( $argument, $return ), empty means no call
* 5. Expected return value
* 6. Resulting XML
*/
return array(
// LINK
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url="">object link</link>.</paragraph></section>
',
array( array(), array() ),
array( array(), array() ),
array(),
),
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link object_remote_id="34oi5ne5tj5iojte8oj58otehj5tjheo8">object link</link>.</paragraph></section>
',
array( array(), array() ),
array( array( '34oi5ne5tj5iojte8oj58otehj5tjheo8' ), array() ),
array(),
),
// EMBED
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <embed object_remote_id="34oi5ne5tj5iojte8oj58otehj5tjheo8">object link</embed>.</paragraph></section>
',
array( array(), array() ),
array( array( '34oi5ne5tj5iojte8oj58otehj5tjheo8' ), array() ),
array(),
),
// EMBED-INLINE
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <embed-inline object_remote_id="34oi5ne5tj5iojte8oj58otehj5tjheo8">object link</embed-inline>.</paragraph></section>
',
array( array(), array() ),
array( array( '34oi5ne5tj5iojte8oj58otehj5tjheo8' ), array() ),
array(),
),
);
}
/**
* @dataProvider providerForTestStoreFieldDataException
* @expectedException \eZ\Publish\Core\Base\Exceptions\NotFoundException
*/
public function testStoreFieldDataException(
$inputXML,
$getLinksIdData,
$getObjectIdData,
$insertLinkData
)
{
$inputDomDocument = new DOMDocument;
$inputDomDocument->loadXML( $inputXML );
$versionInfo = new VersionInfo;
$field = new Field( array( 'value' => new FieldValue( array( 'data' => $inputDomDocument ) ) ) );
$legacyStorage = $this->getPartlyMockedLegacyStorage( array( 'getLinksId', 'getObjectId', 'insertLink' ) );
foreach (
array(
'getLinksId' => $getLinksIdData,
'getObjectId' => $getObjectIdData,
'insertLink' => $insertLinkData
) as $method => $data
)
{
if ( empty( $data ) )
{
$legacyStorage->expects( $this->never() )
->method( $method );
}
else
{
$legacyStorage->expects( $this->once() )
->method( $method )
->with( $this->equalTo( $data[0] ) )
->will( $this->returnValue( $data[1] ) );
}
}
$legacyStorage->storeFieldData( $versionInfo, $field );
}
/**
* @return array
*/
public function providerForTestGetFieldData()
{
/**
* 1. Input XML
* 2. Use of getLinksUrl() in form of array( array $arguments, array $return ), empty means no call
* 6. Resulting XML
*/
return array(
// LINK
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url_id="55">object link</link>.</paragraph></section>
',
array( array( 55 ), array( 55 => '/test' ) ),
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url="/test">object link</link>.</paragraph></section>
',
),
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url_id="55">object link</link><link url_id="55">object link</link>.</paragraph></section>
',
array( array( 55 ), array( 55 => '/test' ) ),
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url="/test">object link</link><link url="/test">object link</link>.</paragraph></section>
',
),
array(
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url_id="">object link</link>.</paragraph></section>
',
array(),
'<?xml version="1.0" encoding="utf-8"?>
<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/" xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/" xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/"><paragraph>This is an <link url_id="">object link</link>.</paragraph></section>
',
),
);
}
/**
* @dataProvider providerForTestGetFieldData
*/
public function testGetFieldData(
$inputXML,
$getLinksUrlData,
$expectedResultXML
)
{
$inputDomDocument = new DOMDocument;
$inputDomDocument->loadXML( $inputXML );
$field = new Field( array( 'value' => new FieldValue( array( 'data' => $inputDomDocument ) ) ) );
$legacyStorage = $this->getPartlyMockedLegacyStorage( array( 'getLinksUrl' ) );
if ( empty( $getLinksUrlData ) )
{
$legacyStorage->expects( $this->never() )
->method( 'getLinksUrl' );
}
else
{
$legacyStorage->expects( $this->once() )
->method( 'getLinksUrl' )
->with( $this->equalTo( $getLinksUrlData[0] ) )
->will( $this->returnValue( $getLinksUrlData[1] ) );
}
$legacyStorage->getFieldData( $field );
$this->assertEquals( $expectedResultXML, $field->value->data->saveXML() );
}
}
| gpl-2.0 |
andongniao/AiStore | src/com/youai/aistore/Bean/ConsigneeBean.java | 567 | package com.youai.aistore.Bean;
/**
* 收货人信息实体
*
* @author Qzr
*
*/
public class ConsigneeBean extends Base {
private String consignee;
private String address;
private String tel;
public String getConsignee() {
return consignee;
}
public void setConsignee(String consignee) {
this.consignee = consignee;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
| gpl-2.0 |