repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
smarr/Truffle
|
compiler/src/org.graalvm.compiler.truffle.test/src/org/graalvm/compiler/truffle/test/AbstractSplittingStrategyTest.java
|
9131
|
/*
* Copyright (c) 2011, 2020, 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 org.graalvm.compiler.truffle.test;
import java.lang.reflect.Field;
import org.graalvm.compiler.truffle.runtime.GraalTruffleRuntime;
import org.graalvm.compiler.truffle.runtime.GraalTruffleRuntimeListener;
import org.graalvm.compiler.truffle.runtime.OptimizedCallTarget;
import org.graalvm.compiler.truffle.runtime.OptimizedDirectCallNode;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.dsl.ReportPolymorphism;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.DirectCallNode;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.nodes.NodeCost;
import com.oracle.truffle.api.nodes.RootNode;
import com.oracle.truffle.api.test.ReflectionUtils;
public class AbstractSplittingStrategyTest extends TestWithPolyglotOptions {
protected static final GraalTruffleRuntime runtime = (GraalTruffleRuntime) Truffle.getRuntime();
static final Object[] noArguments = {};
protected SplitCountingListener listener;
protected static void testSplitsDirectCallsHelper(OptimizedCallTarget callTarget, Object[] firstArgs, Object[] secondArgs) {
// two callers for a target are needed
runtime.createDirectCallNode(callTarget);
final DirectCallNode directCallNode = runtime.createDirectCallNode(callTarget);
directCallNode.call(firstArgs);
Assert.assertFalse("Target needs split before the node went polymorphic", getNeedsSplit(callTarget));
directCallNode.call(firstArgs);
Assert.assertFalse("Target needs split before the node went polymorphic", getNeedsSplit(callTarget));
directCallNode.call(secondArgs);
Assert.assertTrue("Target does not need split after the node went polymorphic", getNeedsSplit(callTarget));
directCallNode.call(secondArgs);
Assert.assertTrue("Target needs split but not split", directCallNode.isCallTargetCloned());
// Test new dirrectCallNode will split
final DirectCallNode newCallNode = runtime.createDirectCallNode(callTarget);
newCallNode.call(firstArgs);
Assert.assertTrue("new call node to \"needs split\" target is not split", newCallNode.isCallTargetCloned());
}
protected static void testDoesNotSplitDirectCallHelper(OptimizedCallTarget callTarget, Object[] firstArgs, Object[] secondArgs) {
// two callers for a target are needed
runtime.createDirectCallNode(callTarget);
final DirectCallNode directCallNode = runtime.createDirectCallNode(callTarget);
directCallNode.call(firstArgs);
Assert.assertFalse("Target needs split before the node went polymorphic", getNeedsSplit(callTarget));
directCallNode.call(firstArgs);
Assert.assertFalse("Target needs split before the node went polymorphic", getNeedsSplit(callTarget));
directCallNode.call(secondArgs);
Assert.assertFalse("Target needs split without reporting", getNeedsSplit(callTarget));
directCallNode.call(secondArgs);
Assert.assertFalse("Target does not need split but is split", directCallNode.isCallTargetCloned());
// Test new dirrectCallNode will split
final DirectCallNode newCallNode = runtime.createDirectCallNode(callTarget);
newCallNode.call(firstArgs);
Assert.assertFalse("new call node to non \"needs split\" target is split", newCallNode.isCallTargetCloned());
}
protected static Boolean getNeedsSplit(OptimizedCallTarget callTarget) {
try {
return (Boolean) reflectivelyGetField(callTarget, "needsSplit");
} catch (NoSuchFieldException | IllegalAccessException e) {
Assert.assertTrue("Cannot read \"needsSplit\" field from OptimizedCallTarget", false);
return false;
}
}
protected static Object reflectivelyGetField(Object o, String fieldName) throws NoSuchFieldException, IllegalAccessException {
Field fallbackEngineDataField = null;
Class<?> cls = o.getClass();
while (fallbackEngineDataField == null) {
try {
fallbackEngineDataField = cls.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
if (cls.getSuperclass() != null) {
cls = cls.getSuperclass();
} else {
throw e;
}
}
}
ReflectionUtils.setAccessible(fallbackEngineDataField, true);
return fallbackEngineDataField.get(o);
}
protected static void reflectivelySetField(Object o, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
Field fallbackEngineDataField = null;
Class<?> cls = o.getClass();
while (fallbackEngineDataField == null) {
try {
fallbackEngineDataField = cls.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
if (cls.getSuperclass() != null) {
cls = cls.getSuperclass();
} else {
throw e;
}
}
}
ReflectionUtils.setAccessible(fallbackEngineDataField, true);
fallbackEngineDataField.set(o, value);
}
protected static void createDummyTargetsToBoostGrowingSplitLimit() {
for (int i = 0; i < 10; i++) {
runtime.createCallTarget(new DummyRootNode());
}
}
@Before
public void addListener() {
setupContext("engine.Compilation", "false",
"engine.SplittingGrowthLimit", "2.0");
listener = new SplitCountingListener();
runtime.addListener(listener);
}
@After
public void removeListener() {
runtime.removeListener(listener);
}
static class SplitCountingListener implements GraalTruffleRuntimeListener {
int splitCount = 0;
@Override
public void onCompilationSplit(OptimizedDirectCallNode callNode) {
splitCount++;
}
}
static class DummyRootNode extends RootNode {
@Child private Node polymorphic = new Node() {
@Override
public NodeCost getCost() {
return NodeCost.POLYMORPHIC;
}
};
protected DummyRootNode() {
super(null);
}
@Override
public boolean isCloningAllowed() {
return true;
}
@Override
public Object execute(VirtualFrame frame) {
return 1;
}
@Override
public String toString() {
return "INNER";
}
}
// Root node for all nodes in this test
@ReportPolymorphism
abstract static class SplittingTestNode extends Node {
public abstract Object execute(VirtualFrame frame);
}
static class ReturnsFirstArgumentNode extends SplittingTestNode {
@Override
public Object execute(VirtualFrame frame) {
return frame.getArguments()[0];
}
}
static class ReturnsSecondArgumentNode extends SplittingTestNode {
@Override
public Object execute(VirtualFrame frame) {
return frame.getArguments()[1];
}
}
abstract class SplittableRootNode extends RootNode {
protected SplittableRootNode() {
super(null);
}
@Override
public boolean isCloningAllowed() {
return true;
}
}
class SplittingTestRootNode extends SplittableRootNode {
@Child private SplittingTestNode bodyNode;
SplittingTestRootNode(SplittingTestNode bodyNode) {
super();
this.bodyNode = bodyNode;
}
@Override
public Object execute(VirtualFrame frame) {
return bodyNode.execute(frame);
}
}
}
|
gpl-2.0
|
kazuyaujihara/osra_vs
|
GraphicsMagick/scripts/rst2htmldeco.py
|
8024
|
#!/usr/bin/env python
# vim:ts=4:sw=4:expandtab
#* Author: Mark Mitchell
#* Copyright 2005-2008 Mark Mitchell, All Rights Reserved
#* License: see __license__ below.
__doc__ = """
Renders reStructuredText files to HTML using the custom docutils writer
docutils_htmldeco_writer, which inserts a common header and navigation menu at
the top of all HTML pages. The header and navigation HTML blobs are
kept in a separate python file, html_fragments.py.
Usage:
rst2htmldeco.py [options] SRCFILE OUTFILE
SRCFILE is the path to a restructured text file.
For example: ./AUTHORS.txt
OUTFILE is the path where the HTML file is written.
For example: ./www/authors.html
Options:
-h --help Print this help message
-e --embed-stylesheet=<FILE>
The stylesheet will be embedded in the HTML.
-l --link-stylesheet=<URL>
The HTML file will Link to the stylesheet,
using the URL verbatim.
-r --url-prefix=<PATH>
The value of url-prefix is prefixed to all the URLs in the
path to get to the top directory from the OUTFILE
directory. Used to create working relative URLs in the custom
header and navigation menu. Defaults to empty.
Example: --url-prefix=../../
-e and -l are mutually excusive. If neither is specified, nothing
will work.
Note that images referenced from the stylesheet may require different
image-dir paths depending on whether the stylesheet is embedded or linked.
If linked, image URLs in the stylesheet are relative to the stylesheet's
location. If embedded, image URLs in the stylesheet are relative to the
HTML file's path.
Embedding vs. linking stylesheet
=================================
Embedding stylesheet
----------------------
* The HTML file needs no additional files in particular locations in order
to render nicely.
* The size of every HTML file is inflated. Download time is increased.
Linking stylesheet
-------------------
* Best performance for files served via HTTP, as browsers will download the
stylesheet once and cache it, and individual HTML files will be more compact.
* No need to regenerate every HTML file if the stylesheet is changed.
* If the HTML file is detached from stylesheet, it will look very plain
when rendered by a browser.
Images are always referenced (there's two, the logo and banner background),
so will not be rendered if the HTML file is detached from the image files.
"""
__copyright__ = "2005, 2008, Mark Mitchell"
__license__ = """
Copyright 2005, 2008, Mark Mitchell
Permission is hereby granted, free of charge, to any person obtaining
a copy of this oftware 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 or copyright holders 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 Software
or the use or other dealings in the Software.
"""
import sys
import os, os.path
import locale
import getopt
import html_fragments
try:
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline, default_description
# Python module name of the custom HTML writer, must be in sys.path
rst_writer = 'docutils_htmldeco_writer'
docutils_opts = [
'--cloak-email-addresses', # Obfusticate email addresses
'--no-generator', # no "Generated by Docutils" credit and link at the end of the document.
# '--date', # Include the date at the end of the document (UTC)
# '--time', # Include the time & date (UTC)
'--no-datestamp', # Do not include a datestamp of any kind
'--traceback', # Enable Python tracebacks when Docutils is halted.
'--rfc-references', # Recognize and link to standalone RFC references (like "RFC 822")
'--rfc-base-url="http://rfc-ref.org/RFC-TEXTS/"', # Base URL for RFC references
]
def make_html(src, dest, embed_stylesheet=False,
stylesheet=None, url_prefix=''):
# Fix the url_prefix path in the banner HTML.
# This Python tricky business is necessary because the custom docutils
# writer, which inserts the HTML blobs, can't do it, because docutils
# doesn't provide any way to pass an argument such as image_dir to the
# writer.
# There must be a better way, but I haven't figured it out yet.
if url_prefix:
html_fragments.url_prefix = url_prefix.rstrip('/') + '/'
html_fragments.nav = html_fragments.make_nav()
html_fragments.banner = html_fragments.make_banner()
html_fragments.footer = html_fragments.make_footer()
args = list(docutils_opts)
if embed_stylesheet:
# for embedded stylesheet
args.append('--stylesheet-path=%s' % stylesheet)
args.append('--embed-stylesheet')
else:
# for linked stylesheet
args.append('--stylesheet=%s' % stylesheet)
args.append('--link-stylesheet')
if src is not None:
args.append(src)
if dest is not None:
args.append(dest)
# Invoke docutils processing of the reST document. This call
# to a docutils method ends up executing the custom HTML writer
# in docutils_htmldeco_writer.py
description = ('Generates (X)HTML documents from standalone reStructuredText '
'sources, with custom banner and footer. ' + default_description)
publish_cmdline(writer_name=rst_writer,
description=description,
argv=args)
def main(argv=None):
if argv is None:
argv = sys.argv[1:]
# parse command line options
try:
opts, posn_args = getopt.getopt(argv, 'he:l:u:',
['help',
'embed-stylesheet=',
'link-stylesheet=',
'url-prefix=',
])
except getopt.GetoptError, msg:
print msg
print __doc__
return 1
# process options
embed_stylesheet = False
link_stylesheet = True
stylesheet = None
url_prefix = ''
for opt, val in opts:
if opt in ("-h", "--help"):
print __doc__
return 0
if opt in ("-e", "--embed-stylesheet"):
link_stylesheet = False
embed_stylesheet = True
stylesheet = val
if opt in ("-l", "--link-stylesheet"):
embed_stylesheet = False
link_stylesheet = True
stylesheet = val
if opt in ("-u", "--url-prefix"):
url_prefix = val
#if len(posn_args) != 2:
# print >> sys.stderr, 'Missing arguments'
# print >> sys.stderr, __doc__
# return 1
try:
srcfile_path = posn_args[0]
except IndexError:
srcfile_path = None
try:
outfile_path = posn_args[1]
except IndexError:
outfile_path = None
make_html(srcfile_path, outfile_path, embed_stylesheet=embed_stylesheet,
stylesheet=stylesheet, url_prefix=url_prefix)
return 0
if __name__ == '__main__':
sys.exit(main())
|
gpl-2.0
|
victoralex/gameleon
|
public_admin/components/translationEditor/translationEditor.php
|
6927
|
<?
class Component extends ComponentDefault
{
// Data transfer errors
const ERR_INVALID_LANGUAGE = 501;
const ERR_INVALID_AREA = 502;
const ERR_COMPONENT_NAME = 503;
// Server errors
const ERR_NONEXISTENT_AREA = 601;
const ERR_NONEXISTENT_COMPONENT = 602;
const ERR_NO_CONTENT = 603;
const ERR_INVALID_CONTENT = 604;
public function onShowComponents()
{
if( !isset($_GET["language"]) || !ereg("^[a-z]{2}-[A-Z]{2}$", $_GET["language"]) )
{
return $this->setHeaderResult( Component::ERR_INVALID_LANGUAGE );
}
if( !isset($_GET["area"]) || !ereg("^[a-z_]+$", $_GET["area"]) )
{
return $this->setHeaderResult( Component::ERR_INVALID_AREA );
}
if( !file_exists( SystemConfig::$installDir . DIRECTORY_SEPARATOR . $_GET["area"] ) )
{
return $this->setHeaderResult( Component::ERR_NONEXISTENT_AREA );
}
// Functional part
$baseDir = SystemConfig::$installDir . DIRECTORY_SEPARATOR . $_GET["area"] . DIRECTORY_SEPARATOR . "components";
$componentsNames = array();
$dirPointer = dir( $baseDir );
while (false !== ($entry = $dirPointer->read()))
{
if( $entry == "." || $entry == ".." )
{
continue;
}
$componentXMLObject = $this->XMLDoc->createElement("areaComponent");
$componentXMLObject->setAttribute("name", $entry );
$componentXMLObject->setAttribute("editDate", filemtime( $baseDir . DIRECTORY_SEPARATOR . $entry ) );
$this->content->appendChild( $componentXMLObject );
}
$dirPointer->close();
return $this->setHeaderResult( Component::ERR_OK_NOCACHE );
}
public function onShowOne()
{
if(!isset($_GET["language"]) || !ereg("^[a-z]{2}-[A-Z]{2}$", $_GET["language"]))
{
return $this->setHeaderResult( Component::ERR_INVALID_LANGUAGE );
}
if(!isset($_GET["componentName"]) || !ereg("^[a-zA-Z0-9_]+$", $_GET["componentName"]))
{
return $this->setHeaderResult( Component::ERR_COMPONENT_NAME );
}
if( !isset($_GET["area"]) || !ereg("^[a-z_]+$", $_GET["area"]) )
{
return $this->setHeaderResult( Component::ERR_INVALID_AREA );
}
if( !file_exists( SystemConfig::$installDir . DIRECTORY_SEPARATOR . $_GET["area"] ) )
{
return $this->setHeaderResult( Component::ERR_NONEXISTENT_AREA );
}
if( !file_exists( SystemConfig::$installDir . DIRECTORY_SEPARATOR . $_GET["area"] . DIRECTORY_SEPARATOR . "components" . DIRECTORY_SEPARATOR . $_GET["componentName"] ) )
{
return $this->setHeaderResult( Component::ERR_NONEXISTENT_COMPONENT );
}
if( !file_exists( SystemConfig::$installDir . DIRECTORY_SEPARATOR . $_GET["area"] . DIRECTORY_SEPARATOR . "components" . DIRECTORY_SEPARATOR . $_GET["componentName"] . DIRECTORY_SEPARATOR . "translations" . DIRECTORY_SEPARATOR . $_GET["language"] . ".xml" ) )
{
return $this->setHeaderResult( Component::ERR_INVALID_LANGUAGE );
}
$this->content->appendChild(
$this->XMLDoc->createCDATASection(
file_get_contents( SystemConfig::$installDir . DIRECTORY_SEPARATOR . $_GET["area"] . DIRECTORY_SEPARATOR . "components" . DIRECTORY_SEPARATOR . $_GET["componentName"] . DIRECTORY_SEPARATOR . "translations" . DIRECTORY_SEPARATOR . $_GET["language"] . ".xml" )
)
);
return $this->setHeaderResult( Component::ERR_OK_NOCACHE );
}
public function onEdit()
{
if(!isset($_GET["language"]) || !ereg("^[a-z]{2}-[A-Z]{2}$", $_GET["language"]))
{
return $this->setHeaderResult( Component::ERR_INVALID_LANGUAGE );
}
if(!isset($_GET["componentName"]) || !ereg("^[a-zA-Z0-9_]+$", $_GET["componentName"]))
{
return $this->setHeaderResult( Component::ERR_COMPONENT_NAME );
}
if( !isset($_GET["area"]) || !ereg("^[a-z_]+$", $_GET["area"]) )
{
return $this->setHeaderResult( Component::ERR_INVALID_AREA );
}
if( !isset($_POST["content"]) || strlen($_POST["content"]) == 0 )
{
return $this->setHeaderResult( Component::ERR_NO_CONTENT );
}
if( !file_exists( SystemConfig::$installDir . DIRECTORY_SEPARATOR . $_GET["area"] ) )
{
return $this->setHeaderResult( Component::ERR_NONEXISTENT_AREA );
}
if( !file_exists( SystemConfig::$installDir . DIRECTORY_SEPARATOR . $_GET["area"] . DIRECTORY_SEPARATOR . "components" . DIRECTORY_SEPARATOR . $_GET["componentName"] ) )
{
return $this->setHeaderResult( Component::ERR_NONEXISTENT_COMPONENT );
}
if( !file_exists( SystemConfig::$installDir . DIRECTORY_SEPARATOR . $_GET["area"] . DIRECTORY_SEPARATOR . "components" . DIRECTORY_SEPARATOR . $_GET["componentName"] . DIRECTORY_SEPARATOR . "translations" . DIRECTORY_SEPARATOR . $_GET["language"] . ".xml" ) )
{
return $this->setHeaderResult( Component::ERR_INVALID_LANGUAGE );
}
$this->setCDATAValue( array(
"field" => "componentTranslationText",
"value" => $_POST["content"]
) );
// Check the data
libxml_use_internal_errors( true );
$doc = new DOMDocument('1.0', 'utf-8');
$doc->loadXML( $_POST["content"] );
$errors = libxml_get_errors();
if( !empty($errors) )
{
$error = $errors[ 0 ];
if( $error->level >= 3 )
{
$lines = explode("\r", $_POST["content"]);
$line = $lines[ $error->line - 1 ];
$this->setCDATAValue( array(
"field" => "errorMessage",
"value" => $error->message
) );
$this->setValue( array(
"field" => "errorLine",
"value" => $error->line
) );
$this->setCDATAValue( array(
"field" => "errorCode",
"value" => htmlentities($line)
) );
return $this->setHeaderResult( Component::ERR_INVALID_CONTENT );
}
}
$doc->save(
SystemConfig::$installDir . DIRECTORY_SEPARATOR . $_GET["area"] . DIRECTORY_SEPARATOR . "components" . DIRECTORY_SEPARATOR . $_GET["componentName"] . DIRECTORY_SEPARATOR . "translations" . DIRECTORY_SEPARATOR . $_GET["language"] . ".xml"
);
require_once( SystemConfiguration::$installPath . DIRECTORY_SEPARATOR . "includes/classes/class.componentManipulation.php");
ComponentManipulation::updateAll( array(
"area" => $_GET["area"],
"component" => $_GET["componentName"],
) );
// Page Redirections
if( SystemConfig::$env == SystemConfig::ENV_PAGE && isset($_POST["continueEdit"]) && $_POST["continueEdit"] == "0")
{
header( "location: index.php?page=" . $_GET["page"] . "&language=" . $_GET["language"]);
}
return $this->setHeaderResult( Component::ERR_OK_NOCACHE );
}
public function onInit()
{
if(!isset($_GET["language"]) || !ereg("^[a-z]{2}-[A-Z]{2}$", $_GET["language"]))
{
return $this->setHeaderResult( Component::ERR_INVALID_LANGUAGE );
}
return $this->setHeaderResult( Component::ERR_OK );
}
}
?>
|
gpl-2.0
|
acappellamaniac/eva_website
|
sites/all/modules/civicrm/CRM/Contact/Page/SavedSearch.php
|
5569
|
<?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$
*
*/
/**
* Main page for viewing all Saved searches.
*
*/
class CRM_Contact_Page_SavedSearch extends CRM_Core_Page {
/**
* The action links that we need to display for the browse screen.
*
* @var array
*/
static $_links = NULL;
/**
* Delete a saved search.
*
* @param int $id
* Id of saved search.
*
* @return void
*/
public function delete($id) {
// first delete the group associated with this saved search
$group = new CRM_Contact_DAO_Group();
$group->saved_search_id = $id;
if ($group->find(TRUE)) {
CRM_Contact_BAO_Group::discard($group->id);
}
$savedSearch = new CRM_Contact_DAO_SavedSearch();
$savedSearch->id = $id;
$savedSearch->is_active = 0;
$savedSearch->save();
}
/**
* Browse all saved searches.
*
* @return mixed
* content of the parents run method
*/
public function browse() {
$rows = array();
$savedSearch = new CRM_Contact_DAO_SavedSearch();
$savedSearch->is_active = 1;
$savedSearch->selectAdd();
$savedSearch->selectAdd('id, form_values');
$savedSearch->find();
$properties = array('id', 'name', 'description');
while ($savedSearch->fetch()) {
// get name and description from group object
$group = new CRM_Contact_DAO_Group();
$group->saved_search_id = $savedSearch->id;
if ($group->find(TRUE)) {
$permissions = CRM_Group_Page_Group::checkPermission($group->id, $group->title);
if (!CRM_Utils_System::isNull($permissions)) {
$row = array();
$row['name'] = $group->title;
$row['description'] = $group->description;
$row['id'] = $savedSearch->id;
$formValues = unserialize($savedSearch->form_values);
$query = new CRM_Contact_BAO_Query($formValues);
$row['query_detail'] = $query->qill();
$action = array_sum(array_keys(self::links()));
$action = $action & CRM_Core_Action::mask($permissions);
$row['action'] = CRM_Core_Action::formLink(
self::links(),
$action,
array('id' => $row['id']),
ts('more'),
FALSE,
'savedSearch.manage.action',
'SavedSearch',
$row['id']
);
$rows[] = $row;
}
}
}
$this->assign('rows', $rows);
return parent::run();
}
/**
* Run this page (figure out the action needed and perform it).
*
* @return void
*/
public function run() {
$action = CRM_Utils_Request::retrieve('action', 'String',
$this, FALSE, 'browse'
);
$this->assign('action', $action);
if ($action & CRM_Core_Action::DELETE) {
$id = CRM_Utils_Request::retrieve('id', 'Positive',
$this, TRUE
);
$this->delete($id);
}
$this->browse();
}
/**
* Get action Links.
*
* @return array
* (reference) of action links
*/
public static function &links() {
if (!(self::$_links)) {
$deleteExtra = ts('Do you really want to remove this Smart Group?');
self::$_links = array(
CRM_Core_Action::VIEW => array(
'name' => ts('Search'),
'url' => 'civicrm/contact/search/advanced',
'qs' => 'reset=1&force=1&ssID=%%id%%',
'title' => ts('Search'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Delete'),
'url' => 'civicrm/contact/search/saved',
'qs' => 'action=delete&id=%%id%%',
'extra' => 'onclick="return confirm(\'' . $deleteExtra . '\');"',
),
);
}
return self::$_links;
}
}
|
gpl-2.0
|
ugosan/rox-legacy
|
src/org/ugosan/rox/grafo/Vertice.java
|
8521
|
/*
Rox - Teoria dos Grafos
Copyright (C) 2003 Ugo Braga Sangiorgi
A licensa completa se encontra no diretório-raiz em gpl.txt
*/
package org.ugosan.rox.grafo;
import java.io.*;
import java.lang.*;
import javax.imageio.*;
import org.ugosan.rox.*;
import org.ugosan.rox.dialogs.ImageCache;
import java.awt.image.*;
import java.awt.*;
import java.util.*;
public class Vertice implements
Serializable{
int posX;
int posY;
int centroX;
int centroY;
int nome;
String rotulo;
String caminho_imagem;
int altura_imagem;
int largura_imagem;
private Properties propriedades = new Properties();
private boolean nome_interno = true;
private boolean selecionado = false;
private Color cor;
private int grau;
private int ordem;
/** Cria um vértice na posição especificada
* Obs: passe o vértice criado como parametro em <code> grafo.addVertice(Vertice) </code>
* @param _x a coordenada X
* @param _y a coordenada Y
**/
public Vertice(int _x, int _y){
this.posX = _x;
this.posY = _y;
this.setImagem(System.getProperty("user.dir")+File.separator+"vertices"+File.separator+"vertice.gif");
}
/** Cria um vértice na posição especificada com a imagem especificada no caminho
* Obs: passe o vértice criado como parametro em <code> grafo.addVertice(Vertice) </code>
* @param _x a coordenada X
* _y a coordenada Y
* caminho: o caminho absoluto da imagem
**/
public Vertice(int _x, int _y, String caminho){
this.posX = _x;
this.posY = _y;
this.setImagem(caminho);
}
/** Retorna o nome do Vertice (relativo a sua ordem de inserção na lista de vértices).
* <p> IMPORTANTE: <br>
* Caso você deseje o rótulo do vértice (que pode ser diferente do nome armazenado internamente) use getRotulo();
* </p>
**/
public int getNome(){
return(nome);
}
/** Atribui um rotulo qualquer ao vértice (diferente do nome, que é relativo a sua ordem de inserção na lista de vértices)
* @param rotulo uma nova string como rótulo
**/
public void setRotulo(String rotulo){
this.rotulo = rotulo;
}
/** Retorna o rótulo do Vertice (diferente do nome, relativo a sua ordem de inserção na lista de vértices).
* <p> IMPORTANTE: <br>
* Caso você deseje o nome do vértice (que pode ser diferente do rótulo) use getNome();
* O nome é relativo ao valor de entrada na lista de vértices, um vértice que possui nome 5, tem a entrada
* igual a nome - 1, ou seja, 4. O rótulo que é atribuído no momento da criação é igual ao nome.
* </p>
**/
public String getRotulo(){
return(rotulo);
}
/** Retorna a posicao X relativa ao JPanel RoxPanel
**/
public int getPosX(){
return(posX);
}
/** Retorna a posicao Y relativa ao JPanel RoxPanel
**/
public int getPosY(){
return(posY);
}
/** Realoca a posicao X,Y relativa ao JPanel RoxPanel
@param x a coordenada X
@param y a coordenada Y
**/
public void setPosXY(int x, int y){
this.setPosX(x);
this.setPosY(y);
}
/** Realoca a posicao X relativa ao JPanel RoxPanel
@param x a coordenada x
**/
public void setPosX(int x){
this.posX = x;
this.centroX = this.posX + largura_imagem/2;
}
/** Realoca a posicao Y relativa ao JPanel RoxPanel
@param y a coordenada Y
**/
public void setPosY(int y){
this.posY = y;
this.centroY = this.posY + altura_imagem/2;
}
/** Retorna a imagem relativa ao Vértice
**/
public BufferedImage getImagem(){
BufferedImage imagem = null;
imagem = ImageCache.getInstance().getImagem(caminho_imagem);
this.altura_imagem = imagem.getHeight();
this.largura_imagem = imagem.getWidth();
return(imagem);
}
/** Lê a imagem especificada no caminho e atribui ao Vértice
* @param caminho o caminho da imagem
**/
public void setImagem(String caminho){
BufferedImage imagem;
imagem = ImageCache.getInstance().getImagem(caminho);
this.altura_imagem = imagem.getHeight();
this.largura_imagem = imagem.getWidth();
this.centroX = this.posX + largura_imagem/2;
this.centroY = this.posY + altura_imagem/2;
this.caminho_imagem = caminho;
}
/** verifica se o nome é interno ao vértice (o nome aparece dentro do vértice)
**/
public boolean isNome_interno()
{
return nome_interno;
}
/** Altera a forma como o noem aparece, dentro do vértice ou em um label externo
* @param valor true=interno ao vértice false=externo ao vértice
**/
public void setNome_interno(boolean valor)
{
nome_interno = valor;
}
public int getCentroX()
{
return centroX;
}
public void setCentroX(int value)
{
centroX = value;
}
public int getCentroY()
{
return centroY;
}
public void setCentroY(int value)
{
centroY = value;
}
public int getAltura_imagem()
{
return altura_imagem;
}
public void setAltura_imagem(int value)
{
altura_imagem = value;
}
public int getLargura_imagem()
{
return largura_imagem;
}
public void setLargura_imagem(int value)
{
largura_imagem = value;
}
public boolean isSelecionado()
{
return selecionado;
}
public void setSelecionado(boolean value)
{
selecionado = value;
}
/**
* @return a Cor deste Vértice
**/
public Color getCor()
{
return(this.cor);
}
/**Atribui uma cor ao Vértice
* @param c uma Cor
**/
public void setCor(Color c)
{
this.cor = c;
}
/**Atribui uma cor ao Vértice
*@param R quantidade de vermelho (entre 0 e 255)
*@param G quantidade de verde (entre 0 e 255)
*@param B quantidade de azul (entre 0 e 255)
**/
public void setCor(int R, int G, int B){
this.cor = new Color(R,G,B);
}
public java.lang.String getCaminho_imagem()
{
return caminho_imagem;
}
/*
public int getGrau()
{
//return Rox.getInstance().getGrafo().getAdjacencias(this).size();
return grau;
}
public void setGrau(int grau){
this.grau = grau;
}
public int getOrdem()
{
return ordem;
}
public void setOrdem(int value)
{
ordem = value;
}
*/
/**Retorna as propriedades do Vertice
**/
public Properties getPropriedades(){
return this.propriedades;
}
/** Retorna uma propriedade atraves de uma chave.
* <p>
* As propriedades são inseridas como: <br>
* <code>
* Vertice.putPropriedade(String chave, String valor); <br>
* ex:
* Vertice v; <br>
* v.putPropriedade("grau","2"); <br>
* </code>
*
* </p>
* <p>
* As propriedades são buscadas como: <br>
* <code>
* Vertice.getPropriedade(String chave); <br>
* ex:
* Vertice v; <br>
* String p = v.getPropriedade("grau"); <br>
* int grau = Integer.getInteger(p).intValue();
* </code>
*
* </p>
* @param chave: a chave da propriedade
**/
public String getPropriedade(String chave){
return propriedades.getProperty(chave);
}
/** Insere uma propriedade atraves de uma chave.
* <p>
* As propriedades são inseridas como: <br>
* <code>
* Vertice.putPropriedade(String chave, String valor); <br>
* ex:<br>
* Vertice v; <br>
* v.putPropriedade("grau","2"); <br>
* </code>
*
* </p>
* <p>
* As propriedades são buscadas como: <br>
* <code>
* Vertice.getPropriedade(String chave); <br>
* ex:<br>
* Vertice v; <br>
* String p = v.getPropriedade("grau"); <br>
* int grau = Integer.getInteger(p).intValue();
* </code>
*
* </p>
* @param chave: a chave da propriedade
* @param valor: a propriedade em si
**/
public void putPropriedade(String chave, String valor){
propriedades.setProperty(chave,valor);
}
}
|
gpl-2.0
|
52North/SES
|
52n-ses-eml-001/src/main/java/org/n52/ses/eml/v001/filter/spatial/BeyondFilter.java
|
2002
|
/**
* Copyright (C) 2008 - 2014 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* icense version 2 and the aforementioned licenses.
*
* 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.
*/
package org.n52.ses.eml.v001.filter.spatial;
import net.opengis.fes.x20.DistanceBufferType;
/**
*
* @author Matthes Rieke <m.rieke@uni-muenster.de>
*
*/
public class BeyondFilter extends ADistanceBufferFilter {
/**
*
* Constructor
*
* @param dbOp FES distance buffer
*/
public BeyondFilter(DistanceBufferType dbOp) {
super(dbOp);
}
@Override
public String createExpressionString(boolean complexPatternGuard) {
//TODO first buffer then do a not(intersect)
return createExpressionForDistanceFilter("beyond");
}
@Override
public void setUsedProperty(String nodeValue) {
/*empty*/
}
}
|
gpl-2.0
|
EmperorArthur/VBA-M
|
src/gba/RTC.cpp
|
7894
|
#include "../System.h"
#include "GBA.h"
#include "Globals.h"
#include "../common/Port.h"
#include "../Util.h"
#include "../NLS.h"
#include <time.h>
#include <memory.h>
#include <string.h>
enum RTCSTATE
{
IDLE = 0,
COMMAND,
DATA,
READDATA
};
typedef struct {
u8 byte0;
u8 byte1;
u8 byte2;
u8 command;
int dataLen;
int bits;
RTCSTATE state;
u8 data[12];
// reserved variables for future
u8 reserved[12];
bool reserved2;
u32 reserved3;
} RTCCLOCKDATA;
static RTCCLOCKDATA rtcClockData;
static bool rtcEnabled = false;
void rtcEnable(bool e)
{
rtcEnabled = e;
}
bool rtcIsEnabled()
{
return rtcEnabled;
}
u16 rtcRead(u32 address)
{
if(rtcEnabled) {
switch(address){
case 0x80000c8:
return rtcClockData.byte2;
break;
case 0x80000c6:
return rtcClockData.byte1;
break;
case 0x80000c4:
// Boktai Solar Sensor
if (rtcClockData.byte1 == 7) {
if (rtcClockData.reserved[11] >= systemGetSensorDarkness()) {
rtcClockData.reserved[10] = 0;
rtcClockData.reserved[11] = 0;
return 8;
}
else {
return 0;
}
}
// WarioWare Twisted Tilt Sensor
else if (rtcClockData.byte1 == 0x0b) {
//sprintf(DebugStr, "Reading Twisted Sensor bit %d", rtcClockData.reserved[11]);
u16 v = systemGetSensorZ();
return ((v >> rtcClockData.reserved[11]) & 1) << 2;
}
// Real Time Clock
else {
//sprintf(DebugStr, "Reading RTC %02x, %02x, %02x", rtcClockData.byte0, rtcClockData.byte1, rtcClockData.byte2);
return rtcClockData.byte0;
}
break;
}
}
return READ16LE((&rom[address & 0x1FFFFFE]));
}
static u8 toBCD(u8 value)
{
value = value % 100;
int l = value % 10;
int h = value / 10;
return h * 16 + l;
}
bool rtcWrite(u32 address, u16 value)
{
if(!rtcEnabled)
return false;
if(address == 0x80000c8) {
rtcClockData.byte2 = (u8)value; // bit 0 = enable reading from 0x80000c4 c6 and c8
}
else if (address == 0x80000c6) {
rtcClockData.byte1 = (u8)value; // 0=read/1=write (for each of 4 low bits)
// rumble is off when not writing to that pin
if (/*rtcWarioRumbleEnabled &&*/ !(value & 8)) systemCartridgeRumble(false);
}
else if (address == 0x80000c4) { // 4 bits of I/O Port Data (upper bits not used)
// WarioWare Twisted rumble
if (/*rtcWarioRumbleEnabled &&*/ (rtcClockData.byte1 & 8)) {
systemCartridgeRumble(value & 8);
}
// Boktai solar sensor
if (rtcClockData.byte1 == 7) {
if (value & 2) {
// reset counter to 0
rtcClockData.reserved[11] = 0;
rtcClockData.reserved[10] = 0;
}
if ((value & 1) && (!(rtcClockData.reserved[10] & 1))) {
// increase counter, ready to do another read
if (rtcClockData.reserved[11]<255) rtcClockData.reserved[11]++;
}
rtcClockData.reserved[10] = value & rtcClockData.byte1;
}
// WarioWare Twisted rotation sensor
if (rtcClockData.byte1 == 0xb) {
if (value & 2) {
// clock goes high in preperation for reading a bit
rtcClockData.reserved[11]--;
}
if (value & 1) {
// start ADC conversion
rtcClockData.reserved[11] = 15;
}
rtcClockData.byte0 = value & rtcClockData.byte1;
// Real Time Clock
}
/**/
if(rtcClockData.byte2 & 1) {
if(rtcClockData.state == IDLE && rtcClockData.byte0 == 1 && value == 5) {
rtcClockData.state = COMMAND;
rtcClockData.bits = 0;
rtcClockData.command = 0;
} else if(!(rtcClockData.byte0 & 1) && (value & 1)) { // bit transfer
rtcClockData.byte0 = (u8)value;
switch(rtcClockData.state) {
case COMMAND:
rtcClockData.command |= ((value & 2) >> 1) << (7-rtcClockData.bits);
rtcClockData.bits++;
if(rtcClockData.bits == 8) {
rtcClockData.bits = 0;
switch(rtcClockData.command) {
case 0x60:
// not sure what this command does but it doesn't take parameters
// maybe it is a reset or stop
rtcClockData.state = IDLE;
rtcClockData.bits = 0;
break;
case 0x62:
// this sets the control state but not sure what those values are
rtcClockData.state = READDATA;
rtcClockData.dataLen = 1;
break;
case 0x63:
rtcClockData.dataLen = 1;
rtcClockData.data[0] = 0x40;
rtcClockData.state = DATA;
break;
case 0x64:
break;
case 0x65:
{
struct tm *newtime;
time_t long_time;
time( &long_time ); /* Get time as long integer. */
newtime = localtime( &long_time ); /* Convert to local time. */
rtcClockData.dataLen = 7;
rtcClockData.data[0] = toBCD(newtime->tm_year);
rtcClockData.data[1] = toBCD(newtime->tm_mon+1);
rtcClockData.data[2] = toBCD(newtime->tm_mday);
rtcClockData.data[3] = toBCD(newtime->tm_wday);
rtcClockData.data[4] = toBCD(newtime->tm_hour);
rtcClockData.data[5] = toBCD(newtime->tm_min);
rtcClockData.data[6] = toBCD(newtime->tm_sec);
rtcClockData.state = DATA;
}
break;
case 0x67:
{
struct tm *newtime;
time_t long_time;
time( &long_time ); /* Get time as long integer. */
newtime = localtime( &long_time ); /* Convert to local time. */
rtcClockData.dataLen = 3;
rtcClockData.data[0] = toBCD(newtime->tm_hour);
rtcClockData.data[1] = toBCD(newtime->tm_min);
rtcClockData.data[2] = toBCD(newtime->tm_sec);
rtcClockData.state = DATA;
}
break;
default:
systemMessage(0, N_("Unknown RTC command %02x"), rtcClockData.command);
rtcClockData.state = IDLE;
break;
}
}
break;
case DATA:
if(rtcClockData.byte1 & 2) {
} else {
rtcClockData.byte0 = (rtcClockData.byte0 & ~2) |
((rtcClockData.data[rtcClockData.bits >> 3] >>
(rtcClockData.bits & 7)) & 1)*2;
rtcClockData.bits++;
if(rtcClockData.bits == 8*rtcClockData.dataLen) {
rtcClockData.bits = 0;
rtcClockData.state = IDLE;
}
}
break;
case READDATA:
if(!(rtcClockData.byte1 & 2)) {
} else {
rtcClockData.data[rtcClockData.bits >> 3] =
(rtcClockData.data[rtcClockData.bits >> 3] >> 1) |
((value << 6) & 128);
rtcClockData.bits++;
if(rtcClockData.bits == 8*rtcClockData.dataLen) {
rtcClockData.bits = 0;
rtcClockData.state = IDLE;
}
}
break;
default:
break;
}
} else
rtcClockData.byte0 = (u8)value;
}
}
return true;
}
void rtcReset()
{
memset(&rtcClockData, 0, sizeof(rtcClockData));
rtcClockData.byte0 = 0;
rtcClockData.byte1 = 0;
rtcClockData.byte2 = 0;
rtcClockData.command = 0;
rtcClockData.dataLen = 0;
rtcClockData.bits = 0;
rtcClockData.state = IDLE;
rtcClockData.reserved[11] = 0;
}
#ifdef __LIBRETRO__
void rtcSaveGame(u8 *&data)
{
utilWriteMem(data, &rtcClockData, sizeof(rtcClockData));
}
void rtcReadGame(const u8 *&data)
{
utilReadMem(&rtcClockData, data, sizeof(rtcClockData));
}
#else
void rtcSaveGame(gzFile gzFile)
{
utilGzWrite(gzFile, &rtcClockData, sizeof(rtcClockData));
}
void rtcReadGame(gzFile gzFile)
{
utilGzRead(gzFile, &rtcClockData, sizeof(rtcClockData));
}
#endif
|
gpl-2.0
|
GeoYS/ldgrowth
|
src/com/aqua/ludum/growth/map/ComputerPlant.java
|
503
|
package com.aqua.ludum.growth.map;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
/**
*
* @author Duane Byer
*/
public class ComputerPlant extends Plant {
public ComputerPlant(Terrain terrain, Point position) {
super(terrain, position);
}
@Override
public void control(float delta) {
}
@Override
public void render(SpriteBatch batch) {
renderPlant(batch, Color.RED);
}
}
|
gpl-2.0
|
zcaliptium/Serious-Engine
|
Sources/Entities/Common/PathFinding.cpp
|
8743
|
/* Copyright (c) 2002-2012 Croteam Ltd.
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 "StdH.h"
#include "Entities/Common/PathFinding.h"
#include "Entities/NavigationMarker.h"
#define PRINTOUT(_dummy)
//#define PRINTOUT(something) something
// open and closed lists of nodes
static CListHead _lhOpen;
static CListHead _lhClosed;
FLOAT NodeDistance(CPathNode *ppn0, CPathNode *ppn1)
{
return (
ppn0->pn_pnmMarker->GetPlacement().pl_PositionVector -
ppn1->pn_pnmMarker->GetPlacement().pl_PositionVector).Length();
}
CPathNode::CPathNode(class CNavigationMarker *penMarker)
{
pn_pnmMarker = penMarker;
pn_ppnParent = NULL;
pn_fG = 0.0f;
pn_fH = 0.0f;
pn_fF = 0.0f;
}
CPathNode::~CPathNode(void)
{
// detach from marker when deleting
ASSERT(pn_pnmMarker!=NULL);
pn_pnmMarker->m_ppnNode = NULL;
}
// get name of this node
const CTString &CPathNode::GetName(void)
{
static CTString strNone="<none>";
if (this==NULL || pn_pnmMarker==NULL) {
return strNone;
} else {
return pn_pnmMarker->GetName();
}
}
// get link with given index or null if no more (for iteration along the graph)
CPathNode *CPathNode::GetLink(INDEX i)
{
if (this==NULL || pn_pnmMarker==NULL) {
ASSERT(FALSE);
return NULL;
}
CNavigationMarker *pnm = pn_pnmMarker->GetLink(i);
if (pnm==NULL) {
return NULL;
}
return pnm->GetPathNode();
}
// add given node to open list, sorting best first
static void SortIntoOpenList(CPathNode *ppnLink)
{
// start at head of the open list
LISTITER(CPathNode, pn_lnInOpen) itpn(_lhOpen);
// while the given node is further than the one in list
while(ppnLink->pn_fF>itpn->pn_fF && !itpn.IsPastEnd()) {
// move to next node
itpn.MoveToNext();
}
// if past the end of list
if (itpn.IsPastEnd()) {
// add to the end of list
_lhOpen.AddTail(ppnLink->pn_lnInOpen);
// if not past end of list
} else {
// add before current node
itpn.InsertBeforeCurrent(ppnLink->pn_lnInOpen);
}
}
// find shortest path from one marker to another
static BOOL FindPath(CNavigationMarker *pnmSrc, CNavigationMarker *pnmDst)
{
ASSERT(pnmSrc!=pnmDst);
CPathNode *ppnSrc = pnmSrc->GetPathNode();
CPathNode *ppnDst = pnmDst->GetPathNode();
PRINTOUT(CPrintF("--------------------\n"));
PRINTOUT(CPrintF("FindPath(%s, %s)\n", ppnSrc->GetName(), ppnDst->GetName()));
// start with empty open and closed lists
ASSERT(_lhOpen.IsEmpty());
ASSERT(_lhClosed.IsEmpty());
// add the start node to open list
ppnSrc->pn_fG = 0.0f;
ppnSrc->pn_fH = NodeDistance(ppnSrc, ppnDst);
ppnSrc->pn_fF = ppnSrc->pn_fG +ppnSrc->pn_fH;
_lhOpen.AddTail(ppnSrc->pn_lnInOpen);
PRINTOUT(CPrintF("StartState: %s\n", ppnSrc->GetName()));
// while the open list is not empty
while (!_lhOpen.IsEmpty()) {
// get the first node from open list (that is, the one with lowest F)
CPathNode *ppnNode = LIST_HEAD(_lhOpen, CPathNode, pn_lnInOpen);
ppnNode->pn_lnInOpen.Remove();
_lhClosed.AddTail(ppnNode->pn_lnInClosed);
PRINTOUT(CPrintF("Node: %s - moved from OPEN to CLOSED\n", ppnNode->GetName()));
// if this is the goal
if (ppnNode==ppnDst) {
PRINTOUT(CPrintF("PATH FOUND!\n"));
// the path is found
return TRUE;
}
// for each link of current node
CPathNode *ppnLink = NULL;
for(INDEX i=0; (ppnLink=ppnNode->GetLink(i))!=NULL; i++) {
PRINTOUT(CPrintF(" Link %d: %s\n", i, ppnLink->GetName()));
// get cost to get to this node if coming from current node
FLOAT fNewG = ppnLink->pn_fG+NodeDistance(ppnNode, ppnLink);
// if a shorter path already exists
if ((ppnLink->pn_lnInOpen.IsLinked() || ppnLink->pn_lnInClosed.IsLinked()) && fNewG>=ppnLink->pn_fG) {
PRINTOUT(CPrintF(" shorter path exists through: %s\n", ppnLink->pn_ppnParent->GetName()));
// skip this link
continue;
}
// remember this path
ppnLink->pn_ppnParent = ppnNode;
ppnLink->pn_fG = fNewG;
ppnLink->pn_fH = NodeDistance(ppnLink, ppnDst);
ppnLink->pn_fF = ppnLink->pn_fG + ppnLink->pn_fH;
// remove from closed list, if in it
if (ppnLink->pn_lnInClosed.IsLinked()) {
ppnLink->pn_lnInClosed.Remove();
PRINTOUT(CPrintF(" %s removed from CLOSED\n", ppnLink->GetName()));
}
// add to open if not in it
if (!ppnLink->pn_lnInOpen.IsLinked()) {
SortIntoOpenList(ppnLink);
PRINTOUT(CPrintF(" %s added to OPEN\n", ppnLink->GetName()));
}
}
}
// if we get here, there is no path
PRINTOUT(CPrintF("PATH NOT FOUND!\n"));
return FALSE;
}
// clear all temporary structures used for path finding
static void ClearPath(CEntity *penThis)
{
{FORDELETELIST(CPathNode, pn_lnInOpen, _lhOpen, itpn) {
delete &itpn.Current();
}}
{FORDELETELIST(CPathNode, pn_lnInClosed, _lhClosed, itpn) {
delete &itpn.Current();
}}
#ifndef NDEBUG
// for each navigation marker in the world
{FOREACHINDYNAMICCONTAINER(penThis->en_pwoWorld->wo_cenEntities, CEntity, iten) {
if (!IsOfClass(iten, "NavigationMarker")) {
continue;
}
CNavigationMarker &nm = (CNavigationMarker&)*iten;
ASSERT(nm.m_ppnNode==NULL);
}}
#endif
}
// find marker closest to a given position
static void FindClosestMarker(
CEntity *penThis, const FLOAT3D &vSrc, CEntity *&penMarker, FLOAT3D &vPath)
{
CNavigationMarker *pnmMin = NULL;
FLOAT fMinDist = UpperLimit(0.0f);
// for each sector this entity is in
{FOREACHSRCOFDST(penThis->en_rdSectors, CBrushSector, bsc_rsEntities, pbsc)
// for each navigation marker in that sector
{FOREACHDSTOFSRC(pbsc->bsc_rsEntities, CEntity, en_rdSectors, pen)
if (!IsOfClass(pen, "NavigationMarker")) {
continue;
}
CNavigationMarker &nm = (CNavigationMarker&)*pen;
// get distance from source
FLOAT fDist = (vSrc-nm.GetPlacement().pl_PositionVector).Length();
// if closer than best found
if(fDist<fMinDist) {
// remember it
fMinDist = fDist;
pnmMin = &nm;
}
ENDFOR}
ENDFOR}
// if none found
if (pnmMin==NULL) {
// fail
vPath = vSrc;
penMarker = NULL;
return;
}
// return position
vPath = pnmMin->GetPlacement().pl_PositionVector;
penMarker = pnmMin;
}
// find first marker for path navigation
void PATH_FindFirstMarker(CEntity *penThis, const FLOAT3D &vSrc, const FLOAT3D &vDst, CEntity *&penMarker, FLOAT3D &vPath)
{
// find closest markers to source and destination positions
CNavigationMarker *pnmSrc;
FLOAT3D vSrcPath;
FindClosestMarker(penThis, vSrc, (CEntity*&)pnmSrc, vSrcPath);
CNavigationMarker *pnmDst;
FLOAT3D vDstPath;
FindClosestMarker(penThis, vDst, (CEntity*&)pnmDst, vDstPath);
// if at least one is not found, or if they are same
if (pnmSrc==NULL || pnmDst==NULL || pnmSrc==pnmDst) {
// fail
penMarker = NULL;
vPath = vSrc;
return;
}
// go to the source marker position
vPath = vSrcPath;
penMarker = pnmSrc;
}
// find next marker for path navigation
void PATH_FindNextMarker(CEntity *penThis, const FLOAT3D &vSrc, const FLOAT3D &vDst, CEntity *&penMarker, FLOAT3D &vPath)
{
// find closest marker to destination position
CNavigationMarker *pnmDst;
FLOAT3D vDstPath;
FindClosestMarker(penThis, vDst, (CEntity*&)pnmDst, vDstPath);
// if at not found, or if same as current
if (pnmDst==NULL || penMarker==pnmDst) {
// fail
penMarker = NULL;
vPath = vSrc;
return;
}
// try to find shortest path to the destination
BOOL bFound = FindPath((CNavigationMarker*)penMarker, pnmDst);
// if not found
if (!bFound) {
// just clean up and fail
delete pnmDst->GetPathNode();
ClearPath(penThis);
penMarker = NULL;
vPath = vSrc;
return;
}
// find the first marker position after current
CPathNode *ppn = pnmDst->GetPathNode();
while (ppn->pn_ppnParent!=NULL && ppn->pn_ppnParent->pn_pnmMarker!=penMarker) {
ppn = ppn->pn_ppnParent;
}
penMarker = ppn->pn_pnmMarker;
// go there
vPath = penMarker->GetPlacement().pl_PositionVector;
// clean up
ClearPath(penThis);
}
|
gpl-2.0
|
shaise/FreeCAD_FastenersWB
|
fnwb_locator.py
|
1007
|
# -*- coding: utf-8 -*-
###################################################################################
#
# fnwb_locator.py
#
# Copyright 2015 Shai Seger <shaise at gmail dot com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
###################################################################################
|
gpl-2.0
|
emeraldstudio/outlets
|
templates/outletcolombia/html/com_content/category/places.php
|
4522
|
<?php
// no direct access
defined('_JEXEC') or die;
JHtml::addIncludePath(JPATH_COMPONENT.'/helpers');
$get = JRequest::get();
$children = $this->category->getChildren();
$doc = JFactory::getDocument();
$template = JURI::base() . "templates/feriaburo";
$category = $this->category;
$seccion = $get['seccion'];
if(empty($seccion)){
$seccion = 'restaurantes';
}
?>
<?php if (!empty($children)) { ?>
<section class="about-page categories">
<div class="content-inner">
<div class="container">
<div class="row-fluid">
<div class="content-area">
<div class="list-categorie-box">
<div class="heading">
<h3>Obtén aquí tus descuentos <span class="location"></span></h3>
<!-- <a href="#" class="change">[change city]</a> --></div>
<!--List Tabs Start-->
<div class="list-categorie-tab">
<div id="content_1" class="content-list-categorie">
<ul class="nav nav-tabs list-categorie-nav" id="myTab">
<? foreach ($children as $key => $value) { ?>
<?
$icons = ($value->icons)?$value->icons:'fa-shopping-cart';
if($value->alias == $seccion){
$active = 'active';
}else{
$active = '';
}
?>
<li class="<?= $active ?>"><a href="#<?= $value->alias?>"><i class="fa <?= $icons?>"></i><?= $value->title?><span> >> </span></a></li>
<? } ?>
</ul>
</div>
<div class="tab-content list-tab-content">
<? foreach ($children as $key => $value) { ?>
<?
$params['count'] = 999;
$params['catid'] = array($value->id);
$articles = ContentHelperQuery::getList($params);
if($value->alias == $seccion){
$active = 'active';
}else{
$active = '';
}
?>
<div class="tab-pane <?= $active?>" id="<?= $value->alias?>">
<div class="text">
<h4><?= $value->title?></h4>
<ul id="places">
<? foreach ($articles as $key => $item) { ?>
<?
$images = json_decode($item->images);
$image_intro = ($images->image_intro)?$images->image_intro:'http://placehold.it/180x148';
$link = $item->link;
?>
<li>
<div class="frame">
<a href="<?= $link ?>">
<img src="<?= $image_intro ?>" alt="img">
</a>
</div>
<div class="tab-text-box">
<strong class="title"><?= $item->title?></strong>
<div class="text-row">
<?= JHtml::_('string.truncate', strip_tags($item->introtext), 200) ?>
</div>
<div class="text-row">
<p> <a href="<?= $link ?>">Mas información</a> </p>
</div>
</li>
<? } ?>
</ul>
</div>
</div>
<? } ?>
</div>
</div>
<!--List Tabs End-->
</div>
</div>
</div>
</div>
</div>
</section>
<? } ?>
|
gpl-2.0
|
reactormonk/nmm
|
Oblivion/OblivionGameMode.cs
|
3861
|
using System.IO;
using Nexus.Client.Games.Gamebryo;
using Nexus.Client.Games.Oblivion.Tools;
using Nexus.Client.Games.Tools;
using Nexus.Client.Util;
namespace Nexus.Client.Games.Oblivion
{
/// <summary>
/// Provides information required for the programme to manage Oblivion plugins and mods.
/// </summary>
public class OblivionGameMode : GamebryoGameModeBase
{
private static string[] SCRIPT_EXTENDER_EXECUTABLES = { "obse_loader.exe" };
private OblivionGameModeDescriptor m_gmdGameModeInfo = null;
private OblivionLauncher m_glnGameLauncher = null;
private OblivionToolLauncher m_gtlToolLauncher = null;
#region Properties
/// <summary>
/// Gets the list of possible script extender executable files for the game.
/// </summary>
/// <value>The list of possible script extender executable files for the game.</value>
protected override string[] ScriptExtenderExecutables
{
get
{
return SCRIPT_EXTENDER_EXECUTABLES;
}
}
/// <summary>
/// Gets the path to the per user Fallout 3 data.
/// </summary>
/// <value>The path to the per user Fallout 3 data.</value>
public override string UserGameDataPath
{
get
{
return Path.Combine(EnvironmentInfo.PersonalDataFolderPath, "My games\\Oblivion");
}
}
/// <summary>
/// Gets the game launcher for the game mode.
/// </summary>
/// <value>The game launcher for the game mode.</value>
public override IGameLauncher GameLauncher
{
get
{
if (m_glnGameLauncher == null)
m_glnGameLauncher = new OblivionLauncher(this, EnvironmentInfo);
return m_glnGameLauncher;
}
}
/// <summary>
/// Gets the tool launcher for the game mode.
/// </summary>
/// <value>The tool launcher for the game mode.</value>
public override IToolLauncher GameToolLauncher
{
get
{
if (m_gtlToolLauncher == null)
m_gtlToolLauncher = new OblivionToolLauncher(this, EnvironmentInfo);
return m_gtlToolLauncher;
}
}
/// <summary>
/// Gets the default game categories.
/// </summary>
/// <value>The default game categories stored in the resource file.</value>
public override string GameDefaultCategories
{
get
{
return Properties.Resources.Categories;
}
}
#endregion
#region Constructors
/// <summary>
/// A simple constructor that initializes the object with the given values.
/// </summary>
/// <param name="p_futFileUtility">The file utility class to be used by the game mode.</param>
/// <param name="p_eifEnvironmentInfo">The application's environment info.</param>
public OblivionGameMode(IEnvironmentInfo p_eifEnvironmentInfo, FileUtil p_futFileUtility)
: base(p_eifEnvironmentInfo, p_futFileUtility)
{
}
#endregion
#region Initialization
/// <summary>
/// Instantiates the container to use to store the list of settings files.
/// </summary>
/// <returns>The container to use to store the list of settings files.</returns>
protected override GamebryoSettingsFiles CreateSettingsFileContainer()
{
return new GamebryoSettingsFiles();
}
/// <summary>
/// Adds the settings files to the game mode's list.
/// </summary>
protected override void SetupSettingsFiles()
{
base.SetupSettingsFiles();
SettingsFiles.IniPath = Path.Combine(UserGameDataPath, "oblivion.ini");
}
#endregion
/// <summary>
/// Creates a game mode descriptor for the current game mode.
/// </summary>
/// <returns>A game mode descriptor for the current game mode.</returns>
protected override IGameModeDescriptor CreateGameModeDescriptor()
{
if (m_gmdGameModeInfo == null)
m_gmdGameModeInfo = new OblivionGameModeDescriptor(EnvironmentInfo);
return m_gmdGameModeInfo;
}
}
}
|
gpl-2.0
|
tempbottle/pop-cpp
|
lib/core/memspool.cc
|
821
|
/**
* File : memspool.cc
* Author : Tuan Anh Nguyen
* Description : Implementation of the memory management
* Creation date : -
*
* Modifications :
* Authors Date Comment
*/
#include <stdio.h>
#include <stdlib.h>
#include "pop_memspool.h"
#include "pop_exception.h"
pop_memspool::pop_memspool() {
}
pop_memspool::~pop_memspool() {
Free();
}
void* pop_memspool::Alloc(int sz) {
if (sz <= 0) {
return nullptr;
}
void* data;
if ((data = malloc(sz)) == nullptr) {
pop_exception::pop_throw(errno);
}
memtemp.push_back(data);
return data;
}
void pop_memspool::Managed(void* data) {
if (data) {
memtemp.push_back(data);
}
}
void pop_memspool::Free() {
for (auto& tmp : memtemp) {
free(tmp);
}
memtemp.clear();
}
|
gpl-2.0
|
rex-xxx/mt6572_x201
|
libcore/luni/src/main/java/java/text/SimpleDateFormat.java
|
55753
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.text;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import libcore.icu.LocaleData;
import libcore.icu.TimeZones;
/**
* A concrete class for formatting and parsing dates in a locale-sensitive
* manner. Formatting turns a {@link Date} into a {@link String}, and parsing turns a
* {@code String} into a {@code Date}.
*
* <h4>Time Pattern Syntax</h4>
* <p>You can supply a pattern describing what strings are produced/accepted, but almost all
* callers should use {@link DateFormat#getDateInstance}, {@link DateFormat#getDateTimeInstance},
* or {@link DateFormat#getTimeInstance} to get a ready-made instance suitable for the user's
* locale.
*
* <p>The main reason you'd create an instance this class directly is because you need to
* format/parse a specific machine-readable format, in which case you almost certainly want
* to explicitly ask for {@link Locale#US} to ensure that you get ASCII digits (rather than,
* say, Arabic digits).
* (See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".)
* The most useful non-localized pattern is {@code "yyyy-MM-dd HH:mm:ss.SSSZ"}, which corresponds
* to the ISO 8601 international standard date format.
*
* <p>To specify the time format, use a <i>time pattern</i> string. In this
* string, any character from {@code 'A'} to {@code 'Z'} or {@code 'a'} to {@code 'z'} is
* treated specially. All other characters are passed through verbatim. The interpretation of each
* of the ASCII letters is given in the table below. ASCII letters not appearing in the table are
* reserved for future use, and it is an error to attempt to use them.
*
* <p><table BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
* <tr BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
* <td><B>Symbol</B></td> <td><B>Meaning</B></td> <td><B>Presentation</B></td> <td><B>Example</B></td> </tr>
* <tr> <td>{@code D}</td> <td>day in year</td> <td>(Number)</td> <td>189</td> </tr>
* <tr> <td>{@code E}</td> <td>day of week</td> <td>(Text)</td> <td>Tuesday</td> </tr>
* <tr> <td>{@code F}</td> <td>day of week in month</td> <td>(Number)</td> <td>2 <i>(2nd Wed in July)</i></td> </tr>
* <tr> <td>{@code G}</td> <td>era designator</td> <td>(Text)</td> <td>AD</td> </tr>
* <tr> <td>{@code H}</td> <td>hour in day (0-23)</td> <td>(Number)</td> <td>0</td> </tr>
* <tr> <td>{@code K}</td> <td>hour in am/pm (0-11)</td> <td>(Number)</td> <td>0</td> </tr>
* <tr> <td>{@code L}</td> <td>stand-alone month</td> <td>(Text/Number)</td> <td>July / 07</td> </tr>
* <tr> <td>{@code M}</td> <td>month in year</td> <td>(Text/Number)</td> <td>July / 07</td> </tr>
* <tr> <td>{@code S}</td> <td>fractional seconds</td> <td>(Number)</td> <td>978</td> </tr>
* <tr> <td>{@code W}</td> <td>week in month</td> <td>(Number)</td> <td>2</td> </tr>
* <tr> <td>{@code Z}</td> <td>time zone (RFC 822)</td> <td>(Timezone)</td> <td>-0800</td> </tr>
* <tr> <td>{@code a}</td> <td>am/pm marker</td> <td>(Text)</td> <td>PM</td> </tr>
* <tr> <td>{@code c}</td> <td>stand-alone day of week</td> <td>(Text/Number)</td> <td>Tuesday / 2</td> </tr>
* <tr> <td>{@code d}</td> <td>day in month</td> <td>(Number)</td> <td>10</td> </tr>
* <tr> <td>{@code h}</td> <td>hour in am/pm (1-12)</td> <td>(Number)</td> <td>12</td> </tr>
* <tr> <td>{@code k}</td> <td>hour in day (1-24)</td> <td>(Number)</td> <td>24</td> </tr>
* <tr> <td>{@code m}</td> <td>minute in hour</td> <td>(Number)</td> <td>30</td> </tr>
* <tr> <td>{@code s}</td> <td>second in minute</td> <td>(Number)</td> <td>55</td> </tr>
* <tr> <td>{@code w}</td> <td>week in year</td> <td>(Number)</td> <td>27</td> </tr>
* <tr> <td>{@code y}</td> <td>year</td> <td>(Number)</td> <td>2010</td> </tr>
* <tr> <td>{@code z}</td> <td>time zone</td> <td>(Timezone)</td> <td>Pacific Standard Time</td> </tr>
* <tr> <td>{@code '}</td> <td>escape for text</td> <td>(Delimiter)</td> <td>'Date='</td> </tr>
* <tr> <td>{@code ''}</td> <td>single quote</td> <td>(Literal)</td> <td>'o''clock'</td> </tr>
* </table>
*
* <p>The number of consecutive copies (the "count") of a pattern character further influences
* the format.
* <ul>
* <li><b>Text</b> if the count is 4 or more, use the full form; otherwise use a short or
* abbreviated form if one exists. So {@code zzzz} might give {@code Pacific Standard Time}
* whereas {@code z} might give {@code PST}. Note that the count does <i>not</i> specify the
* exact width of the field.
*
* <li><b>Number</b> the count is the minimum number of digits. Shorter values are
* zero-padded to this width, longer values overflow this width.
*
* <p>Years are handled specially: {@code yy} truncates to the last 2 digits, but any
* other number of consecutive {@code y}s does not truncate. So where {@code yyyy} or
* {@code y} might give {@code 2010}, {@code yy} would give {@code 10}.
*
* <p>Fractional seconds are also handled specially: they're zero-padded on the
* <i>right</i>.
*
* <li><b>Text/Number</b>: if the count is 3 or more, use text; otherwise use a number.
* So {@code MM} might give {@code 07} while {@code MMM} gives {@code July}.
* </ul>
*
* <p>The two pattern characters {@code L} and {@code c} are ICU-compatible extensions, not
* available in the RI. These are necessary for correct localization in languages such as Russian
* that distinguish between, say, "June" and "June 2010".
*
* <p>When numeric fields are adjacent directly, with no intervening delimiter
* characters, they constitute a run of adjacent numeric fields. Such runs are
* parsed specially. For example, the format "HHmmss" parses the input text
* "123456" to 12:34:56, parses the input text "12345" to 1:23:45, and fails to
* parse "1234". In other words, the leftmost field of the run is flexible,
* while the others keep a fixed width. If the parse fails anywhere in the run,
* then the leftmost field is shortened by one character, and the entire run is
* parsed again. This is repeated until either the parse succeeds or the
* leftmost field is one character in length. If the parse still fails at that
* point, the parse of the run fails.
*
* <p>See {@link #set2DigitYearStart} for more about handling two-digit years.
*
* <h4>Sample Code</h4>
* <p>If you're formatting for human use, you should use an instance returned from
* {@link DateFormat} as described above. This code:
* <pre>
* DateFormat[] formats = new DateFormat[] {
* DateFormat.getDateInstance(),
* DateFormat.getDateTimeInstance(),
* DateFormat.getTimeInstance(),
* };
* for (DateFormat df : formats) {
* System.err.println(df.format(new Date(0)));
* }
* </pre>
*
* <p>Produces this output when run on an {@code en_US} device in the PDT time zone:
* <pre>
* Dec 31, 1969
* Dec 31, 1969 4:00:00 PM
* 4:00:00 PM
* </pre>
* And will produce similarly appropriate localized human-readable output on any user's system.
*
* <p>If you're formatting for machine use, consider this code:
* <pre>
* String[] formats = new String[] {
* "yyyy-MM-dd",
* "yyyy-MM-dd HH:mm",
* "yyyy-MM-dd HH:mmZ",
* "yyyy-MM-dd HH:mm:ss.SSSZ",
* "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
* };
* for (String format : formats) {
* SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
* System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
* sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
* System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
* }
* </pre>
*
* <p>Which produces this output when run in the PDT time zone:
* <pre>
* yyyy-MM-dd 1969-12-31
* yyyy-MM-dd 1970-01-01
* yyyy-MM-dd HH:mm 1969-12-31 16:00
* yyyy-MM-dd HH:mm 1970-01-01 00:00
* yyyy-MM-dd HH:mmZ 1969-12-31 16:00-0800
* yyyy-MM-dd HH:mmZ 1970-01-01 00:00+0000
* yyyy-MM-dd HH:mm:ss.SSSZ 1969-12-31 16:00:00.000-0800
* yyyy-MM-dd HH:mm:ss.SSSZ 1970-01-01 00:00:00.000+0000
* yyyy-MM-dd'T'HH:mm:ss.SSSZ 1969-12-31T16:00:00.000-0800
* yyyy-MM-dd'T'HH:mm:ss.SSSZ 1970-01-01T00:00:00.000+0000
* </pre>
*
* <p>As this example shows, each {@code SimpleDateFormat} instance has a {@link TimeZone}.
* This is because it's called upon to format instances of {@code Date}, which represents an
* absolute time in UTC. That is, {@code Date} does not carry time zone information.
* By default, {@code SimpleDateFormat} will use the system's default time zone. This is
* appropriate for human-readable output (for which, see the previous sample instead), but
* generally inappropriate for machine-readable output, where ambiguity is a problem. Note that
* in this example, the output that included a time but no time zone cannot be parsed back into
* the original {@code Date}. For this
* reason it is almost always necessary and desirable to include the timezone in the output.
* It may also be desirable to set the formatter's time zone to UTC (to ease comparison, or to
* make logs more readable, for example).
*
* <h4>Synchronization</h4>
* {@code SimpleDateFormat} is not thread-safe. Users should create a separate instance for
* each thread.
*
* @see java.util.Calendar
* @see java.util.Date
* @see java.util.TimeZone
* @see java.text.DateFormat
*/
public class SimpleDateFormat extends DateFormat {
private static final long serialVersionUID = 4774881970558875024L;
// 'L' and 'c' are ICU-compatible extensions for stand-alone month and stand-alone weekday.
static final String PATTERN_CHARS = "GyMdkHmsSEDFwWahKzZLc";
// The index of 'Z' in the PATTERN_CHARS string. This pattern character is supported by the RI,
// but has no corresponding public constant.
private static final int RFC_822_TIMEZONE_FIELD = 18;
// The index of 'L' (cf. 'M') in the PATTERN_CHARS string. This is an ICU-compatible extension
// necessary for correct localization in various languages (http://b/2633414).
private static final int STAND_ALONE_MONTH_FIELD = 19;
// The index of 'c' (cf. 'E') in the PATTERN_CHARS string. This is an ICU-compatible extension
// necessary for correct localization in various languages (http://b/2633414).
private static final int STAND_ALONE_DAY_OF_WEEK_FIELD = 20;
private String pattern;
private DateFormatSymbols formatData;
transient private int creationYear;
private Date defaultCenturyStart;
/**
* Constructs a new {@code SimpleDateFormat} for formatting and parsing
* dates and times in the {@code SHORT} style for the user's default locale.
* See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
*/
public SimpleDateFormat() {
this(Locale.getDefault());
this.pattern = defaultPattern();
this.formatData = new DateFormatSymbols(Locale.getDefault());
}
/**
* Constructs a new {@code SimpleDateFormat} using the specified
* non-localized pattern and the {@code DateFormatSymbols} and {@code
* Calendar} for the user's default locale.
* See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
*
* @param pattern
* the pattern.
* @throws NullPointerException
* if the pattern is {@code null}.
* @throws IllegalArgumentException
* if {@code pattern} is not considered to be usable by this
* formatter.
*/
public SimpleDateFormat(String pattern) {
this(pattern, Locale.getDefault());
}
/**
* Validates the format character.
*
* @param format
* the format character
*
* @throws IllegalArgumentException
* when the format character is invalid
*/
private void validateFormat(char format) {
int index = PATTERN_CHARS.indexOf(format);
if (index == -1) {
throw new IllegalArgumentException("Unknown pattern character '" + format + "'");
}
}
/**
* Validates the pattern.
*
* @param template
* the pattern to validate.
*
* @throws NullPointerException
* if the pattern is null
* @throws IllegalArgumentException
* if the pattern is invalid
*/
private void validatePattern(String template) {
boolean quote = false;
int next, last = -1, count = 0;
final int patternLength = template.length();
for (int i = 0; i < patternLength; i++) {
next = (template.charAt(i));
if (next == '\'') {
if (count > 0) {
validateFormat((char) last);
count = 0;
}
if (last == next) {
last = -1;
} else {
last = next;
}
quote = !quote;
continue;
}
if (!quote
&& (last == next || (next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z'))) {
if (last == next) {
count++;
} else {
if (count > 0) {
validateFormat((char) last);
}
last = next;
count = 1;
}
} else {
if (count > 0) {
validateFormat((char) last);
count = 0;
}
last = -1;
}
}
if (count > 0) {
validateFormat((char) last);
}
if (quote) {
throw new IllegalArgumentException("Unterminated quote");
}
}
/**
* Constructs a new {@code SimpleDateFormat} using the specified
* non-localized pattern and {@code DateFormatSymbols} and the {@code
* Calendar} for the user's default locale.
* See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
*
* @param template
* the pattern.
* @param value
* the DateFormatSymbols.
* @throws NullPointerException
* if the pattern is {@code null}.
* @throws IllegalArgumentException
* if the pattern is invalid.
*/
public SimpleDateFormat(String template, DateFormatSymbols value) {
this(Locale.getDefault());
validatePattern(template);
pattern = template;
formatData = (DateFormatSymbols) value.clone();
}
/**
* Constructs a new {@code SimpleDateFormat} using the specified
* non-localized pattern and the {@code DateFormatSymbols} and {@code
* Calendar} for the specified locale.
*
* @param template
* the pattern.
* @param locale
* the locale.
* @throws NullPointerException
* if the pattern is {@code null}.
* @throws IllegalArgumentException
* if the pattern is invalid.
*/
public SimpleDateFormat(String template, Locale locale) {
this(locale);
validatePattern(template);
pattern = template;
formatData = new DateFormatSymbols(locale);
}
private SimpleDateFormat(Locale locale) {
numberFormat = NumberFormat.getInstance(locale);
numberFormat.setParseIntegerOnly(true);
numberFormat.setGroupingUsed(false);
calendar = new GregorianCalendar(locale);
calendar.add(Calendar.YEAR, -80);
creationYear = calendar.get(Calendar.YEAR);
defaultCenturyStart = calendar.getTime();
}
/**
* Changes the pattern of this simple date format to the specified pattern
* which uses localized pattern characters.
*
* @param template
* the localized pattern.
*/
public void applyLocalizedPattern(String template) {
pattern = convertPattern(template, formatData.getLocalPatternChars(), PATTERN_CHARS, true);
}
/**
* Changes the pattern of this simple date format to the specified pattern
* which uses non-localized pattern characters.
*
* @param template
* the non-localized pattern.
* @throws NullPointerException
* if the pattern is {@code null}.
* @throws IllegalArgumentException
* if the pattern is invalid.
*/
public void applyPattern(String template) {
validatePattern(template);
pattern = template;
}
/**
* Returns a new {@code SimpleDateFormat} with the same pattern and
* properties as this simple date format.
*/
@Override
public Object clone() {
SimpleDateFormat clone = (SimpleDateFormat) super.clone();
clone.formatData = (DateFormatSymbols) formatData.clone();
clone.defaultCenturyStart = new Date(defaultCenturyStart.getTime());
return clone;
}
private static String defaultPattern() {
LocaleData localeData = LocaleData.get(Locale.getDefault());
return localeData.getDateFormat(SHORT) + " " + localeData.getTimeFormat(SHORT);
}
/**
* Compares the specified object with this simple date format and indicates
* if they are equal. In order to be equal, {@code object} must be an
* instance of {@code SimpleDateFormat} and have the same {@code DateFormat}
* properties, pattern, {@code DateFormatSymbols} and creation year.
*
* @param object
* the object to compare with this object.
* @return {@code true} if the specified object is equal to this simple date
* format; {@code false} otherwise.
* @see #hashCode
*/
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof SimpleDateFormat)) {
return false;
}
SimpleDateFormat simple = (SimpleDateFormat) object;
return super.equals(object) && pattern.equals(simple.pattern)
&& formatData.equals(simple.formatData);
}
/**
* Formats the specified object using the rules of this simple date format
* and returns an {@code AttributedCharacterIterator} with the formatted
* date and attributes.
*
* @param object
* the object to format.
* @return an {@code AttributedCharacterIterator} with the formatted date
* and attributes.
* @throws NullPointerException
* if the object is {@code null}.
* @throws IllegalArgumentException
* if the object cannot be formatted by this simple date
* format.
*/
@Override
public AttributedCharacterIterator formatToCharacterIterator(Object object) {
if (object == null) {
throw new NullPointerException("object == null");
}
if (object instanceof Date) {
return formatToCharacterIteratorImpl((Date) object);
}
if (object instanceof Number) {
return formatToCharacterIteratorImpl(new Date(((Number) object).longValue()));
}
throw new IllegalArgumentException("Bad class: " + object.getClass());
}
private AttributedCharacterIterator formatToCharacterIteratorImpl(Date date) {
StringBuffer buffer = new StringBuffer();
ArrayList<FieldPosition> fields = new ArrayList<FieldPosition>();
// format the date, and find fields
formatImpl(date, buffer, null, fields);
// create and AttributedString with the formatted buffer
AttributedString as = new AttributedString(buffer.toString());
// add DateFormat field attributes to the AttributedString
for (FieldPosition pos : fields) {
Format.Field attribute = pos.getFieldAttribute();
as.addAttribute(attribute, attribute, pos.getBeginIndex(), pos.getEndIndex());
}
// return the CharacterIterator from AttributedString
return as.getIterator();
}
/**
* Formats the date.
* <p>
* If the FieldPosition {@code field} is not null, and the field
* specified by this FieldPosition is formatted, set the begin and end index
* of the formatted field in the FieldPosition.
* <p>
* If the list {@code fields} is not null, find fields of this
* date, set FieldPositions with these fields, and add them to the fields
* vector.
*
* @param date
* Date to Format
* @param buffer
* StringBuffer to store the resulting formatted String
* @param field
* FieldPosition to set begin and end index of the field
* specified, if it is part of the format for this date
* @param fields
* list used to store the FieldPositions for each field in this
* date
* @return the formatted Date
* @throws IllegalArgumentException
* if the object cannot be formatted by this Format.
*/
private StringBuffer formatImpl(Date date, StringBuffer buffer,
FieldPosition field, List<FieldPosition> fields) {
boolean quote = false;
int next, last = -1, count = 0;
calendar.setTime(date);
if (field != null) {
field.clear();
}
final int patternLength = pattern.length();
for (int i = 0; i < patternLength; i++) {
next = (pattern.charAt(i));
if (next == '\'') {
if (count > 0) {
append(buffer, field, fields, (char) last, count);
count = 0;
}
if (last == next) {
buffer.append('\'');
last = -1;
} else {
last = next;
}
quote = !quote;
continue;
}
if (!quote
&& (last == next || (next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z'))) {
if (last == next) {
count++;
} else {
if (count > 0) {
append(buffer, field, fields, (char) last, count);
}
last = next;
count = 1;
}
} else {
if (count > 0) {
append(buffer, field, fields, (char) last, count);
count = 0;
}
last = -1;
buffer.append((char) next);
}
}
if (count > 0) {
append(buffer, field, fields, (char) last, count);
}
return buffer;
}
private void append(StringBuffer buffer, FieldPosition position,
List<FieldPosition> fields, char format, int count) {
int field = -1;
int index = PATTERN_CHARS.indexOf(format);
if (index == -1) {
throw new IllegalArgumentException("Unknown pattern character '" + format + "'");
}
int beginPosition = buffer.length();
Field dateFormatField = null;
switch (index) {
case ERA_FIELD:
dateFormatField = Field.ERA;
buffer.append(formatData.eras[calendar.get(Calendar.ERA)]);
break;
case YEAR_FIELD:
dateFormatField = Field.YEAR;
int year = calendar.get(Calendar.YEAR);
/*
* For 'y' and 'yyy', we're consistent with Unicode and previous releases
* of Android. But this means we're inconsistent with the RI.
* http://unicode.org/reports/tr35/
*/
if (count == 2) {
appendNumber(buffer, 2, year % 100);
} else {
appendNumber(buffer, count, year);
}
break;
case STAND_ALONE_MONTH_FIELD: // L
dateFormatField = Field.MONTH;
appendMonth(buffer, count, formatData.longStandAloneMonths, formatData.shortStandAloneMonths);
break;
case MONTH_FIELD: // M
dateFormatField = Field.MONTH;
appendMonth(buffer, count, formatData.months, formatData.shortMonths);
break;
case DATE_FIELD:
dateFormatField = Field.DAY_OF_MONTH;
field = Calendar.DATE;
break;
case HOUR_OF_DAY1_FIELD: // k
dateFormatField = Field.HOUR_OF_DAY1;
int hour = calendar.get(Calendar.HOUR_OF_DAY);
appendNumber(buffer, count, hour == 0 ? 24 : hour);
break;
case HOUR_OF_DAY0_FIELD: // H
dateFormatField = Field.HOUR_OF_DAY0;
field = Calendar.HOUR_OF_DAY;
break;
case MINUTE_FIELD:
dateFormatField = Field.MINUTE;
field = Calendar.MINUTE;
break;
case SECOND_FIELD:
dateFormatField = Field.SECOND;
field = Calendar.SECOND;
break;
case MILLISECOND_FIELD:
dateFormatField = Field.MILLISECOND;
int value = calendar.get(Calendar.MILLISECOND);
appendNumber(buffer, count, value);
break;
case STAND_ALONE_DAY_OF_WEEK_FIELD:
dateFormatField = Field.DAY_OF_WEEK;
appendDayOfWeek(buffer, count, formatData.longStandAloneWeekdays, formatData.shortStandAloneWeekdays);
break;
case DAY_OF_WEEK_FIELD:
dateFormatField = Field.DAY_OF_WEEK;
appendDayOfWeek(buffer, count, formatData.weekdays, formatData.shortWeekdays);
break;
case DAY_OF_YEAR_FIELD:
dateFormatField = Field.DAY_OF_YEAR;
field = Calendar.DAY_OF_YEAR;
break;
case DAY_OF_WEEK_IN_MONTH_FIELD:
dateFormatField = Field.DAY_OF_WEEK_IN_MONTH;
field = Calendar.DAY_OF_WEEK_IN_MONTH;
break;
case WEEK_OF_YEAR_FIELD:
dateFormatField = Field.WEEK_OF_YEAR;
field = Calendar.WEEK_OF_YEAR;
break;
case WEEK_OF_MONTH_FIELD:
dateFormatField = Field.WEEK_OF_MONTH;
field = Calendar.WEEK_OF_MONTH;
break;
case AM_PM_FIELD:
dateFormatField = Field.AM_PM;
buffer.append(formatData.ampms[calendar.get(Calendar.AM_PM)]);
break;
case HOUR1_FIELD: // h
dateFormatField = Field.HOUR1;
hour = calendar.get(Calendar.HOUR);
appendNumber(buffer, count, hour == 0 ? 12 : hour);
break;
case HOUR0_FIELD: // K
dateFormatField = Field.HOUR0;
field = Calendar.HOUR;
break;
case TIMEZONE_FIELD: // z
dateFormatField = Field.TIME_ZONE;
appendTimeZone(buffer, count, true);
break;
case RFC_822_TIMEZONE_FIELD: // Z
dateFormatField = Field.TIME_ZONE;
appendNumericTimeZone(buffer, false);
break;
}
if (field != -1) {
appendNumber(buffer, count, calendar.get(field));
}
if (fields != null) {
position = new FieldPosition(dateFormatField);
position.setBeginIndex(beginPosition);
position.setEndIndex(buffer.length());
fields.add(position);
} else {
// Set to the first occurrence
if ((position.getFieldAttribute() == dateFormatField || (position
.getFieldAttribute() == null && position.getField() == index))
&& position.getEndIndex() == 0) {
position.setBeginIndex(beginPosition);
position.setEndIndex(buffer.length());
}
}
}
private void appendDayOfWeek(StringBuffer buffer, int count, String[] longs, String[] shorts) {
boolean isLong = (count > 3);
String[] days = isLong ? longs : shorts;
buffer.append(days[calendar.get(Calendar.DAY_OF_WEEK)]);
}
private void appendMonth(StringBuffer buffer, int count, String[] longs, String[] shorts) {
int month = calendar.get(Calendar.MONTH);
if (count <= 2) {
appendNumber(buffer, count, month + 1);
return;
}
boolean isLong = (count > 3);
String[] months = isLong ? longs : shorts;
buffer.append(months[month]);
}
/**
* Append a representation of the time zone of 'calendar' to 'buffer'.
*
* @param count the number of z or Z characters in the format string; "zzz" would be 3,
* for example.
* @param generalTimeZone true if we should use a display name ("PDT") if available;
* false implies that we should use RFC 822 format ("-0800") instead. This corresponds to 'z'
* versus 'Z' in the format string.
*/
private void appendTimeZone(StringBuffer buffer, int count, boolean generalTimeZone) {
if (generalTimeZone) {
TimeZone tz = calendar.getTimeZone();
boolean daylight = (calendar.get(Calendar.DST_OFFSET) != 0);
int style = count < 4 ? TimeZone.SHORT : TimeZone.LONG;
if (!formatData.customZoneStrings) {
buffer.append(tz.getDisplayName(daylight, style, formatData.locale));
return;
}
// We can't call TimeZone.getDisplayName() because it would not use
// the custom DateFormatSymbols of this SimpleDateFormat.
String custom = TimeZones.getDisplayName(formatData.zoneStrings, tz.getID(), daylight, style);
if (custom != null) {
buffer.append(custom);
return;
}
}
// We didn't find what we were looking for, so default to a numeric time zone.
appendNumericTimeZone(buffer, generalTimeZone);
}
/**
* @param generalTimeZone "GMT-08:00" rather than "-0800".
*/
private void appendNumericTimeZone(StringBuffer buffer, boolean generalTimeZone) {
int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
char sign = '+';
if (offset < 0) {
sign = '-';
offset = -offset;
}
if (generalTimeZone) {
buffer.append("GMT");
}
buffer.append(sign);
appendNumber(buffer, 2, offset / 3600000);
if (generalTimeZone) {
buffer.append(':');
}
appendNumber(buffer, 2, (offset % 3600000) / 60000);
}
private void appendNumber(StringBuffer buffer, int count, int value) {
// TODO: we could avoid using the NumberFormat in most cases for a significant speedup.
// The only problem is that we expose the NumberFormat to third-party code, so we'd have
// some work to do to work out when the optimization is valid.
int minimumIntegerDigits = numberFormat.getMinimumIntegerDigits();
numberFormat.setMinimumIntegerDigits(count);
numberFormat.format(Integer.valueOf(value), buffer, new FieldPosition(0));
numberFormat.setMinimumIntegerDigits(minimumIntegerDigits);
}
private Date error(ParsePosition position, int offset, TimeZone zone) {
position.setErrorIndex(offset);
calendar.setTimeZone(zone);
return null;
}
/**
* Formats the specified date as a string using the pattern of this date
* format and appends the string to the specified string buffer.
* <p>
* If the {@code field} member of {@code field} contains a value specifying
* a format field, then its {@code beginIndex} and {@code endIndex} members
* will be updated with the position of the first occurrence of this field
* in the formatted text.
*
* @param date
* the date to format.
* @param buffer
* the target string buffer to append the formatted date/time to.
* @param fieldPos
* on input: an optional alignment field; on output: the offsets
* of the alignment field in the formatted text.
* @return the string buffer.
* @throws IllegalArgumentException
* if there are invalid characters in the pattern.
*/
@Override
public StringBuffer format(Date date, StringBuffer buffer, FieldPosition fieldPos) {
// Harmony delegates to ICU's SimpleDateFormat, we implement it directly
return formatImpl(date, buffer, fieldPos, null);
}
/**
* Returns the date which is the start of the one hundred year period for two-digit year values.
* See {@link #set2DigitYearStart} for details.
*/
public Date get2DigitYearStart() {
return (Date) defaultCenturyStart.clone();
}
/**
* Returns the {@code DateFormatSymbols} used by this simple date format.
*
* @return the {@code DateFormatSymbols} object.
*/
public DateFormatSymbols getDateFormatSymbols() {
return (DateFormatSymbols) formatData.clone();
}
@Override
public int hashCode() {
return super.hashCode() + pattern.hashCode() + formatData.hashCode() + creationYear;
}
private int parse(String string, int offset, char format, int count) {
int index = PATTERN_CHARS.indexOf(format);
if (index == -1) {
throw new IllegalArgumentException("Unknown pattern character '" + format + "'");
}
int field = -1;
// TODO: what's 'absolute' for? when is 'count' negative, and why?
int absolute = 0;
if (count < 0) {
count = -count;
absolute = count;
}
switch (index) {
case ERA_FIELD:
return parseText(string, offset, formatData.eras, Calendar.ERA);
case YEAR_FIELD:
if (count >= 3) {
field = Calendar.YEAR;
} else {
ParsePosition position = new ParsePosition(offset);
Number result = parseNumber(absolute, string, position);
if (result == null) {
return -position.getErrorIndex() - 1;
}
int year = result.intValue();
// A two digit year must be exactly two digits, i.e. 01
if ((position.getIndex() - offset) == 2 && year >= 0) {
year += creationYear / 100 * 100;
if (year < creationYear) {
year += 100;
}
}
calendar.set(Calendar.YEAR, year);
return position.getIndex();
}
break;
case STAND_ALONE_MONTH_FIELD: // L
return parseMonth(string, offset, count, absolute,
formatData.longStandAloneMonths, formatData.shortStandAloneMonths);
case MONTH_FIELD: // M
return parseMonth(string, offset, count, absolute,
formatData.months, formatData.shortMonths);
case DATE_FIELD:
field = Calendar.DATE;
break;
case HOUR_OF_DAY1_FIELD: // k
ParsePosition position = new ParsePosition(offset);
Number result = parseNumber(absolute, string, position);
if (result == null) {
return -position.getErrorIndex() - 1;
}
int hour = result.intValue();
if (hour == 24) {
hour = 0;
}
calendar.set(Calendar.HOUR_OF_DAY, hour);
return position.getIndex();
case HOUR_OF_DAY0_FIELD: // H
field = Calendar.HOUR_OF_DAY;
break;
case MINUTE_FIELD:
field = Calendar.MINUTE;
break;
case SECOND_FIELD:
field = Calendar.SECOND;
break;
case MILLISECOND_FIELD:
field = Calendar.MILLISECOND;
break;
case STAND_ALONE_DAY_OF_WEEK_FIELD:
return parseDayOfWeek(string, offset, formatData.longStandAloneWeekdays, formatData.shortStandAloneWeekdays);
case DAY_OF_WEEK_FIELD:
return parseDayOfWeek(string, offset, formatData.weekdays, formatData.shortWeekdays);
case DAY_OF_YEAR_FIELD:
field = Calendar.DAY_OF_YEAR;
break;
case DAY_OF_WEEK_IN_MONTH_FIELD:
field = Calendar.DAY_OF_WEEK_IN_MONTH;
break;
case WEEK_OF_YEAR_FIELD:
field = Calendar.WEEK_OF_YEAR;
break;
case WEEK_OF_MONTH_FIELD:
field = Calendar.WEEK_OF_MONTH;
break;
case AM_PM_FIELD:
return parseText(string, offset, formatData.ampms, Calendar.AM_PM);
case HOUR1_FIELD: // h
position = new ParsePosition(offset);
result = parseNumber(absolute, string, position);
if (result == null) {
return -position.getErrorIndex() - 1;
}
hour = result.intValue();
if (hour == 12) {
hour = 0;
}
calendar.set(Calendar.HOUR, hour);
return position.getIndex();
case HOUR0_FIELD: // K
field = Calendar.HOUR;
break;
case TIMEZONE_FIELD: // z
return parseTimeZone(string, offset);
case RFC_822_TIMEZONE_FIELD: // Z
return parseTimeZone(string, offset);
}
if (field != -1) {
return parseNumber(absolute, string, offset, field, 0);
}
return offset;
}
private int parseDayOfWeek(String string, int offset, String[] longs, String[] shorts) {
int index = parseText(string, offset, longs, Calendar.DAY_OF_WEEK);
if (index < 0) {
index = parseText(string, offset, shorts, Calendar.DAY_OF_WEEK);
}
return index;
}
private int parseMonth(String string, int offset, int count, int absolute, String[] longs, String[] shorts) {
if (count <= 2) {
return parseNumber(absolute, string, offset, Calendar.MONTH, -1);
}
int index = parseText(string, offset, longs, Calendar.MONTH);
if (index < 0) {
index = parseText(string, offset, shorts, Calendar.MONTH);
}
return index;
}
/**
* Parses a date from the specified string starting at the index specified
* by {@code position}. If the string is successfully parsed then the index
* of the {@code ParsePosition} is updated to the index following the parsed
* text. On error, the index is unchanged and the error index of {@code
* ParsePosition} is set to the index where the error occurred.
*
* @param string
* the string to parse using the pattern of this simple date
* format.
* @param position
* input/output parameter, specifies the start index in {@code
* string} from where to start parsing. If parsing is successful,
* it is updated with the index following the parsed text; on
* error, the index is unchanged and the error index is set to
* the index where the error occurred.
* @return the date resulting from the parse, or {@code null} if there is an
* error.
* @throws IllegalArgumentException
* if there are invalid characters in the pattern.
*/
@Override
public Date parse(String string, ParsePosition position) {
// Harmony delegates to ICU's SimpleDateFormat, we implement it directly
boolean quote = false;
int next, last = -1, count = 0, offset = position.getIndex();
int length = string.length();
calendar.clear();
TimeZone zone = calendar.getTimeZone();
final int patternLength = pattern.length();
for (int i = 0; i < patternLength; i++) {
next = pattern.charAt(i);
if (next == '\'') {
if (count > 0) {
if ((offset = parse(string, offset, (char) last, count)) < 0) {
return error(position, -offset - 1, zone);
}
count = 0;
}
if (last == next) {
if (offset >= length || string.charAt(offset) != '\'') {
return error(position, offset, zone);
}
offset++;
last = -1;
} else {
last = next;
}
quote = !quote;
continue;
}
if (!quote
&& (last == next || (next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z'))) {
if (last == next) {
count++;
} else {
if (count > 0) {
if ((offset = parse(string, offset, (char) last, -count)) < 0) {
return error(position, -offset - 1, zone);
}
}
last = next;
count = 1;
}
} else {
if (count > 0) {
if ((offset = parse(string, offset, (char) last, count)) < 0) {
return error(position, -offset - 1, zone);
}
count = 0;
}
last = -1;
if (offset >= length || string.charAt(offset) != next) {
return error(position, offset, zone);
}
offset++;
}
}
if (count > 0) {
if ((offset = parse(string, offset, (char) last, count)) < 0) {
return error(position, -offset - 1, zone);
}
}
Date date;
try {
date = calendar.getTime();
} catch (IllegalArgumentException e) {
return error(position, offset, zone);
}
position.setIndex(offset);
calendar.setTimeZone(zone);
return date;
}
private Number parseNumber(int max, String string, ParsePosition position) {
int length = string.length();
int index = position.getIndex();
if (max > 0 && max < length - index) {
length = index + max;
}
while (index < length && (string.charAt(index) == ' ' || string.charAt(index) == '\t')) {
++index;
}
if (max == 0) {
position.setIndex(index);
Number n = numberFormat.parse(string, position);
// In RTL locales, NumberFormat might have parsed "2012-" in an ISO date as the
// negative number -2012.
// Ideally, we wouldn't have this broken API that exposes a NumberFormat and expects
// us to use it. The next best thing would be a way to ask the NumberFormat to parse
// positive numbers only, but icu4c supports negative (BCE) years. The best we can do
// is try to recognize when icu4c has done this, and undo it.
if (n != null && n.longValue() < 0) {
if (numberFormat instanceof DecimalFormat) {
DecimalFormat df = (DecimalFormat) numberFormat;
char lastChar = string.charAt(position.getIndex() - 1);
char minusSign = df.getDecimalFormatSymbols().getMinusSign();
if (lastChar == minusSign) {
n = Long.valueOf(-n.longValue()); // Make the value positive.
position.setIndex(position.getIndex() - 1); // Spit out the negative sign.
}
}
}
return n;
}
int result = 0;
int digit;
while (index < length && (digit = Character.digit(string.charAt(index), 10)) != -1) {
result = result * 10 + digit;
++index;
}
if (index == position.getIndex()) {
position.setErrorIndex(index);
return null;
}
position.setIndex(index);
return Integer.valueOf(result);
}
private int parseNumber(int max, String string, int offset, int field, int skew) {
ParsePosition position = new ParsePosition(offset);
Number result = parseNumber(max, string, position);
if (result == null) {
return -position.getErrorIndex() - 1;
}
calendar.set(field, result.intValue() + skew);
return position.getIndex();
}
private int parseText(String string, int offset, String[] text, int field) {
int found = -1;
for (int i = 0; i < text.length; i++) {
if (text[i].isEmpty()) {
continue;
}
if (string.regionMatches(true, offset, text[i], 0, text[i].length())) {
// Search for the longest match, in case some fields are subsets
if (found == -1 || text[i].length() > text[found].length()) {
found = i;
}
}
}
if (found != -1) {
calendar.set(field, found);
return offset + text[found].length();
}
return -offset - 1;
}
private int parseTimeZone(String string, int offset) {
boolean foundGMT = string.regionMatches(offset, "GMT", 0, 3);
if (foundGMT) {
offset += 3;
}
char sign;
if (offset < string.length()
&& ((sign = string.charAt(offset)) == '+' || sign == '-')) {
ParsePosition position = new ParsePosition(offset + 1);
Number result = numberFormat.parse(string, position);
if (result == null) {
return -position.getErrorIndex() - 1;
}
int hour = result.intValue();
int raw = hour * 3600000;
int index = position.getIndex();
if (index < string.length() && string.charAt(index) == ':') {
position.setIndex(index + 1);
result = numberFormat.parse(string, position);
if (result == null) {
return -position.getErrorIndex() - 1;
}
int minute = result.intValue();
raw += minute * 60000;
} else if (hour >= 24) {
raw = (hour / 100 * 3600000) + (hour % 100 * 60000);
}
if (sign == '-') {
raw = -raw;
}
calendar.setTimeZone(new SimpleTimeZone(raw, ""));
return position.getIndex();
}
if (foundGMT) {
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
return offset;
}
String[][] zones = formatData.internalZoneStrings();
for (String[] element : zones) {
for (int j = TimeZones.LONG_NAME; j < TimeZones.NAME_COUNT; j++) {
if (string.regionMatches(true, offset, element[j], 0, element[j].length())) {
TimeZone zone = TimeZone.getTimeZone(element[TimeZones.OLSON_NAME]);
if (zone == null) {
return -offset - 1;
}
int raw = zone.getRawOffset();
if (j == TimeZones.LONG_NAME_DST || j == TimeZones.SHORT_NAME_DST) {
// Not all time zones use a one-hour difference, so we need to query
// the TimeZone. (Australia/Lord_Howe is the usual example of this.)
int dstSavings = zone.getDSTSavings();
// One problem with TimeZone.getDSTSavings is that it will return 0 if the
// time zone has stopped using DST, even if we're parsing a date from
// the past. In that case, assume the default.
if (dstSavings == 0) {
// TODO: we should change this to use TimeZone.getOffset(long),
// but that requires the complete date to be parsed first.
dstSavings = 3600000;
}
raw += dstSavings;
}
calendar.setTimeZone(new SimpleTimeZone(raw, ""));
return offset + element[j].length();
}
}
}
return -offset - 1;
}
/**
* Sets the date which is the start of the one hundred year period for two-digit year values.
*
* <p>When parsing a date string using the abbreviated year pattern {@code yy}, {@code
* SimpleDateFormat} must interpret the abbreviated year relative to some
* century. It does this by adjusting dates to be within 80 years before and 20
* years after the time the {@code SimpleDateFormat} instance was created. For
* example, using a pattern of {@code MM/dd/yy}, an
* instance created on Jan 1, 1997 would interpret the string {@code "01/11/12"}
* as Jan 11, 2012 but interpret the string {@code "05/04/64"} as May 4, 1964.
* During parsing, only strings consisting of exactly two digits, as
* defined by {@link java.lang.Character#isDigit(char)}, will be parsed into the
* default century. Any other numeric string, such as a one digit string, a
* three or more digit string, or a two digit string that isn't all digits (for
* example, {@code "-1"}), is interpreted literally. So using the same pattern, both
* {@code "01/02/3"} and {@code "01/02/003"} are parsed as Jan 2, 3 AD.
* Similarly, {@code "01/02/-3"} is parsed as Jan 2, 4 BC.
*
* <p>If the year pattern does not have exactly two 'y' characters, the year is
* interpreted literally, regardless of the number of digits. So using the
* pattern {@code MM/dd/yyyy}, {@code "01/11/12"} is parsed as Jan 11, 12 A.D.
*/
public void set2DigitYearStart(Date date) {
defaultCenturyStart = (Date) date.clone();
Calendar cal = new GregorianCalendar();
cal.setTime(defaultCenturyStart);
creationYear = cal.get(Calendar.YEAR);
}
/**
* Sets the {@code DateFormatSymbols} used by this simple date format.
*
* @param value
* the new {@code DateFormatSymbols} object.
*/
public void setDateFormatSymbols(DateFormatSymbols value) {
formatData = (DateFormatSymbols) value.clone();
}
/**
* Returns the pattern of this simple date format using localized pattern
* characters.
*
* @return the localized pattern.
*/
public String toLocalizedPattern() {
return convertPattern(pattern, PATTERN_CHARS, formatData.getLocalPatternChars(), false);
}
private static String convertPattern(String template, String fromChars, String toChars, boolean check) {
if (!check && fromChars.equals(toChars)) {
return template;
}
boolean quote = false;
StringBuilder output = new StringBuilder();
int length = template.length();
for (int i = 0; i < length; i++) {
int index;
char next = template.charAt(i);
if (next == '\'') {
quote = !quote;
}
if (!quote && (index = fromChars.indexOf(next)) != -1) {
output.append(toChars.charAt(index));
} else if (check && !quote && ((next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z'))) {
throw new IllegalArgumentException("Invalid pattern character '" + next + "' in " + "'" + template + "'");
} else {
output.append(next);
}
}
if (quote) {
throw new IllegalArgumentException("Unterminated quote");
}
return output.toString();
}
/**
* Returns the pattern of this simple date format using non-localized
* pattern characters.
*
* @return the non-localized pattern.
*/
public String toPattern() {
return pattern;
}
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("defaultCenturyStart", Date.class),
new ObjectStreamField("formatData", DateFormatSymbols.class),
new ObjectStreamField("pattern", String.class),
new ObjectStreamField("serialVersionOnStream", int.class),
};
private void writeObject(ObjectOutputStream stream) throws IOException {
ObjectOutputStream.PutField fields = stream.putFields();
fields.put("defaultCenturyStart", defaultCenturyStart);
fields.put("formatData", formatData);
fields.put("pattern", pattern);
fields.put("serialVersionOnStream", 1);
stream.writeFields();
}
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField fields = stream.readFields();
int version = fields.get("serialVersionOnStream", 0);
Date date;
if (version > 0) {
date = (Date) fields.get("defaultCenturyStart", new Date());
} else {
date = new Date();
}
set2DigitYearStart(date);
formatData = (DateFormatSymbols) fields.get("formatData", null);
pattern = (String) fields.get("pattern", "");
}
}
|
gpl-2.0
|
hop-/Flyy
|
src/base_object.cpp
|
1260
|
#include "base_object.hpp"
using namespace Flyy;
using namespace Flyy::Base;
////////////////////////////////////////////////////////////////
Position::Position(int px, int py) :
x(px),
y(py)
{}
Position& Position::operator=(const Position& p)
{
x = p.x;
y = p.y;
return *this;
}
////////////////////////////////////////////////////////////////
Rectangle::Rectangle() :
p(),
w(0),
h(0)
{}
Rectangle::Rectangle(PositionUnit width, PositionUnit height,
Position position = Position()) :
p(position),
w(width),
h(height)
{}
////////////////////////////////////////////////////////////////
Object::Object(){}
Object::Object(Rectangle rect)
{
rect.p.x = rect.p.x * P_UNIT_TO_METER;
rect.p.y = rect.p.y * P_UNIT_TO_METER;
rect.h = rect.h * P_UNIT_TO_METER;
rect.w = rect.w * P_UNIT_TO_METER;
m_rect = rect;
}
Object::Object(int width, int height,
Position position = Position())
{
m_rect.p.x = position.x * P_UNIT_TO_METER;
m_rect.p.y = position.y * P_UNIT_TO_METER;
m_rect.h = height * P_UNIT_TO_METER;
m_rect.w = width * P_UNIT_TO_METER;
}
Object::~Object(){}
////////////////////////////////////////////////////////////////
|
gpl-2.0
|
chris-wood/SCoNet
|
ns-3-dev/src/ccnSIM/model/fw/per-fib-limits.cc
|
2765
|
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2012 University of California, Los Angeles
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
*/
#include "per-fib-limits.h"
#include "per-out-face-limits.h"
#include "ns3/ccn-l3-protocol.h"
#include "ns3/ccn-interest.h"
#include "ns3/ccn-data.h"
#include "best-route.h"
#include "flooding.h"
#include "smart-flooding.h"
namespace ns3 {
namespace ccn {
namespace fw {
extern template class PerOutFaceLimits<BestRoute>;
extern template class PerOutFaceLimits<Flooding>;
extern template class PerOutFaceLimits<SmartFlooding>;
template class PerFibLimits< PerOutFaceLimits<BestRoute> >;
typedef PerFibLimits< PerOutFaceLimits<BestRoute> > PerFibLimitsPerOutFaceLimitsBestRoute;
NS_OBJECT_ENSURE_REGISTERED (PerFibLimitsPerOutFaceLimitsBestRoute);
template class PerFibLimits< PerOutFaceLimits<Flooding> >;
typedef PerFibLimits< PerOutFaceLimits<Flooding> > PerFibLimitsPerOutFaceLimitsFlooding;
NS_OBJECT_ENSURE_REGISTERED (PerFibLimitsPerOutFaceLimitsFlooding);
template class PerFibLimits< PerOutFaceLimits<SmartFlooding> >;
typedef PerFibLimits< PerOutFaceLimits<SmartFlooding> > PerFibLimitsPerOutFaceLimitsSmartFlooding;
NS_OBJECT_ENSURE_REGISTERED (PerFibLimitsPerOutFaceLimitsSmartFlooding);
#ifdef DOXYGEN
// /**
// * \brief Strategy implementing per-fib-per-out-face limits on top of BestRoute strategy
// */
class BestRoute::PerOutFaceLimits::PerFibLimits : public ::ns3::ccn::fw::PerFibLimits< ::ns3::ccn::fw::PerOutFaceLimits<BestRoute> > { };
/**
* \brief Strategy implementing per-fib-per-out-face limits on top of Flooding strategy
*/
class Flooding::PerOutFaceLimits::PerFibLimits : public ::ns3::ccn::fw::PerFibLimits< ::ns3::ccn::fw::PerOutFaceLimits<Flooding> > { };
/**
* \brief Strategy implementing per-fib-per-out-face limits on top of SmartFlooding strategy
*/
class SmartFlooding::PerOutFaceLimits::PerFibLimits : public ::ns3::ccn::fw::PerFibLimits< ::ns3::ccn::fw::PerOutFaceLimits<SmartFlooding> > { };
#endif
} // namespace fw
} // namespace ccn
} // namespace ns3
|
gpl-2.0
|
jiteshtandel/04CP018_no_son
|
wp-content/themes/getknowtion/js/bbpress/editor.js
|
1399
|
jQuery(document).ready( function() {
/* Use backticks instead of <code> for the Code button in the editor */
if ( typeof( edButtons ) !== 'undefined' ) {
edButtons[110] = new QTags.TagButton( 'code', 'code', '`', '`', 'c' );
QTags._buttonsInit();
}
/* Tab from topic title */
jQuery( '#bbp_topic_title' ).bind( 'keydown.editor-focus', function(e) {
if ( e.which !== 9 )
return;
if ( !e.ctrlKey && !e.altKey && !e.shiftKey ) {
if ( typeof( tinymce ) !== 'undefined' ) {
if ( ! tinymce.activeEditor.isHidden() ) {
var editor = tinymce.activeEditor.editorContainer;
jQuery( '#' + editor + ' td.mceToolbar > a' ).focus();
} else {
jQuery( 'textarea.bbp-the-content' ).focus();
}
} else {
jQuery( 'textarea.bbp-the-content' ).focus();
}
e.preventDefault();
}
});
/* Shift + tab from topic tags */
jQuery( '#bbp_topic_tags' ).bind( 'keydown.editor-focus', function(e) {
if ( e.which !== 9 )
return;
if ( e.shiftKey && !e.ctrlKey && !e.altKey ) {
if ( typeof( tinymce ) !== 'undefined' ) {
if ( ! tinymce.activeEditor.isHidden() ) {
var editor = tinymce.activeEditor.editorContainer;
jQuery( '#' + editor + ' td.mceToolbar > a' ).focus();
} else {
jQuery( 'textarea.bbp-the-content' ).focus();
}
} else {
jQuery( 'textarea.bbp-the-content' ).focus();
}
e.preventDefault();
}
});
});
|
gpl-2.0
|
tolymhlv/trider
|
administrator/components/com_jshopping/views/category/view.html.php
|
880
|
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.application.component.view');
class JshoppingViewCategory extends JViewLegacy
{
function displayList($tpl=null){
JToolBarHelper::title( _JSHOP_TREE_CATEGORY, 'generic.png' );
JToolBarHelper::addNew();
JToolBarHelper::publishList();
JToolBarHelper::unpublishList();
JToolBarHelper::deleteList();
parent::display($tpl);
}
function displayEdit($tpl=null){
JToolBarHelper::title( ($this->category->category_id) ? (_JSHOP_EDIT_CATEGORY) : (_JSHOP_NEW_CATEGORY), 'generic.png' );
JToolBarHelper::save();
JToolBarHelper::spacer();
JToolBarHelper::apply();
JToolBarHelper::spacer();
JToolBarHelper::cancel();
parent::display($tpl);
}
}
?>
|
gpl-2.0
|
mweltin/neuralpy
|
neuralpy/neuralpyexceptions.py
|
768
|
class MissingTransferFunctionError(Exception):
"""'
This exception is raised when a node's transfer function is call and
it is undefined. The node base class raises this exceptions. Networks
should always be build with a node derived class.
"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class MissingDerivativeFunctionError(Exception):
"""'
This exception is raised when a node's transfer function is call and
it is undefined. The node base class raises this exceptions. Networks
should always be build with a node derived class.
"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
|
gpl-2.0
|
xingh/magix
|
Magix-Brix/Magix.Brix.Loader/Properties/AssemblyInfo.cs
|
1761
|
/*
* Magix - A Web Application Framework for Humans
* Copyright 2010 - 2011 - Ra-Software, Inc. - thomas.hansen@winergyinc.com
* Magix is licensed as GPLv3, or Commercially for Proprietary Projects through Ra-Software.
*/
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Magix.Brix.Loader")]
[assembly: AssemblyDescription("Magix-Brix Loader helper for dynamically loading modules in your application")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ra-Software, Inc.")]
[assembly: AssemblyProduct("Magix.Brix.Loader")]
[assembly: AssemblyCopyright("Copyright © Ra-Software, Inc. - 2010")]
[assembly: AssemblyTrademark("Magix-Brix")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("933e592e-7eac-4ed8-967f-f2a1205e070f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
gpl-2.0
|
diging/quadriga
|
Quadriga/src/main/java/edu/asu/spring/quadriga/service/publicwebsite/IPublicPageBlockLinkTargets.java
|
567
|
package edu.asu.spring.quadriga.service.publicwebsite;
/**
* This interface holds constants to describe what the text blocks
* on the home page of the public website can link to.
*
* @author Julia Damerow
*
*/
public interface IPublicPageBlockLinkTargets {
public final static String ABOUT = "ABOUT";
public final static String BROWSE = "BROWSE";
public final static String EXPLORE = "EXPLORE";
public final static String SEARCH = "SEARCH";
public final static String STATS = "STATS";
public final static String BLOG = "BLOG";
}
|
gpl-2.0
|
meletakis/collato
|
esn/api/api.py
|
6761
|
from tastypie.authorization import Authorization
import copy
from tastypie.resources import ModelResource, ALL, Resource
from tastypie import fields
from django.contrib.auth.models import User
from roleapp.models import Role
from userprofiles.models import UserProfile
from relationships.models import RelationshipStatus, Relationship
from actstream.models import Action as activities
from notifications.models import Notification as notifications
from applications.models import Action as appaction
from applications.models import App, Data
from responsibilities.models import Responsibility, Assignment
from django.contrib.contenttypes.models import ContentType
import random
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
authorization= Authorization()
filtering = {
'is_superuser' : ALL,
'username' : ALL,
}
class RoleTypeResource(ModelResource):
class Meta:
queryset = Role.objects.all()
resource_name = 'role'
allowed_methods = ['get','post']
excludes = [] # poia na min emfanizei
#fields = ['id'] # poia na emfanizei
include_resource_uri = False
authorization= Authorization()
filtering = {
'type' : ALL
}
#http://127.0.0.1:8000/api/roles/list/?type__startswith=M returns "Maintainers"
def alter_list_data_to_serialize(self, request, data_dict):
if isinstance(data_dict, dict):
if 'meta' in data_dict:
# Get rid of the "meta".
del(data_dict['meta'])
# Rename the objects.
data_dict['roles'] = copy.copy(data_dict['objects'])
del(data_dict['objects'])
return data_dict
class UserProfileResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
role = fields.ForeignKey(RoleTypeResource, 'role')
class Meta:
queryset = UserProfile.objects.all()
resource_name = 'profile'
excludes = [] # poia na min emfanizei
#fields = ['id'] # poia na emfanizei
filtering = {
'user' : ALL
}
include_resource_uri = False
authorization= Authorization()
#http://127.0.0.1:8000/api/roles/list/?type__startswith=M returns "Maintainers"
def alter_list_data_to_serialize(self, request, data_dict):
if isinstance(data_dict, dict):
if 'meta' in data_dict:
# Get rid of the "meta".
del(data_dict['meta'])
# Rename the objects.
data_dict['users'] = copy.copy(data_dict['objects'])
del(data_dict['objects'])
return data_dict
class RelationshipStatusResource(ModelResource):
from_role = fields.ForeignKey(RoleTypeResource, 'from_role', null=True)
to_role = fields.ForeignKey(RoleTypeResource, 'to_role', null=True)
class Meta:
queryset = RelationshipStatus.objects.all()
resource_name = 'relationship_status'
authorization= Authorization()
class RelationshipResource(ModelResource):
from_user = fields.ForeignKey(UserResource, 'from_user')
to_user = fields.ForeignKey(UserResource, 'to_user')
status = fields.ForeignKey(RelationshipStatusResource, 'status')
class Meta:
queryset = Relationship.objects.all()
resource_name = 'relationship'
authorization= Authorization()
class AppDataResource(ModelResource):
class Meta:
allowed_methods = ['get']
queryset = Data.objects.all()
resource_name = 'app_data'
authorization= Authorization()
class AppResource(ModelResource):
class Meta:
allowed_methods = ['get']
queryset = App.objects.all()
resource_name = 'apps'
authorization= Authorization()
class ContentTypeResource(ModelResource):
class Meta:
allowed_methods = ['get']
queryset = ContentType.objects.all()
resource_name = 'content_type'
authorization= Authorization()
class AppStreamResource(ModelResource):
actor_content_type = fields.ForeignKey(ContentTypeResource, 'actor_content_type')
target_content_type = fields.ForeignKey(ContentTypeResource, 'target_content_type')
action_object_content_type = fields.ForeignKey(ContentTypeResource, 'action_object_content_type')
class Meta:
filtering = {
'action_object_object_id' : ALL,
'actor_object_id' : ALL,
'data' : ALL,
'target_object_id' : ALL,
'description' : ALL,
'verb' : ALL,
'timestamp': ['exact', 'lt', 'lte', 'gte', 'gt']
}
queryset = appaction.objects.all()
resource_name = 'app_activities'
allowed_methods = ['get','post','put','patch']
authorization= Authorization()
include_resource_uri = False
class ActionStreamResource(ModelResource):
actor_content_type = fields.ForeignKey(ContentTypeResource, 'actor_content_type')
target_content_type = fields.ForeignKey(ContentTypeResource, 'target_content_type')
action_object_content_type = fields.ForeignKey(ContentTypeResource, 'action_object_content_type')
class Meta:
queryset = activities.objects.all()
resource_name = 'activities'
allowed_methods = ['get','post',]
authorization= Authorization()
class NotificationsResource(ModelResource):
# the two above fields can be null
action_object_content_type = fields.ToOneField('resources.ContentTypeResource', attribute = 'action_object_content_type', related_name='action_object_content_type', full=True, null=True)
target_content_type = fields.ToOneField('resources.ContentTypeResource', attribute = 'target_content_type', related_name='target_content_type', full=True, null=True)
actor_content_type = fields.ForeignKey(ContentTypeResource, 'actor_content_type')
recipient = fields.ForeignKey(UserResource, 'recipient')
#target_content_type = fields.ForeignKey(ContentTypeResource, 'target_content_type')
#action_object_content_type = fields.ForeignKey(ContentTypeResource, 'action_object_content_type')
class Meta:
queryset = notifications.objects.all()
resource_name = 'notifications'
allowed_methods = ['get','post',]
authorization= Authorization()
include_resource_uri = False
class Ethesis_confirmation_Resource(ModelResource):
class Meta:
queryset = User.objects.all()
allowed_methods = ['get']
authorization= Authorization()
resource_name = 'ethesis_confirmation'
filtering = {
'id' : ALL
}
fields = ['id','username']
def dehydrate(self, bundle):
bundle.data['ethesis_confirmation'] = random.choice(['not submitted', 'submitted', 'accepted'])
return bundle
class Owed_courses_Resource(ModelResource):
class Meta:
queryset = User.objects.all()
allowed_methods = ['get']
authorization= Authorization()
resource_name = 'owed_courses'
filtering = {
'id' : ALL
}
fields = ['id','username']
def dehydrate(self, bundle):
bundle.data['owed_courses'] = random.choice(['0', '2', '4'])
return bundle
|
gpl-2.0
|
salem/aman
|
skins/js/tinymce/themes/advanced/js/color_picker.js
|
11268
|
tinyMCEPopup.requireLangPack();
var detail = 50, strhex = "0123456789abcdef", i, isMouseDown = false, isMouseOver = false;
var colors = [
"#000000","#000033","#000066","#000099","#0000cc","#0000ff","#330000","#330033",
"#330066","#330099","#3300cc","#3300ff","#660000","#660033","#660066","#660099",
"#6600cc","#6600ff","#990000","#990033","#990066","#990099","#9900cc","#9900ff",
"#cc0000","#cc0033","#cc0066","#cc0099","#cc00cc","#cc00ff","#ff0000","#ff0033",
"#ff0066","#ff0099","#ff00cc","#ff00ff","#003300","#003333","#003366","#003399",
"#0033cc","#0033ff","#333300","#333333","#333366","#333399","#3333cc","#3333ff",
"#663300","#663333","#663366","#663399","#6633cc","#6633ff","#993300","#993333",
"#993366","#993399","#9933cc","#9933ff","#cc3300","#cc3333","#cc3366","#cc3399",
"#cc33cc","#cc33ff","#ff3300","#ff3333","#ff3366","#ff3399","#ff33cc","#ff33ff",
"#006600","#006633","#006666","#006699","#0066cc","#0066ff","#336600","#336633",
"#336666","#336699","#3366cc","#3366ff","#666600","#666633","#666666","#666699",
"#6666cc","#6666ff","#996600","#996633","#996666","#996699","#9966cc","#9966ff",
"#cc6600","#cc6633","#cc6666","#cc6699","#cc66cc","#cc66ff","#ff6600","#ff6633",
"#ff6666","#ff6699","#ff66cc","#ff66ff","#009900","#009933","#009966","#009999",
"#0099cc","#0099ff","#339900","#339933","#339966","#339999","#3399cc","#3399ff",
"#669900","#669933","#669966","#669999","#6699cc","#6699ff","#999900","#999933",
"#999966","#999999","#9999cc","#9999ff","#cc9900","#cc9933","#cc9966","#cc9999",
"#cc99cc","#cc99ff","#ff9900","#ff9933","#ff9966","#ff9999","#ff99cc","#ff99ff",
"#00cc00","#00cc33","#00cc66","#00cc99","#00cccc","#00ccff","#33cc00","#33cc33",
"#33cc66","#33cc99","#33cccc","#33ccff","#66cc00","#66cc33","#66cc66","#66cc99",
"#66cccc","#66ccff","#99cc00","#99cc33","#99cc66","#99cc99","#99cccc","#99ccff",
"#cccc00","#cccc33","#cccc66","#cccc99","#cccccc","#ccccff","#ffcc00","#ffcc33",
"#ffcc66","#ffcc99","#ffcccc","#ffccff","#00ff00","#00ff33","#00ff66","#00ff99",
"#00ffcc","#00ffff","#33ff00","#33ff33","#33ff66","#33ff99","#33ffcc","#33ffff",
"#66ff00","#66ff33","#66ff66","#66ff99","#66ffcc","#66ffff","#99ff00","#99ff33",
"#99ff66","#99ff99","#99ffcc","#99ffff","#ccff00","#ccff33","#ccff66","#ccff99",
"#ccffcc","#ccffff","#ffff00","#ffff33","#ffff66","#ffff99","#ffffcc","#ffffff"
];
var named = {
'#F0F8FF':'AliceBlue','#FAEBD7':'AntiqueWhite','#00FFFF':'Aqua','#7FFFD4':'Aquamarine','#F0FFFF':'Azure','#F5F5DC':'Beige',
'#FFE4C4':'Bisque','#000000':'Black','#FFEBCD':'BlanchedAlmond','#0000FF':'Blue','#8A2BE2':'BlueViolet','#A52A2A':'Brown',
'#DEB887':'BurlyWood','#5F9EA0':'CadetBlue','#7FFF00':'Chartreuse','#D2691E':'Chocolate','#FF7F50':'Coral','#6495ED':'CornflowerBlue',
'#FFF8DC':'Cornsilk','#DC143C':'Crimson','#00FFFF':'Cyan','#00008B':'DarkBlue','#008B8B':'DarkCyan','#B8860B':'DarkGoldenRod',
'#A9A9A9':'DarkGray','#A9A9A9':'DarkGrey','#006400':'DarkGreen','#BDB76B':'DarkKhaki','#8B008B':'DarkMagenta','#556B2F':'DarkOliveGreen',
'#FF8C00':'Darkorange','#9932CC':'DarkOrchid','#8B0000':'DarkRed','#E9967A':'DarkSalmon','#8FBC8F':'DarkSeaGreen','#483D8B':'DarkSlateBlue',
'#2F4F4F':'DarkSlateGray','#2F4F4F':'DarkSlateGrey','#00CED1':'DarkTurquoise','#9400D3':'DarkViolet','#FF1493':'DeepPink','#00BFFF':'DeepSkyBlue',
'#696969':'DimGray','#696969':'DimGrey','#1E90FF':'DodgerBlue','#B22222':'FireBrick','#FFFAF0':'FloralWhite','#228B22':'ForestGreen',
'#FF00FF':'Fuchsia','#DCDCDC':'Gainsboro','#F8F8FF':'GhostWhite','#FFD700':'Gold','#DAA520':'GoldenRod','#808080':'Gray','#808080':'Grey',
'#008000':'Green','#ADFF2F':'GreenYellow','#F0FFF0':'HoneyDew','#FF69B4':'HotPink','#CD5C5C':'IndianRed','#4B0082':'Indigo','#FFFFF0':'Ivory',
'#F0E68C':'Khaki','#E6E6FA':'Lavender','#FFF0F5':'LavenderBlush','#7CFC00':'LawnGreen','#FFFACD':'LemonChiffon','#ADD8E6':'LightBlue',
'#F08080':'LightCoral','#E0FFFF':'LightCyan','#FAFAD2':'LightGoldenRodYellow','#D3D3D3':'LightGray','#D3D3D3':'LightGrey','#90EE90':'LightGreen',
'#FFB6C1':'LightPink','#FFA07A':'LightSalmon','#20B2AA':'LightSeaGreen','#87CEFA':'LightSkyBlue','#778899':'LightSlateGray','#778899':'LightSlateGrey',
'#B0C4DE':'LightSteelBlue','#FFFFE0':'LightYellow','#00FF00':'Lime','#32CD32':'LimeGreen','#FAF0E6':'Linen','#FF00FF':'Magenta','#800000':'Maroon',
'#66CDAA':'MediumAquaMarine','#0000CD':'MediumBlue','#BA55D3':'MediumOrchid','#9370D8':'MediumPurple','#3CB371':'MediumSeaGreen','#7B68EE':'MediumSlateBlue',
'#00FA9A':'MediumSpringGreen','#48D1CC':'MediumTurquoise','#C71585':'MediumVioletRed','#191970':'MidnightBlue','#F5FFFA':'MintCream','#FFE4E1':'MistyRose','#FFE4B5':'Moccasin',
'#FFDEAD':'NavajoWhite','#000080':'Navy','#FDF5E6':'OldLace','#808000':'Olive','#6B8E23':'OliveDrab','#FFA500':'Orange','#FF4500':'OrangeRed','#DA70D6':'Orchid',
'#EEE8AA':'PaleGoldenRod','#98FB98':'PaleGreen','#AFEEEE':'PaleTurquoise','#D87093':'PaleVioletRed','#FFEFD5':'PapayaWhip','#FFDAB9':'PeachPuff',
'#CD853F':'Peru','#FFC0CB':'Pink','#DDA0DD':'Plum','#B0E0E6':'PowderBlue','#800080':'Purple','#FF0000':'Red','#BC8F8F':'RosyBrown','#4169E1':'RoyalBlue',
'#8B4513':'SaddleBrown','#FA8072':'Salmon','#F4A460':'SandyBrown','#2E8B57':'SeaGreen','#FFF5EE':'SeaShell','#A0522D':'Sienna','#C0C0C0':'Silver',
'#87CEEB':'SkyBlue','#6A5ACD':'SlateBlue','#708090':'SlateGray','#708090':'SlateGrey','#FFFAFA':'Snow','#00FF7F':'SpringGreen',
'#4682B4':'SteelBlue','#D2B48C':'Tan','#008080':'Teal','#D8BFD8':'Thistle','#FF6347':'Aman','#40E0D0':'Turquoise','#EE82EE':'Violet',
'#F5DEB3':'Wheat','#FFFFFF':'White','#F5F5F5':'WhiteSmoke','#FFFF00':'Yellow','#9ACD32':'YellowGreen'
};
function init() {
var inputColor = convertRGBToHex(tinyMCEPopup.getWindowArg('input_color'));
tinyMCEPopup.resizeToInnerSize();
generatePicker();
if (inputColor) {
changeFinalColor(inputColor);
col = convertHexToRGB(inputColor);
if (col)
updateLight(col.r, col.g, col.b);
}
}
function insertAction() {
var color = document.getElementById("color").value, f = tinyMCEPopup.getWindowArg('func');
tinyMCEPopup.restoreSelection();
if (f)
f(color);
tinyMCEPopup.close();
}
function showColor(color, name) {
if (name)
document.getElementById("colorname").innerHTML = name;
document.getElementById("preview").style.backgroundColor = color;
document.getElementById("color").value = color.toLowerCase();
}
function convertRGBToHex(col) {
var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi");
if (!col)
return col;
var rgb = col.replace(re, "$1,$2,$3").split(',');
if (rgb.length == 3) {
r = parseInt(rgb[0]).toString(16);
g = parseInt(rgb[1]).toString(16);
b = parseInt(rgb[2]).toString(16);
r = r.length == 1 ? '0' + r : r;
g = g.length == 1 ? '0' + g : g;
b = b.length == 1 ? '0' + b : b;
return "#" + r + g + b;
}
return col;
}
function convertHexToRGB(col) {
if (col.indexOf('#') != -1) {
col = col.replace(new RegExp('[^0-9A-F]', 'gi'), '');
r = parseInt(col.substring(0, 2), 16);
g = parseInt(col.substring(2, 4), 16);
b = parseInt(col.substring(4, 6), 16);
return {r : r, g : g, b : b};
}
return null;
}
function generatePicker() {
var el = document.getElementById('light'), h = '', i;
for (i = 0; i < detail; i++){
h += '<div id="gs'+i+'" style="background-color:#000000; width:15px; height:3px; border-style:none; border-width:0px;"'
+ ' onclick="changeFinalColor(this.style.backgroundColor)"'
+ ' onmousedown="isMouseDown = true; return false;"'
+ ' onmouseup="isMouseDown = false;"'
+ ' onmousemove="if (isMouseDown && isMouseOver) changeFinalColor(this.style.backgroundColor); return false;"'
+ ' onmouseover="isMouseOver = true;"'
+ ' onmouseout="isMouseOver = false;"'
+ '></div>';
}
el.innerHTML = h;
}
function generateWebColors() {
var el = document.getElementById('webcolors'), h = '', i;
if (el.className == 'generated')
return;
h += '<table border="0" cellspacing="1" cellpadding="0">'
+ '<tr>';
for (i=0; i<colors.length; i++) {
h += '<td bgcolor="' + colors[i] + '" width="10" height="10">'
+ '<a href="javascript:insertAction();" onfocus="showColor(\'' + colors[i] + '\');" onmouseover="showColor(\'' + colors[i] + '\');" style="display:block;width:10px;height:10px;overflow:hidden;">'
+ '</a></td>';
if ((i+1) % 18 == 0)
h += '</tr><tr>';
}
h += '</table>';
el.innerHTML = h;
el.className = 'generated';
}
function generateNamedColors() {
var el = document.getElementById('namedcolors'), h = '', n, v, i = 0;
if (el.className == 'generated')
return;
for (n in named) {
v = named[n];
h += '<a href="javascript:insertAction();" onmouseover="showColor(\'' + n + '\',\'' + v + '\');" style="background-color: ' + n + '"><!-- IE --></a>'
}
el.innerHTML = h;
el.className = 'generated';
}
function dechex(n) {
return strhex.charAt(Math.floor(n / 16)) + strhex.charAt(n % 16);
}
function computeColor(e) {
var x, y, partWidth, partDetail, imHeight, r, g, b, coef, i, finalCoef, finalR, finalG, finalB;
x = e.offsetX ? e.offsetX : (e.target ? e.clientX - e.target.x : 0);
y = e.offsetY ? e.offsetY : (e.target ? e.clientY - e.target.y : 0);
partWidth = document.getElementById('colors').width / 6;
partDetail = detail / 2;
imHeight = document.getElementById('colors').height;
r = (x >= 0)*(x < partWidth)*255 + (x >= partWidth)*(x < 2*partWidth)*(2*255 - x * 255 / partWidth) + (x >= 4*partWidth)*(x < 5*partWidth)*(-4*255 + x * 255 / partWidth) + (x >= 5*partWidth)*(x < 6*partWidth)*255;
g = (x >= 0)*(x < partWidth)*(x * 255 / partWidth) + (x >= partWidth)*(x < 3*partWidth)*255 + (x >= 3*partWidth)*(x < 4*partWidth)*(4*255 - x * 255 / partWidth);
b = (x >= 2*partWidth)*(x < 3*partWidth)*(-2*255 + x * 255 / partWidth) + (x >= 3*partWidth)*(x < 5*partWidth)*255 + (x >= 5*partWidth)*(x < 6*partWidth)*(6*255 - x * 255 / partWidth);
coef = (imHeight - y) / imHeight;
r = 128 + (r - 128) * coef;
g = 128 + (g - 128) * coef;
b = 128 + (b - 128) * coef;
changeFinalColor('#' + dechex(r) + dechex(g) + dechex(b));
updateLight(r, g, b);
}
function updateLight(r, g, b) {
var i, partDetail = detail / 2, finalCoef, finalR, finalG, finalB, color;
for (i=0; i<detail; i++) {
if ((i>=0) && (i<partDetail)) {
finalCoef = i / partDetail;
finalR = dechex(255 - (255 - r) * finalCoef);
finalG = dechex(255 - (255 - g) * finalCoef);
finalB = dechex(255 - (255 - b) * finalCoef);
} else {
finalCoef = 2 - i / partDetail;
finalR = dechex(r * finalCoef);
finalG = dechex(g * finalCoef);
finalB = dechex(b * finalCoef);
}
color = finalR + finalG + finalB;
setCol('gs' + i, '#'+color);
}
}
function changeFinalColor(color) {
if (color.indexOf('#') == -1)
color = convertRGBToHex(color);
setCol('preview', color);
document.getElementById('color').value = color;
}
function setCol(e, c) {
try {
document.getElementById(e).style.backgroundColor = c;
} catch (ex) {
// Ignore IE warning
}
}
tinyMCEPopup.onInit.add(init);
|
gpl-2.0
|
galo2099/golaberto
|
db/migrate/007_add_game_version.rb
|
715
|
class AddGameVersion < ActiveRecord::Migration
def self.up
Game.create_versioned_table
create_table :game_goals_versions, :id => false, :force => true do |t|
t.column :game_version_id, :integer, :default => 0, :null => false
t.column :goal_id, :integer, :default => 0, :null => false
end
Game.reset_column_information
Game.class_eval do
def changed?
true
end
end
games = Game.find(:all)
say_with_time "Updating games" do
games.each do |g|
g.save
say "#{g.id} updated!", true
end
end
end
def self.down
Game.drop_versioned_table
remove_column :games, :version
drop_table :game_goals_versions
end
end
|
gpl-2.0
|
Dioud/Url-Shortener
|
project/src/com/supinfo/project/servlet/LogoutServlet.java
|
690
|
package com.supinfo.project.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet permettant de se délogger.
*/
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final HttpSession session = request.getSession();
session.invalidate();
response.sendRedirect(getServletContext().getContextPath());
}
}
|
gpl-2.0
|
repstd/modified_vlc
|
modules/gui/qt4/dialogs/firstrun.moc.cpp
|
2740
|
/****************************************************************************
** Meta object code from reading C++ file 'firstrun.hpp'
**
** Created: Mon Dec 7 17:03:18 2015
** by: The Qt Meta Object Compiler version 63 (Qt 4.8.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "firstrun.hpp"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'firstrun.hpp' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_FirstRun[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
10, 9, 9, 9, 0x08,
0 // eod
};
static const char qt_meta_stringdata_FirstRun[] = {
"FirstRun\0\0save()\0"
};
void FirstRun::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
FirstRun *_t = static_cast<FirstRun *>(_o);
switch (_id) {
case 0: _t->save(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObjectExtraData FirstRun::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject FirstRun::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_FirstRun,
qt_meta_data_FirstRun, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &FirstRun::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *FirstRun::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *FirstRun::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_FirstRun))
return static_cast<void*>(const_cast< FirstRun*>(this));
return QWidget::qt_metacast(_clname);
}
int FirstRun::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
}
return _id;
}
QT_END_MOC_NAMESPACE
|
gpl-2.0
|
unktomi/form-follows-function
|
f3jdi/src/org/f3/tools/debug/expr/ExpressionParserTokenManager.java
|
53729
|
/*
* Copyright 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* Generated By:JavaCC: Do not edit this line. ExpressionParserTokenManager.java */
package org.f3.tools.debug.expr;
import com.sun.jdi.*;
import java.util.Stack;
import java.util.List;
import java.util.ArrayList;
public class ExpressionParserTokenManager implements ExpressionParserConstants
{
private final int jjStopStringLiteralDfa_0(int pos, long active0, long active1)
{
switch (pos)
{
case 0:
if ((active1 & 0x4000L) != 0L)
return 4;
if ((active0 & 0x7fffffffffffe00L) != 0L)
{
jjmatchedKind = 67;
return 28;
}
if ((active1 & 0x100200000000L) != 0L)
return 49;
return -1;
case 1:
if ((active0 & 0x7ffffffbfcffe00L) != 0L)
{
if (jjmatchedPos != 1)
{
jjmatchedKind = 67;
jjmatchedPos = 1;
}
return 28;
}
if ((active0 & 0x40300000L) != 0L)
return 28;
return -1;
case 2:
if ((active0 & 0x77fffb3afeffe00L) != 0L)
{
if (jjmatchedPos != 2)
{
jjmatchedKind = 67;
jjmatchedPos = 2;
}
return 28;
}
if ((active0 & 0x80004c10000000L) != 0L)
return 28;
return -1;
case 3:
if ((active0 & 0x63bff2b8faf4e00L) != 0L)
{
jjmatchedKind = 67;
jjmatchedPos = 3;
return 28;
}
if ((active0 & 0x14400902040b000L) != 0L)
return 28;
return -1;
case 4:
if ((active0 & 0x2235f2b80ac0600L) != 0L)
{
if (jjmatchedPos != 4)
{
jjmatchedKind = 67;
jjmatchedPos = 4;
}
return 28;
}
if ((active0 & 0x418a0000f034800L) != 0L)
return 28;
return -1;
case 5:
if ((active0 & 0x222070a848c0600L) != 0L)
{
jjmatchedKind = 67;
jjmatchedPos = 5;
return 28;
}
if ((active0 & 0x11582100200000L) != 0L)
return 28;
return -1;
case 6:
if ((active0 & 0x222040a80040200L) != 0L)
{
jjmatchedKind = 67;
jjmatchedPos = 6;
return 28;
}
if ((active0 & 0x30004880400L) != 0L)
return 28;
return -1;
case 7:
if ((active0 & 0x22040a80000000L) != 0L)
{
jjmatchedKind = 67;
jjmatchedPos = 7;
return 28;
}
if ((active0 & 0x200000000040200L) != 0L)
return 28;
return -1;
case 8:
if ((active0 & 0x2000280000000L) != 0L)
{
jjmatchedKind = 67;
jjmatchedPos = 8;
return 28;
}
if ((active0 & 0x20040800000000L) != 0L)
return 28;
return -1;
case 9:
if ((active0 & 0x2000000000000L) != 0L)
{
jjmatchedKind = 67;
jjmatchedPos = 9;
return 28;
}
if ((active0 & 0x280000000L) != 0L)
return 28;
return -1;
case 10:
if ((active0 & 0x2000000000000L) != 0L)
{
jjmatchedKind = 67;
jjmatchedPos = 10;
return 28;
}
return -1;
default :
return -1;
}
}
private final int jjStartNfa_0(int pos, long active0, long active1)
{
return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0, active1), pos + 1);
}
private final int jjStopAtPos(int pos, int kind)
{
jjmatchedKind = kind;
jjmatchedPos = pos;
return pos + 1;
}
private final int jjStartNfaWithStates_0(int pos, int kind, int state)
{
jjmatchedKind = kind;
jjmatchedPos = pos;
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) { return pos + 1; }
return jjMoveNfa_0(state, pos + 1);
}
private final int jjMoveStringLiteralDfa0_0()
{
switch(curChar)
{
case 33:
jjmatchedKind = 82;
return jjMoveStringLiteralDfa1_0(0x0L, 0x2000000L);
case 37:
jjmatchedKind = 101;
return jjMoveStringLiteralDfa1_0(0x0L, 0x1000000000000L);
case 38:
jjmatchedKind = 98;
return jjMoveStringLiteralDfa1_0(0x0L, 0x200008000000L);
case 40:
return jjStopAtPos(0, 70);
case 41:
return jjStopAtPos(0, 71);
case 42:
jjmatchedKind = 96;
return jjMoveStringLiteralDfa1_0(0x0L, 0x80000000000L);
case 43:
jjmatchedKind = 94;
return jjMoveStringLiteralDfa1_0(0x0L, 0x20010000000L);
case 44:
return jjStopAtPos(0, 77);
case 45:
jjmatchedKind = 95;
return jjMoveStringLiteralDfa1_0(0x0L, 0x40020000000L);
case 46:
return jjStartNfaWithStates_0(0, 78, 4);
case 47:
jjmatchedKind = 97;
return jjMoveStringLiteralDfa1_0(0x0L, 0x100000000000L);
case 58:
return jjStopAtPos(0, 85);
case 59:
return jjStopAtPos(0, 76);
case 60:
jjmatchedKind = 81;
return jjMoveStringLiteralDfa1_0(0x0L, 0x2004000800000L);
case 61:
jjmatchedKind = 79;
return jjMoveStringLiteralDfa1_0(0x0L, 0x400000L);
case 62:
jjmatchedKind = 80;
return jjMoveStringLiteralDfa1_0(0x0L, 0xc018001000000L);
case 63:
return jjStopAtPos(0, 84);
case 91:
return jjStopAtPos(0, 74);
case 93:
return jjStopAtPos(0, 75);
case 94:
jjmatchedKind = 100;
return jjMoveStringLiteralDfa1_0(0x0L, 0x800000000000L);
case 97:
return jjMoveStringLiteralDfa1_0(0x200L, 0x0L);
case 98:
return jjMoveStringLiteralDfa1_0(0x1c00L, 0x0L);
case 99:
return jjMoveStringLiteralDfa1_0(0x7e000L, 0x0L);
case 100:
return jjMoveStringLiteralDfa1_0(0x380000L, 0x0L);
case 101:
return jjMoveStringLiteralDfa1_0(0xc00000L, 0x0L);
case 102:
return jjMoveStringLiteralDfa1_0(0x1f000000L, 0x0L);
case 103:
return jjMoveStringLiteralDfa1_0(0x20000000L, 0x0L);
case 105:
return jjMoveStringLiteralDfa1_0(0xfc0000000L, 0x0L);
case 108:
return jjMoveStringLiteralDfa1_0(0x1000000000L, 0x0L);
case 110:
return jjMoveStringLiteralDfa1_0(0xe000000000L, 0x0L);
case 112:
return jjMoveStringLiteralDfa1_0(0xf0000000000L, 0x0L);
case 114:
return jjMoveStringLiteralDfa1_0(0x100000000000L, 0x0L);
case 115:
return jjMoveStringLiteralDfa1_0(0x3e00000000000L, 0x0L);
case 116:
return jjMoveStringLiteralDfa1_0(0xfc000000000000L, 0x0L);
case 118:
return jjMoveStringLiteralDfa1_0(0x300000000000000L, 0x0L);
case 119:
return jjMoveStringLiteralDfa1_0(0x400000000000000L, 0x0L);
case 123:
return jjStopAtPos(0, 72);
case 124:
jjmatchedKind = 99;
return jjMoveStringLiteralDfa1_0(0x0L, 0x400004000000L);
case 125:
return jjStopAtPos(0, 73);
case 126:
return jjStopAtPos(0, 83);
default :
return jjMoveNfa_0(0, 0);
}
}
private final int jjMoveStringLiteralDfa1_0(long active0, long active1)
{
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(0, active0, active1);
return 1;
}
switch(curChar)
{
case 38:
if ((active1 & 0x8000000L) != 0L)
return jjStopAtPos(1, 91);
break;
case 43:
if ((active1 & 0x10000000L) != 0L)
return jjStopAtPos(1, 92);
break;
case 45:
if ((active1 & 0x20000000L) != 0L)
return jjStopAtPos(1, 93);
break;
case 60:
if ((active1 & 0x4000000000L) != 0L)
{
jjmatchedKind = 102;
jjmatchedPos = 1;
}
return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x2000000000000L);
case 61:
if ((active1 & 0x400000L) != 0L)
return jjStopAtPos(1, 86);
else if ((active1 & 0x800000L) != 0L)
return jjStopAtPos(1, 87);
else if ((active1 & 0x1000000L) != 0L)
return jjStopAtPos(1, 88);
else if ((active1 & 0x2000000L) != 0L)
return jjStopAtPos(1, 89);
else if ((active1 & 0x20000000000L) != 0L)
return jjStopAtPos(1, 105);
else if ((active1 & 0x40000000000L) != 0L)
return jjStopAtPos(1, 106);
else if ((active1 & 0x80000000000L) != 0L)
return jjStopAtPos(1, 107);
else if ((active1 & 0x100000000000L) != 0L)
return jjStopAtPos(1, 108);
else if ((active1 & 0x200000000000L) != 0L)
return jjStopAtPos(1, 109);
else if ((active1 & 0x400000000000L) != 0L)
return jjStopAtPos(1, 110);
else if ((active1 & 0x800000000000L) != 0L)
return jjStopAtPos(1, 111);
else if ((active1 & 0x1000000000000L) != 0L)
return jjStopAtPos(1, 112);
break;
case 62:
if ((active1 & 0x8000000000L) != 0L)
{
jjmatchedKind = 103;
jjmatchedPos = 1;
}
return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0xc010000000000L);
case 97:
return jjMoveStringLiteralDfa2_0(active0, 0x12001006000L, active1, 0L);
case 98:
return jjMoveStringLiteralDfa2_0(active0, 0x200L, active1, 0L);
case 101:
return jjMoveStringLiteralDfa2_0(active0, 0x104000080000L, active1, 0L);
case 102:
if ((active0 & 0x40000000L) != 0L)
return jjStartNfaWithStates_0(1, 30, 28);
break;
case 104:
return jjMoveStringLiteralDfa2_0(active0, 0x41c200000008000L, active1, 0L);
case 105:
return jjMoveStringLiteralDfa2_0(active0, 0x6000000L, active1, 0L);
case 108:
return jjMoveStringLiteralDfa2_0(active0, 0x8410000L, active1, 0L);
case 109:
return jjMoveStringLiteralDfa2_0(active0, 0x180000000L, active1, 0L);
case 110:
return jjMoveStringLiteralDfa2_0(active0, 0xe00000000L, active1, 0L);
case 111:
if ((active0 & 0x100000L) != 0L)
{
jjmatchedKind = 20;
jjmatchedPos = 1;
}
return jjMoveStringLiteralDfa2_0(active0, 0x300001030260400L, active1, 0L);
case 114:
return jjMoveStringLiteralDfa2_0(active0, 0xe0060000000800L, active1, 0L);
case 116:
return jjMoveStringLiteralDfa2_0(active0, 0x400000000000L, active1, 0L);
case 117:
return jjMoveStringLiteralDfa2_0(active0, 0x888000000000L, active1, 0L);
case 119:
return jjMoveStringLiteralDfa2_0(active0, 0x1000000000000L, active1, 0L);
case 120:
return jjMoveStringLiteralDfa2_0(active0, 0x800000L, active1, 0L);
case 121:
return jjMoveStringLiteralDfa2_0(active0, 0x2000000001000L, active1, 0L);
case 124:
if ((active1 & 0x4000000L) != 0L)
return jjStopAtPos(1, 90);
break;
default :
break;
}
return jjStartNfa_0(0, active0, active1);
}
private final int jjMoveStringLiteralDfa2_0(long old0, long active0, long old1, long active1)
{
if (((active0 &= old0) | (active1 &= old1)) == 0L)
return jjStartNfa_0(0, old0, old1);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(1, active0, active1);
return 2;
}
switch(curChar)
{
case 61:
if ((active1 & 0x2000000000000L) != 0L)
return jjStopAtPos(2, 113);
else if ((active1 & 0x4000000000000L) != 0L)
return jjStopAtPos(2, 114);
break;
case 62:
if ((active1 & 0x10000000000L) != 0L)
{
jjmatchedKind = 104;
jjmatchedPos = 2;
}
return jjMoveStringLiteralDfa3_0(active0, 0L, active1, 0x8000000000000L);
case 97:
return jjMoveStringLiteralDfa3_0(active0, 0x20400000018000L, active1, 0L);
case 98:
return jjMoveStringLiteralDfa3_0(active0, 0x80000000000L, active1, 0L);
case 99:
return jjMoveStringLiteralDfa3_0(active0, 0x10000000000L, active1, 0L);
case 101:
return jjMoveStringLiteralDfa3_0(active0, 0x800L, active1, 0L);
case 102:
return jjMoveStringLiteralDfa3_0(active0, 0x80000L, active1, 0L);
case 105:
return jjMoveStringLiteralDfa3_0(active0, 0x505020000000000L, active1, 0L);
case 108:
return jjMoveStringLiteralDfa3_0(active0, 0x200008001000000L, active1, 0L);
case 110:
return jjMoveStringLiteralDfa3_0(active0, 0x2001006060000L, active1, 0L);
case 111:
return jjMoveStringLiteralDfa3_0(active0, 0x240008000400L, active1, 0L);
case 112:
return jjMoveStringLiteralDfa3_0(active0, 0x800180000000L, active1, 0L);
case 114:
if ((active0 & 0x10000000L) != 0L)
return jjStartNfaWithStates_0(2, 28, 28);
return jjMoveStringLiteralDfa3_0(active0, 0x18000000000000L, active1, 0L);
case 115:
return jjMoveStringLiteralDfa3_0(active0, 0x200402200L, active1, 0L);
case 116:
if ((active0 & 0x400000000L) != 0L)
{
jjmatchedKind = 34;
jjmatchedPos = 2;
}
return jjMoveStringLiteralDfa3_0(active0, 0x102820805000L, active1, 0L);
case 117:
return jjMoveStringLiteralDfa3_0(active0, 0x40000000200000L, active1, 0L);
case 119:
if ((active0 & 0x4000000000L) != 0L)
return jjStartNfaWithStates_0(2, 38, 28);
break;
case 121:
if ((active0 & 0x80000000000000L) != 0L)
return jjStartNfaWithStates_0(2, 55, 28);
break;
default :
break;
}
return jjStartNfa_0(1, active0, active1);
}
private final int jjMoveStringLiteralDfa3_0(long old0, long active0, long old1, long active1)
{
if (((active0 &= old0) | (active1 &= old1)) == 0L)
return jjStartNfa_0(1, old0, old1);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(2, active0, active1);
return 3;
}
switch(curChar)
{
case 61:
if ((active1 & 0x8000000000000L) != 0L)
return jjStopAtPos(3, 115);
break;
case 97:
return jjMoveStringLiteralDfa4_0(active0, 0x20000000e080800L, active1, 0L);
case 98:
return jjMoveStringLiteralDfa4_0(active0, 0x200000L, active1, 0L);
case 99:
return jjMoveStringLiteralDfa4_0(active0, 0x2000000004000L, active1, 0L);
case 100:
if ((active0 & 0x100000000000000L) != 0L)
return jjStartNfaWithStates_0(3, 56, 28);
break;
case 101:
if ((active0 & 0x1000L) != 0L)
return jjStartNfaWithStates_0(3, 12, 28);
else if ((active0 & 0x2000L) != 0L)
return jjStartNfaWithStates_0(3, 13, 28);
else if ((active0 & 0x400000L) != 0L)
return jjStartNfaWithStates_0(3, 22, 28);
else if ((active0 & 0x40000000000000L) != 0L)
return jjStartNfaWithStates_0(3, 54, 28);
return jjMoveStringLiteralDfa4_0(active0, 0x800800800000L, active1, 0L);
case 103:
if ((active0 & 0x1000000000L) != 0L)
return jjStartNfaWithStates_0(3, 36, 28);
break;
case 105:
return jjMoveStringLiteralDfa4_0(active0, 0x2000000000L, active1, 0L);
case 107:
return jjMoveStringLiteralDfa4_0(active0, 0x10000000000L, active1, 0L);
case 108:
if ((active0 & 0x8000000000L) != 0L)
return jjStartNfaWithStates_0(3, 39, 28);
return jjMoveStringLiteralDfa4_0(active0, 0x400080080000400L, active1, 0L);
case 110:
return jjMoveStringLiteralDfa4_0(active0, 0x20000000000000L, active1, 0L);
case 111:
if ((active0 & 0x20000000L) != 0L)
return jjStartNfaWithStates_0(3, 29, 28);
return jjMoveStringLiteralDfa4_0(active0, 0x18000100000000L, active1, 0L);
case 114:
if ((active0 & 0x8000L) != 0L)
return jjStartNfaWithStates_0(3, 15, 28);
return jjMoveStringLiteralDfa4_0(active0, 0x200000000000L, active1, 0L);
case 115:
if ((active0 & 0x4000000000000L) != 0L)
return jjStartNfaWithStates_0(3, 50, 28);
return jjMoveStringLiteralDfa4_0(active0, 0x1030000L, active1, 0L);
case 116:
return jjMoveStringLiteralDfa4_0(active0, 0x1440200040200L, active1, 0L);
case 117:
return jjMoveStringLiteralDfa4_0(active0, 0x100000000000L, active1, 0L);
case 118:
return jjMoveStringLiteralDfa4_0(active0, 0x20000000000L, active1, 0L);
default :
break;
}
return jjStartNfa_0(2, active0, active1);
}
private final int jjMoveStringLiteralDfa4_0(long old0, long active0, long old1, long active1)
{
if (((active0 &= old0) | (active1 &= old1)) == 0L)
return jjStartNfa_0(2, old0, old1);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(3, active0, 0L);
return 4;
}
switch(curChar)
{
case 97:
return jjMoveStringLiteralDfa5_0(active0, 0x30200000000L);
case 99:
return jjMoveStringLiteralDfa5_0(active0, 0x1000000000000L);
case 101:
if ((active0 & 0x1000000L) != 0L)
return jjStartNfaWithStates_0(4, 24, 28);
else if ((active0 & 0x400000000000000L) != 0L)
return jjStartNfaWithStates_0(4, 58, 28);
return jjMoveStringLiteralDfa5_0(active0, 0x40080000400L);
case 104:
if ((active0 & 0x4000L) != 0L)
return jjStartNfaWithStates_0(4, 14, 28);
return jjMoveStringLiteralDfa5_0(active0, 0x2000000000000L);
case 105:
return jjMoveStringLiteralDfa5_0(active0, 0x480000040000L);
case 107:
if ((active0 & 0x800L) != 0L)
return jjStartNfaWithStates_0(4, 11, 28);
break;
case 108:
if ((active0 & 0x2000000L) != 0L)
{
jjmatchedKind = 25;
jjmatchedPos = 4;
}
return jjMoveStringLiteralDfa5_0(active0, 0x4200000L);
case 110:
return jjMoveStringLiteralDfa5_0(active0, 0x800000L);
case 114:
if ((active0 & 0x800000000000L) != 0L)
return jjStartNfaWithStates_0(4, 47, 28);
return jjMoveStringLiteralDfa5_0(active0, 0x100900000200L);
case 115:
if ((active0 & 0x10000L) != 0L)
return jjStartNfaWithStates_0(4, 16, 28);
return jjMoveStringLiteralDfa5_0(active0, 0x20000000000000L);
case 116:
if ((active0 & 0x20000L) != 0L)
return jjStartNfaWithStates_0(4, 17, 28);
else if ((active0 & 0x8000000L) != 0L)
return jjStartNfaWithStates_0(4, 27, 28);
else if ((active0 & 0x200000000000L) != 0L)
return jjStartNfaWithStates_0(4, 45, 28);
return jjMoveStringLiteralDfa5_0(active0, 0x200000000000000L);
case 117:
return jjMoveStringLiteralDfa5_0(active0, 0x80000L);
case 118:
return jjMoveStringLiteralDfa5_0(active0, 0x2000000000L);
case 119:
if ((active0 & 0x8000000000000L) != 0L)
{
jjmatchedKind = 51;
jjmatchedPos = 4;
}
return jjMoveStringLiteralDfa5_0(active0, 0x10000000000000L);
default :
break;
}
return jjStartNfa_0(3, active0, 0L);
}
private final int jjMoveStringLiteralDfa5_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(3, old0, 0L);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(4, active0, 0L);
return 5;
}
switch(curChar)
{
case 97:
return jjMoveStringLiteralDfa6_0(active0, 0x600L);
case 99:
if ((active0 & 0x80000000000L) != 0L)
return jjStartNfaWithStates_0(5, 43, 28);
else if ((active0 & 0x400000000000L) != 0L)
return jjStartNfaWithStates_0(5, 46, 28);
return jjMoveStringLiteralDfa6_0(active0, 0x40000000000L);
case 100:
return jjMoveStringLiteralDfa6_0(active0, 0x800000L);
case 101:
if ((active0 & 0x200000L) != 0L)
return jjStartNfaWithStates_0(5, 21, 28);
else if ((active0 & 0x2000000000L) != 0L)
return jjStartNfaWithStates_0(5, 37, 28);
break;
case 102:
return jjMoveStringLiteralDfa6_0(active0, 0x800000000L);
case 103:
return jjMoveStringLiteralDfa6_0(active0, 0x10000000000L);
case 104:
if ((active0 & 0x1000000000000L) != 0L)
return jjStartNfaWithStates_0(5, 48, 28);
break;
case 105:
return jjMoveStringLiteralDfa6_0(active0, 0x220000000000000L);
case 108:
return jjMoveStringLiteralDfa6_0(active0, 0x4080000L);
case 109:
return jjMoveStringLiteralDfa6_0(active0, 0x80000000L);
case 110:
if ((active0 & 0x100000000000L) != 0L)
return jjStartNfaWithStates_0(5, 44, 28);
return jjMoveStringLiteralDfa6_0(active0, 0x200040000L);
case 114:
return jjMoveStringLiteralDfa6_0(active0, 0x2000000000000L);
case 115:
if ((active0 & 0x10000000000000L) != 0L)
return jjStartNfaWithStates_0(5, 52, 28);
break;
case 116:
if ((active0 & 0x100000000L) != 0L)
return jjStartNfaWithStates_0(5, 32, 28);
return jjMoveStringLiteralDfa6_0(active0, 0x20000000000L);
default :
break;
}
return jjStartNfa_0(4, active0, 0L);
}
private final int jjMoveStringLiteralDfa6_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(4, old0, 0L);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(5, active0, 0L);
return 6;
}
switch(curChar)
{
case 97:
return jjMoveStringLiteralDfa7_0(active0, 0x800000000L);
case 99:
return jjMoveStringLiteralDfa7_0(active0, 0x200000200L);
case 101:
if ((active0 & 0x10000000000L) != 0L)
return jjStartNfaWithStates_0(6, 40, 28);
else if ((active0 & 0x20000000000L) != 0L)
return jjStartNfaWithStates_0(6, 41, 28);
return jjMoveStringLiteralDfa7_0(active0, 0x20000080000000L);
case 108:
return jjMoveStringLiteralDfa7_0(active0, 0x200000000000000L);
case 110:
if ((active0 & 0x400L) != 0L)
return jjStartNfaWithStates_0(6, 10, 28);
break;
case 111:
return jjMoveStringLiteralDfa7_0(active0, 0x2000000000000L);
case 115:
if ((active0 & 0x800000L) != 0L)
return jjStartNfaWithStates_0(6, 23, 28);
break;
case 116:
if ((active0 & 0x80000L) != 0L)
return jjStartNfaWithStates_0(6, 19, 28);
return jjMoveStringLiteralDfa7_0(active0, 0x40000000000L);
case 117:
return jjMoveStringLiteralDfa7_0(active0, 0x40000L);
case 121:
if ((active0 & 0x4000000L) != 0L)
return jjStartNfaWithStates_0(6, 26, 28);
break;
default :
break;
}
return jjStartNfa_0(5, active0, 0L);
}
private final int jjMoveStringLiteralDfa7_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(5, old0, 0L);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(6, active0, 0L);
return 7;
}
switch(curChar)
{
case 99:
return jjMoveStringLiteralDfa8_0(active0, 0x800000000L);
case 101:
if ((active0 & 0x40000L) != 0L)
return jjStartNfaWithStates_0(7, 18, 28);
else if ((active0 & 0x200000000000000L) != 0L)
return jjStartNfaWithStates_0(7, 57, 28);
return jjMoveStringLiteralDfa8_0(active0, 0x40200000000L);
case 110:
return jjMoveStringLiteralDfa8_0(active0, 0x22000080000000L);
case 116:
if ((active0 & 0x200L) != 0L)
return jjStartNfaWithStates_0(7, 9, 28);
break;
default :
break;
}
return jjStartNfa_0(6, active0, 0L);
}
private final int jjMoveStringLiteralDfa8_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(6, old0, 0L);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(7, active0, 0L);
return 8;
}
switch(curChar)
{
case 100:
if ((active0 & 0x40000000000L) != 0L)
return jjStartNfaWithStates_0(8, 42, 28);
break;
case 101:
if ((active0 & 0x800000000L) != 0L)
return jjStartNfaWithStates_0(8, 35, 28);
break;
case 105:
return jjMoveStringLiteralDfa9_0(active0, 0x2000000000000L);
case 111:
return jjMoveStringLiteralDfa9_0(active0, 0x200000000L);
case 116:
if ((active0 & 0x20000000000000L) != 0L)
return jjStartNfaWithStates_0(8, 53, 28);
return jjMoveStringLiteralDfa9_0(active0, 0x80000000L);
default :
break;
}
return jjStartNfa_0(7, active0, 0L);
}
private final int jjMoveStringLiteralDfa9_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(7, old0, 0L);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(8, active0, 0L);
return 9;
}
switch(curChar)
{
case 102:
if ((active0 & 0x200000000L) != 0L)
return jjStartNfaWithStates_0(9, 33, 28);
break;
case 115:
if ((active0 & 0x80000000L) != 0L)
return jjStartNfaWithStates_0(9, 31, 28);
break;
case 122:
return jjMoveStringLiteralDfa10_0(active0, 0x2000000000000L);
default :
break;
}
return jjStartNfa_0(8, active0, 0L);
}
private final int jjMoveStringLiteralDfa10_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(8, old0, 0L);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(9, active0, 0L);
return 10;
}
switch(curChar)
{
case 101:
return jjMoveStringLiteralDfa11_0(active0, 0x2000000000000L);
default :
break;
}
return jjStartNfa_0(9, active0, 0L);
}
private final int jjMoveStringLiteralDfa11_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(9, old0, 0L);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(10, active0, 0L);
return 11;
}
switch(curChar)
{
case 100:
if ((active0 & 0x2000000000000L) != 0L)
return jjStartNfaWithStates_0(11, 49, 28);
break;
default :
break;
}
return jjStartNfa_0(10, active0, 0L);
}
private final void jjCheckNAdd(int state)
{
if (jjrounds[state] != jjround)
{
jjstateSet[jjnewStateCnt++] = state;
jjrounds[state] = jjround;
}
}
private final void jjAddStates(int start, int end)
{
do {
jjstateSet[jjnewStateCnt++] = jjnextStates[start];
} while (start++ != end);
}
private final void jjCheckNAddTwoStates(int state1, int state2)
{
jjCheckNAdd(state1);
jjCheckNAdd(state2);
}
private final void jjCheckNAddStates(int start, int end)
{
do {
jjCheckNAdd(jjnextStates[start]);
} while (start++ != end);
}
private final void jjCheckNAddStates(int start)
{
jjCheckNAdd(jjnextStates[start]);
jjCheckNAdd(jjnextStates[start + 1]);
}
static final long[] jjbitVec0 = {
0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
};
static final long[] jjbitVec2 = {
0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
};
static final long[] jjbitVec3 = {
0x1ff00000fffffffeL, 0xffffffffffffc000L, 0xffffffffL, 0x600000000000000L
};
static final long[] jjbitVec4 = {
0x0L, 0x0L, 0x0L, 0xff7fffffff7fffffL
};
static final long[] jjbitVec5 = {
0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
};
static final long[] jjbitVec6 = {
0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffL, 0x0L
};
static final long[] jjbitVec7 = {
0xffffffffffffffffL, 0xffffffffffffffffL, 0x0L, 0x0L
};
static final long[] jjbitVec8 = {
0x3fffffffffffL, 0x0L, 0x0L, 0x0L
};
private final int jjMoveNfa_0(int startState, int curPos)
{
int[] nextStates;
int startsAt = 0;
jjnewStateCnt = 67;
int i = 1;
jjstateSet[0] = startState;
int j, kind = 0x7fffffff;
for (;;)
{
if (++jjround == 0x7fffffff)
ReInitRounds();
if (curChar < 64)
{
long l = 1L << curChar;
MatchLoop: do
{
switch(jjstateSet[--i])
{
case 0:
if ((0x3ff000000000000L & l) != 0L)
jjCheckNAddStates(0, 6);
else if (curChar == 47)
jjAddStates(7, 9);
else if (curChar == 36)
{
if (kind > 67)
kind = 67;
jjCheckNAdd(28);
}
else if (curChar == 34)
jjCheckNAddStates(10, 12);
else if (curChar == 39)
jjAddStates(13, 14);
else if (curChar == 46)
jjCheckNAdd(4);
if ((0x3fe000000000000L & l) != 0L)
{
if (kind > 59)
kind = 59;
jjCheckNAddTwoStates(1, 2);
}
else if (curChar == 48)
{
if (kind > 59)
kind = 59;
jjCheckNAddStates(15, 17);
}
break;
case 49:
if (curChar == 42)
jjCheckNAddTwoStates(62, 63);
else if (curChar == 47)
jjCheckNAddStates(18, 20);
if (curChar == 42)
jjstateSet[jjnewStateCnt++] = 54;
break;
case 1:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 59)
kind = 59;
jjCheckNAddTwoStates(1, 2);
break;
case 3:
if (curChar == 46)
jjCheckNAdd(4);
break;
case 4:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 63)
kind = 63;
jjCheckNAddStates(21, 23);
break;
case 6:
if ((0x280000000000L & l) != 0L)
jjCheckNAdd(7);
break;
case 7:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 63)
kind = 63;
jjCheckNAddTwoStates(7, 8);
break;
case 9:
if (curChar == 39)
jjAddStates(13, 14);
break;
case 10:
if ((0xffffff7fffffdbffL & l) != 0L)
jjCheckNAdd(11);
break;
case 11:
if (curChar == 39 && kind > 65)
kind = 65;
break;
case 13:
if ((0x8400000000L & l) != 0L)
jjCheckNAdd(11);
break;
case 14:
if ((0xff000000000000L & l) != 0L)
jjCheckNAddTwoStates(15, 11);
break;
case 15:
if ((0xff000000000000L & l) != 0L)
jjCheckNAdd(11);
break;
case 16:
if ((0xf000000000000L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 17;
break;
case 17:
if ((0xff000000000000L & l) != 0L)
jjCheckNAdd(15);
break;
case 18:
if (curChar == 34)
jjCheckNAddStates(10, 12);
break;
case 19:
if ((0xfffffffbffffdbffL & l) != 0L)
jjCheckNAddStates(10, 12);
break;
case 21:
if ((0x8400000000L & l) != 0L)
jjCheckNAddStates(10, 12);
break;
case 22:
if (curChar == 34 && kind > 66)
kind = 66;
break;
case 23:
if ((0xff000000000000L & l) != 0L)
jjCheckNAddStates(24, 27);
break;
case 24:
if ((0xff000000000000L & l) != 0L)
jjCheckNAddStates(10, 12);
break;
case 25:
if ((0xf000000000000L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 26;
break;
case 26:
if ((0xff000000000000L & l) != 0L)
jjCheckNAdd(24);
break;
case 27:
if (curChar != 36)
break;
if (kind > 67)
kind = 67;
jjCheckNAdd(28);
break;
case 28:
if ((0x3ff001000000000L & l) == 0L)
break;
if (kind > 67)
kind = 67;
jjCheckNAdd(28);
break;
case 29:
if ((0x3ff000000000000L & l) != 0L)
jjCheckNAddStates(0, 6);
break;
case 30:
if ((0x3ff000000000000L & l) != 0L)
jjCheckNAddTwoStates(30, 31);
break;
case 31:
if (curChar != 46)
break;
if (kind > 63)
kind = 63;
jjCheckNAddStates(28, 30);
break;
case 32:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 63)
kind = 63;
jjCheckNAddStates(28, 30);
break;
case 34:
if ((0x280000000000L & l) != 0L)
jjCheckNAdd(35);
break;
case 35:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 63)
kind = 63;
jjCheckNAddTwoStates(35, 8);
break;
case 36:
if ((0x3ff000000000000L & l) != 0L)
jjCheckNAddTwoStates(36, 37);
break;
case 38:
if ((0x280000000000L & l) != 0L)
jjCheckNAdd(39);
break;
case 39:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 63)
kind = 63;
jjCheckNAddTwoStates(39, 8);
break;
case 40:
if ((0x3ff000000000000L & l) != 0L)
jjCheckNAddStates(31, 33);
break;
case 42:
if ((0x280000000000L & l) != 0L)
jjCheckNAdd(43);
break;
case 43:
if ((0x3ff000000000000L & l) != 0L)
jjCheckNAddTwoStates(43, 8);
break;
case 44:
if (curChar != 48)
break;
if (kind > 59)
kind = 59;
jjCheckNAddStates(15, 17);
break;
case 46:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 59)
kind = 59;
jjCheckNAddTwoStates(46, 2);
break;
case 47:
if ((0xff000000000000L & l) == 0L)
break;
if (kind > 59)
kind = 59;
jjCheckNAddTwoStates(47, 2);
break;
case 48:
if (curChar == 47)
jjAddStates(7, 9);
break;
case 50:
if ((0xffffffffffffdbffL & l) != 0L)
jjCheckNAddStates(18, 20);
break;
case 51:
if ((0x2400L & l) != 0L && kind > 6)
kind = 6;
break;
case 52:
if (curChar == 10 && kind > 6)
kind = 6;
break;
case 53:
if (curChar == 13)
jjstateSet[jjnewStateCnt++] = 52;
break;
case 54:
if (curChar == 42)
jjCheckNAddTwoStates(55, 56);
break;
case 55:
if ((0xfffffbffffffffffL & l) != 0L)
jjCheckNAddTwoStates(55, 56);
break;
case 56:
if (curChar == 42)
jjCheckNAddStates(34, 36);
break;
case 57:
if ((0xffff7bffffffffffL & l) != 0L)
jjCheckNAddTwoStates(58, 56);
break;
case 58:
if ((0xfffffbffffffffffL & l) != 0L)
jjCheckNAddTwoStates(58, 56);
break;
case 59:
if (curChar == 47 && kind > 7)
kind = 7;
break;
case 60:
if (curChar == 42)
jjstateSet[jjnewStateCnt++] = 54;
break;
case 61:
if (curChar == 42)
jjCheckNAddTwoStates(62, 63);
break;
case 62:
if ((0xfffffbffffffffffL & l) != 0L)
jjCheckNAddTwoStates(62, 63);
break;
case 63:
if (curChar == 42)
jjCheckNAddStates(37, 39);
break;
case 64:
if ((0xffff7bffffffffffL & l) != 0L)
jjCheckNAddTwoStates(65, 63);
break;
case 65:
if ((0xfffffbffffffffffL & l) != 0L)
jjCheckNAddTwoStates(65, 63);
break;
case 66:
if (curChar == 47 && kind > 8)
kind = 8;
break;
default : break;
}
} while(i != startsAt);
}
else if (curChar < 128)
{
long l = 1L << (curChar & 077);
MatchLoop: do
{
switch(jjstateSet[--i])
{
case 0:
case 28:
if ((0x7fffffe87fffffeL & l) == 0L)
break;
if (kind > 67)
kind = 67;
jjCheckNAdd(28);
break;
case 2:
if ((0x100000001000L & l) != 0L && kind > 59)
kind = 59;
break;
case 5:
if ((0x2000000020L & l) != 0L)
jjAddStates(40, 41);
break;
case 8:
if ((0x5000000050L & l) != 0L && kind > 63)
kind = 63;
break;
case 10:
if ((0xffffffffefffffffL & l) != 0L)
jjCheckNAdd(11);
break;
case 12:
if (curChar == 92)
jjAddStates(42, 44);
break;
case 13:
if ((0x14404410000000L & l) != 0L)
jjCheckNAdd(11);
break;
case 19:
if ((0xffffffffefffffffL & l) != 0L)
jjCheckNAddStates(10, 12);
break;
case 20:
if (curChar == 92)
jjAddStates(45, 47);
break;
case 21:
if ((0x14404410000000L & l) != 0L)
jjCheckNAddStates(10, 12);
break;
case 33:
if ((0x2000000020L & l) != 0L)
jjAddStates(48, 49);
break;
case 37:
if ((0x2000000020L & l) != 0L)
jjAddStates(50, 51);
break;
case 41:
if ((0x2000000020L & l) != 0L)
jjAddStates(52, 53);
break;
case 45:
if ((0x100000001000000L & l) != 0L)
jjCheckNAdd(46);
break;
case 46:
if ((0x7e0000007eL & l) == 0L)
break;
if (kind > 59)
kind = 59;
jjCheckNAddTwoStates(46, 2);
break;
case 50:
jjAddStates(18, 20);
break;
case 55:
jjCheckNAddTwoStates(55, 56);
break;
case 57:
case 58:
jjCheckNAddTwoStates(58, 56);
break;
case 62:
jjCheckNAddTwoStates(62, 63);
break;
case 64:
case 65:
jjCheckNAddTwoStates(65, 63);
break;
default : break;
}
} while(i != startsAt);
}
else
{
int hiByte = (int)(curChar >> 8);
int i1 = hiByte >> 6;
long l1 = 1L << (hiByte & 077);
int i2 = (curChar & 0xff) >> 6;
long l2 = 1L << (curChar & 077);
MatchLoop: do
{
switch(jjstateSet[--i])
{
case 0:
case 28:
if (!jjCanMove_1(hiByte, i1, i2, l1, l2))
break;
if (kind > 67)
kind = 67;
jjCheckNAdd(28);
break;
case 10:
if (jjCanMove_0(hiByte, i1, i2, l1, l2))
jjstateSet[jjnewStateCnt++] = 11;
break;
case 19:
if (jjCanMove_0(hiByte, i1, i2, l1, l2))
jjAddStates(10, 12);
break;
case 50:
if (jjCanMove_0(hiByte, i1, i2, l1, l2))
jjAddStates(18, 20);
break;
case 55:
if (jjCanMove_0(hiByte, i1, i2, l1, l2))
jjCheckNAddTwoStates(55, 56);
break;
case 57:
case 58:
if (jjCanMove_0(hiByte, i1, i2, l1, l2))
jjCheckNAddTwoStates(58, 56);
break;
case 62:
if (jjCanMove_0(hiByte, i1, i2, l1, l2))
jjCheckNAddTwoStates(62, 63);
break;
case 64:
case 65:
if (jjCanMove_0(hiByte, i1, i2, l1, l2))
jjCheckNAddTwoStates(65, 63);
break;
default : break;
}
} while(i != startsAt);
}
if (kind != 0x7fffffff)
{
jjmatchedKind = kind;
jjmatchedPos = curPos;
kind = 0x7fffffff;
}
++curPos;
if ((i = jjnewStateCnt) == (startsAt = 67 - (jjnewStateCnt = startsAt)))
return curPos;
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) { return curPos; }
}
}
static final int[] jjnextStates = {
30, 31, 36, 37, 40, 41, 8, 49, 60, 61, 19, 20, 22, 10, 12, 45,
47, 2, 50, 51, 53, 4, 5, 8, 19, 20, 24, 22, 32, 33, 8, 40,
41, 8, 56, 57, 59, 63, 64, 66, 6, 7, 13, 14, 16, 21, 23, 25,
34, 35, 38, 39, 42, 43,
};
private static final boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2)
{
switch(hiByte)
{
case 0:
return ((jjbitVec2[i2] & l2) != 0L);
default :
if ((jjbitVec0[i1] & l1) != 0L)
return true;
return false;
}
}
private static final boolean jjCanMove_1(int hiByte, int i1, int i2, long l1, long l2)
{
switch(hiByte)
{
case 0:
return ((jjbitVec4[i2] & l2) != 0L);
case 48:
return ((jjbitVec5[i2] & l2) != 0L);
case 49:
return ((jjbitVec6[i2] & l2) != 0L);
case 51:
return ((jjbitVec7[i2] & l2) != 0L);
case 61:
return ((jjbitVec8[i2] & l2) != 0L);
default :
if ((jjbitVec3[i1] & l1) != 0L)
return true;
return false;
}
}
public static final String[] jjstrLiteralImages = {
"", null, null, null, null, null, null, null, null,
"\141\142\163\164\162\141\143\164", "\142\157\157\154\145\141\156", "\142\162\145\141\153", "\142\171\164\145",
"\143\141\163\145", "\143\141\164\143\150", "\143\150\141\162", "\143\154\141\163\163",
"\143\157\156\163\164", "\143\157\156\164\151\156\165\145", "\144\145\146\141\165\154\164",
"\144\157", "\144\157\165\142\154\145", "\145\154\163\145",
"\145\170\164\145\156\144\163", "\146\141\154\163\145", "\146\151\156\141\154",
"\146\151\156\141\154\154\171", "\146\154\157\141\164", "\146\157\162", "\147\157\164\157", "\151\146",
"\151\155\160\154\145\155\145\156\164\163", "\151\155\160\157\162\164", "\151\156\163\164\141\156\143\145\157\146",
"\151\156\164", "\151\156\164\145\162\146\141\143\145", "\154\157\156\147",
"\156\141\164\151\166\145", "\156\145\167", "\156\165\154\154", "\160\141\143\153\141\147\145",
"\160\162\151\166\141\164\145", "\160\162\157\164\145\143\164\145\144", "\160\165\142\154\151\143",
"\162\145\164\165\162\156", "\163\150\157\162\164", "\163\164\141\164\151\143", "\163\165\160\145\162",
"\163\167\151\164\143\150", "\163\171\156\143\150\162\157\156\151\172\145\144", "\164\150\151\163",
"\164\150\162\157\167", "\164\150\162\157\167\163", "\164\162\141\156\163\151\145\156\164",
"\164\162\165\145", "\164\162\171", "\166\157\151\144", "\166\157\154\141\164\151\154\145",
"\167\150\151\154\145", null, null, null, null, null, null, null, null, null, null, null, "\50",
"\51", "\173", "\175", "\133", "\135", "\73", "\54", "\56", "\75", "\76", "\74",
"\41", "\176", "\77", "\72", "\75\75", "\74\75", "\76\75", "\41\75", "\174\174",
"\46\46", "\53\53", "\55\55", "\53", "\55", "\52", "\57", "\46", "\174", "\136", "\45",
"\74\74", "\76\76", "\76\76\76", "\53\75", "\55\75", "\52\75", "\57\75", "\46\75",
"\174\75", "\136\75", "\45\75", "\74\74\75", "\76\76\75", "\76\76\76\75", };
public static final String[] lexStateNames = {
"DEFAULT",
};
static final long[] jjtoToken = {
0x8ffffffffffffe01L, 0xfffffffffffceL,
};
static final long[] jjtoSkip = {
0x1feL, 0x0L,
};
static final long[] jjtoSpecial = {
0x1c0L, 0x0L,
};
private ASCII_UCodeESC_CharStream input_stream;
private final int[] jjrounds = new int[67];
private final int[] jjstateSet = new int[134];
protected char curChar;
public ExpressionParserTokenManager(ASCII_UCodeESC_CharStream stream)
{
if (ASCII_UCodeESC_CharStream.staticFlag)
throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");
input_stream = stream;
}
public ExpressionParserTokenManager(ASCII_UCodeESC_CharStream stream, int lexState)
{
this(stream);
SwitchTo(lexState);
}
public void ReInit(ASCII_UCodeESC_CharStream stream)
{
jjmatchedPos = jjnewStateCnt = 0;
curLexState = defaultLexState;
input_stream = stream;
ReInitRounds();
}
private final void ReInitRounds()
{
int i;
jjround = 0x80000001;
for (i = 67; i-- > 0;)
jjrounds[i] = 0x80000000;
}
public void ReInit(ASCII_UCodeESC_CharStream stream, int lexState)
{
ReInit(stream);
SwitchTo(lexState);
}
public void SwitchTo(int lexState)
{
if (lexState >= 1 || lexState < 0)
throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);
else
curLexState = lexState;
}
private final Token jjFillToken()
{
Token t = Token.newToken(jjmatchedKind);
t.kind = jjmatchedKind;
String im = jjstrLiteralImages[jjmatchedKind];
t.image = (im == null) ? input_stream.GetImage() : im;
t.beginLine = input_stream.getBeginLine();
t.beginColumn = input_stream.getBeginColumn();
t.endLine = input_stream.getEndLine();
t.endColumn = input_stream.getEndColumn();
return t;
}
int curLexState = 0;
int defaultLexState = 0;
int jjnewStateCnt;
int jjround;
int jjmatchedPos;
int jjmatchedKind;
public final Token getNextToken()
{
int kind;
Token specialToken = null;
Token matchedToken;
int curPos = 0;
EOFLoop :
for (;;)
{
try
{
curChar = input_stream.BeginToken();
}
catch(java.io.IOException e)
{
jjmatchedKind = 0;
matchedToken = jjFillToken();
matchedToken.specialToken = specialToken;
return matchedToken;
}
try {
while (curChar <= 32 && (0x100003600L & (1L << curChar)) != 0L)
curChar = input_stream.BeginToken();
}
catch (java.io.IOException e1) { continue EOFLoop; }
jjmatchedKind = 0x7fffffff;
jjmatchedPos = 0;
curPos = jjMoveStringLiteralDfa0_0();
if (jjmatchedKind != 0x7fffffff)
{
if (jjmatchedPos + 1 < curPos)
input_stream.backup(curPos - jjmatchedPos - 1);
if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
{
matchedToken = jjFillToken();
matchedToken.specialToken = specialToken;
return matchedToken;
}
else
{
if ((jjtoSpecial[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
{
matchedToken = jjFillToken();
if (specialToken == null)
specialToken = matchedToken;
else
{
matchedToken.specialToken = specialToken;
specialToken = (specialToken.next = matchedToken);
}
}
continue EOFLoop;
}
}
int error_line = input_stream.getEndLine();
int error_column = input_stream.getEndColumn();
String error_after = null;
boolean EOFSeen = false;
try { input_stream.readChar(); input_stream.backup(1); }
catch (java.io.IOException e1) {
EOFSeen = true;
error_after = curPos <= 1 ? "" : input_stream.GetImage();
if (curChar == '\n' || curChar == '\r') {
error_line++;
error_column = 0;
}
else
error_column++;
}
if (!EOFSeen) {
input_stream.backup(1);
error_after = curPos <= 1 ? "" : input_stream.GetImage();
}
throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);
}
}
}
|
gpl-2.0
|
renevanpelt/CreateJS-boilerplate
|
phaser/player.js
|
2677
|
Player = function(game, x, y){
//Call parent constructor
Phaser.Sprite.call(this, game, x, y, 'player' );
game.add.existing(this);//Add player to game.
//Player Properties
this.facing = 'left';
this.isIdle = false;
this.jumpTimer = 0;
this.shootTimer = 0;
//Jump sound
this.jumpsound = game.add.audio('jump');
this.shootsound = game.add.audio('shoot');
//Physics
game.physics.enable(this, Phaser.Physics.ARCADE);
this.anchor.setTo(0.5, 0.5);
this.body.bounce.y = Player.bouncyness;
this.body.collideWorldBounds = true;
//Collision body size is different from sprite size.
this.body.setSize(8, 16, 0, 16);
//Animations
this.animations.add('left', [0, 1, 2, 3], 10, true);
this.animations.add('turn', [4], 20, true);
this.animations.add('right', [5, 6, 7, 8], 10, true);
}
Player.prototype = Object.create(Phaser.Sprite.prototype);
//Class Constants
Player.horizontalspeed = 400;
Player.jumpspeed = 550;
Player.bouncyness = 0; //between 0 - 1
Player.jumpCooldown = 750;
Player.shootCooldown = 300;
//Override update function to incorporate controls.
Player.prototype.update = function(){
this.body.velocity.x = 0; //Force stiff movement by setting velocity to 0 at begin of each update.
if (controls['left'].isDown)
{
this.body.velocity.x = -Player.horizontalspeed;
if (this.facing != 'left')
{
this.animations.play('left');
this.facing = 'left';
}
}
else if (controls['right'].isDown)
{
this.body.velocity.x = Player.horizontalspeed;
if (this.facing != 'right')
{
this.animations.play('right');
this.facing = 'right';
}
}
else
{
if (!this.isIdle)
{
this.animations.stop();
if (this.facing == 'left')
{
this.frame = 0;
}
else
{
this.frame = 5;
}
this.isIdle;
}
}
if (controls['jump'].isDown && this.body.onFloor() && game.time.now > this.jumpTimer)
{
this.body.velocity.y = -Player.jumpspeed;
this.jumpTimer = game.time.now + Player.jumpCooldown;
this.jumpsound.play();
}
//Shoot
if(controls['shoot'].isDown && game.time.now > this.shootTimer){
this.shoot(game);
this.shootTimer = game.time.now + Player.shootCooldown;
}
}
Player.prototype.shoot = function(game){
if(this.facing=='left'){
dir = 210;
}else{
var dir = -30;
}
var bullet = new Bullet(game, this.x, this.y, this, 700, dir);
this.shootsound.play();
}
|
gpl-2.0
|
danielbush/fez
|
public/upgrade/rm_fedora.php
|
5638
|
<?php
/**
* This script is intended to be run once, when the site owner is ready to switch off Fedora
* for good. A series of schema changes will be triggered, and Fedora-bypass functionality
* will be activated.
*
* Developers working on the Fedora phase-out should add any necessary functions to this file.
* In staging, you may find it useful to comment out anything you've already run, while testing
* new upgrade code in this script.
*
* I've like to thank my parents.
**/
set_time_limit(0);
include_once("../config.inc.php");
include_once(APP_INC_PATH . "class.search_key.php");
echo "WELCOME TO THE WORLD OF TOMORROW!\n\n";
$log = FezLog::get();
$db = DB_API::get();
////////////////////////////////////////////////////////////////////////////////////////////
// SHADOW TABLES
////////////////////////////////////////////////////////////////////////////////////////////
// 1.1 Create core search key shadow table
echo "Creating core search key shadow table ... ";
$stmt = "CREATE TABLE fez_record_search_key__shadow LIKE fez_record_search_key;";
try {
$db->exec($stmt);
} catch (Exception $ex) {
$log->err($ex);
return -1;
}
echo "done.\n";
// 1.2 Add stamp column to new shadow table
echo "Adding stamp column to new shadow table ... ";
$stmt = "ALTER TABLE fez_record_search_key__shadow ADD COLUMN `rek_stamp` datetime;";
try {
$db->exec($stmt);
} catch (Exception $ex) {
$log->err($ex);
return -1;
}
echo "done.\n";
// 1.3 Create non-core search key shadow tables
echo "Creating non-core search key shadow tables ... \n";
$searchKeys = Search_Key::getList();
foreach ($searchKeys as $sk) {
if ($sk['sek_relationship'] == '1') {
echo "* Shadowing " . $sk['sek_title_db'] . " table ... ";
$stmt = "CREATE TABLE fez_record_search_key_" . $sk['sek_title_db'] . "__shadow LIKE fez_record_search_key_" . $sk['sek_title_db'] . ";";
try {
$db->exec($stmt);
} catch (Exception $ex) {
$log->err($ex);
return -1;
}
echo "ok!\n";
}
}
echo "Done.\n\n";
// 1.4 Add stamp column to new shadow tables
$searchKeys = Search_Key::getList();
foreach ($searchKeys as $sk) {
if ($sk['sek_relationship'] == '1') {
echo "* Adding datestamp to " . $sk['sek_title_db'] . " ... ";
$stmt = "ALTER TABLE fez_record_search_key_" . $sk['sek_title_db'] . "__shadow ADD COLUMN `rek_" . $sk['sek_title_db'] . "_stamp` datetime;";
try {
$db->exec($stmt);
} catch (Exception $ex) {
$log->err($ex);
return -1;
}
echo "ok!\n";
}
}
echo "Done.\n\n";
// 1.5 Determine the maximum PID, save it to the new pid_index table.
$nextPID = Fedora_API::getNextPID(false);
$nextPIDParts = explode(":", $nextPID);
$nextPIDNumber = $nextPIDParts[1];
echo "Creating pid_index table ... ";
$stmt = "CREATE TABLE fez_pid_index (pid_number int(10) unsigned NOT NULL, PRIMARY KEY (pid_number));";
$db->exec($stmt);
echo "ok!\n";
echo "Fetching next PID from Fedora, and writing to pid_index table ... ";
$stmt = "INSERT INTO fez_pid_index (pid_number) values ('" . $nextPIDNumber . "');";
$db->exec($stmt);
echo "ok!\n";
// 1.6 Remove unique constraints from non-core shadow tables
$searchKeys = Search_Key::getList();
foreach ($searchKeys as $sk) {
if ($sk['sek_relationship'] == '1') {
echo "* Removing unique constraints from fez_record_search_key_" . $sk['sek_title_db'] . "__shadow ... ";
$stmt = "DROP INDEX unique_constraint ON fez_record_search_key_" . $sk['sek_title_db'] . "__shadow;";
try {
$db->exec($stmt);
} catch (Exception $ex) {
echo "No constraint to remove.\n";
}
echo "ok!\n";
}
}
// 1.7 Remove unique constraints from core shadow table
echo "* Removing unique constraint from fez_record_search_key__shadow ... ";
$stmt = "DROP INDEX unique_constraint ON fez_record_search_key__shadow;";
try {
$db->exec($stmt);
} catch (Exception $ex) {
echo "No constraint to remove.\n";
}
echo "ok!\n";
echo "* Removing primary key constraint from fez_record_search_key__shadow ... ";
$stmt = "ALTER TABLE fez_record_search_key__shadow DROP PRIMARY KEY;";
try {
$db->exec($stmt);
} catch (Exception $ex) {
echo "No constraint to remove.\n";
}
echo "ok!\n\n";
// 1.8 Add joint primary keys to shadow tables
echo "* Adding joint primary key to fez_record_search_key__shadow";
$stmt = "TRUNCATE TABLE fez_record_search_key__shadow;";
try {
$db->exec($stmt);
} catch (Exception $ex) {
echo " - ERROR - Could not truncate fez_record_search_key__shadow.\n";
}
$stmt = "ALTER TABLE fez_record_search_key__shadow DROP PRIMARY KEY, ADD PRIMARY KEY (rek_pid, rek_stamp);";
try {
$db->exec($stmt);
} catch (Exception $ex) {
echo " - ERROR - Could not add joint primary key to fez_record_search_key__shadow.\n";
}
echo "\n";
$searchKeys = Search_Key::getList();
foreach ($searchKeys as $sk) {
if ($sk['sek_relationship'] == '1') {
$stmt = "TRUNCATE TABLE fez_record_search_key_" . $sk['sek_title_db'] . "__shadow;";
try {
$db->exec($stmt);
} catch (Exception $ex) {
echo " - ERROR - Could not truncate " . $sk['sek_title_db']. "\n";
}
echo "* Adding joint primary key to fez_record_search_key_" . $sk['sek_title_db'] . "__shadow";
$stmt = "ALTER TABLE fez_record_search_key_" . $sk['sek_title_db'] . "__shadow ADD UNIQUE KEY (rek_" . $sk['sek_title_db'] . "_pid, rek_" . $sk['sek_title_db'] . "_stamp);";
try {
$db->exec($stmt);
} catch (Exception $ex) {
echo " - FAILED\n";
}
echo "\n";
}
}
// Other steps as necessary.
exit ("\n\nExiting Fedora upgrade script.\n");
?>
|
gpl-2.0
|
CruzR/wc3lib
|
src/mdlx/ribbonemitter.cpp
|
5997
|
/***************************************************************************
* Copyright (C) 2009 by Tamino Dauth *
* tamino@cdauth.eu *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "ribbonemitter.hpp"
#include "mdlxtranslations.hpp"
#include "mdlxrotations.hpp"
#include "mdlxscalings.hpp"
#include "ribbonemittervisibilities.hpp"
#include "ribbonemitterheightsabove.hpp"
#include "ribbonemitterheightsbelow.hpp"
#include "../utilities.hpp"
#include "../vertex.hpp"
namespace wc3lib
{
namespace mdlx
{
RibbonEmitter::RibbonEmitter(class RibbonEmitters *ribbonEmitters) : Node(ribbonEmitters->mdlx()), GroupMdxBlockMember(ribbonEmitters, "RibbonEmitter"), m_visibilities(new RibbonEmitterVisibilities(this)), m_heightsAbove(new RibbonEmitterHeightsAbove(this)), m_heightsBelow(new RibbonEmitterHeightsBelow(this))
{
}
RibbonEmitter::~RibbonEmitter()
{
delete this->m_visibilities;
delete this->m_heightsAbove;
delete this->m_heightsBelow;
}
std::streamsize RibbonEmitter::readMdl(istream &istream) throw (class Exception)
{
return 0;
}
std::streamsize RibbonEmitter::writeMdl(ostream &ostream) const throw (class Exception)
{
std::streamsize size = 0;
writeMdlBlock(ostream, size, "RibbonEmitter", this->name(), 0, true);
size += Node::writeMdl(ostream);
if (!this->heightsAbove()->properties().empty())
size += this->heightsAbove()->writeMdl(ostream);
else
writeMdlStaticValueProperty(ostream, size, "HeightAbove", this->heightAboveValue());
if (!this->heightsBelow()->properties().empty())
size += this->heightsBelow()->writeMdl(ostream);
else
writeMdlStaticValueProperty(ostream, size, "HeightBelow", this->heightBelowValue());
writeMdlStaticVectorProperty(ostream, size, "Color", wc3lib::Vertex(colorRed(), colorGreen(), colorBlue()));
writeMdlStaticValueProperty(ostream, size, "TextureSlot", this->unknown0());
if (!this->visibilities()->properties().empty())
size += this->visibilities()->writeMdl(ostream);
else
writeMdlStaticValueProperty(ostream, size, "Alpha", this->alpha());
writeMdlValueProperty(ostream, size, "EmissionRate", this->emissionRate());
writeMdlValueProperty(ostream, size, "LifeSpan", this->lifeSpan());
if (this->gravity() != 0.0)
writeMdlValueProperty(ostream, size, "Gravity", this->gravity());
writeMdlValueProperty(ostream, size, "Rows", this->rows());
writeMdlValueProperty(ostream, size, "Columns", this->columns());
writeMdlValueProperty(ostream, size, "MaterialID", this->materialId());
writeMdlBlockConclusion(ostream, size);
return size;
}
std::streamsize RibbonEmitter::readMdx(istream &istream) throw (class Exception)
{
std::streamsize size = 0;
long32 nbytesi = 0;
wc3lib::read(istream, nbytesi, size);
size += Node::readMdx(istream);
wc3lib::read(istream, this->m_heightAboveValue, size);
wc3lib::read(istream, this->m_heightBelowValue, size);
wc3lib::read(istream, this->m_alpha, size);
wc3lib::read(istream, this->m_colorRed, size);
wc3lib::read(istream, this->m_colorGreen, size);
wc3lib::read(istream, this->m_colorBlue, size);
wc3lib::read(istream, this->m_lifeSpan, size);
wc3lib::read(istream, this->m_unknown0, size);
wc3lib::read(istream, this->m_emissionRate, size);
wc3lib::read(istream, this->m_rows, size);
wc3lib::read(istream, this->m_columns, size);
wc3lib::read(istream, this->m_materialId, size);
wc3lib::read(istream, this->m_gravity, size);
size += this->m_visibilities->readMdx(istream);
size += this->m_heightsAbove->readMdx(istream);
size += this->m_heightsBelow->readMdx(istream);
return size;
}
std::streamsize RibbonEmitter::writeMdx(ostream &ostream) const throw (class Exception)
{
std::streamsize size = 0;
std::streampos position;
skipByteCount<long32>(ostream, position);
size += Node::writeMdx(ostream);
wc3lib::write(ostream, this->m_heightAboveValue, size);
wc3lib::write(ostream, this->m_heightBelowValue, size);
wc3lib::write(ostream, this->m_alpha, size);
wc3lib::write(ostream, this->m_colorRed, size);
wc3lib::write(ostream, this->m_colorGreen, size);
wc3lib::write(ostream, this->m_colorBlue, size);
wc3lib::write(ostream, this->m_lifeSpan, size);
wc3lib::write(ostream, this->m_unknown0, size);
wc3lib::write(ostream, this->m_emissionRate, size);
wc3lib::write(ostream, this->m_rows, size);
wc3lib::write(ostream, this->m_columns, size);
wc3lib::write(ostream, this->m_materialId, size);
wc3lib::write(ostream, this->m_gravity, size);
size += this->m_visibilities->writeMdx(ostream);
size += this->m_heightsAbove->writeMdx(ostream);
size += this->m_heightsBelow->writeMdx(ostream);
const long32 nbytesi = boost::numeric_cast<long32>(size);
writeByteCount(ostream, nbytesi, position, size, true);
return size;
}
}
}
|
gpl-2.0
|
Dilink/ImageManager
|
src/fr/Dilink/src/panels/PanelLeft.java
|
332
|
package fr.Dilink.src.panels;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JPanel;
public class PanelLeft extends JPanel
{
private static final long serialVersionUID = 1L;
public PanelLeft() {
this.setLayout(new GridLayout(1, 1));
this.add(new PanelListeImages(), BorderLayout.WEST);
}
}
|
gpl-2.0
|
imleon/qdrealestate
|
src/main/java/com/lostleon/qdrealestate/bean/DailyMetrics.java
|
1863
|
package com.lostleon.qdrealestate.bean;
import java.util.Date;
import com.lostleon.qdrealestate.util.Util;
/**
* 每天每个Project的数据都记录成一个本类的对象
*
* @author lostleon@gmail.com
*
*/
public class DailyMetrics {
/* 日期 */
private Date date;
/* 截止到当天24:00的总成交面积 */
private float totalSoldSize;
/* 截止到当天24:00的总成交套数 */
private int totalSoldNum;
/* 截止到当天24:00的均价 */
private float totalAvgPrice;
/* 当天的成交面积 */
private float todaySoldSize;
/* 当天的成交套数 */
private int todaySoldNum;
/* 当天的成交均价 */
private float todayAvgPrice;
public DailyMetrics(Date d, float totalSoldSize, int totalSoldNum,
float totalAvgPrice, float todaySoldSize, int todaySoldNum,
float todayAvgPrice) {
this.date = d;
this.totalSoldSize = totalSoldSize;
this.totalSoldNum = totalSoldNum;
this.totalAvgPrice = totalAvgPrice;
this.todaySoldSize = todaySoldSize;
this.todaySoldNum = todaySoldNum;
this.todayAvgPrice = todayAvgPrice;
}
public float getTotalAvgPrice() {
return this.totalAvgPrice;
}
public float getTodayAvgPrice() {
return this.todayAvgPrice;
}
public Date getDate() {
return this.date;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(Util.date2str(date)).append("|").append(totalSoldSize)
.append("|").append(totalSoldNum).append("|")
.append(totalAvgPrice).append("|").append(totalSoldSize)
.append("|").append(totalSoldNum).append("|")
.append(todayAvgPrice);
return sb.toString();
}
}
|
gpl-2.0
|
taipeicity/i-voting
|
administrator/components/com_surveyforce/surveyforce.php
|
1709
|
<?php
/**
* @package Surveyforce
* @version 1.0-modified
* @copyright JooPlce Team, 臺北市政府資訊局, Copyright (C) 2016. All rights reserved.
* @license GPL-2.0+
* @author JooPlace Team, 臺北市政府資訊局- http://doit.gov.taipei/
*/
//TODO: Plugins , "Hide this question if" option
//TODO: Answers:
/*
Ranking DropDown
Ranking Drag'AND'Drop
*/
defined('_JEXEC') or die('Restricted access');
JLoader::register('SurveyforceHelper', JPATH_COMPONENT_ADMINISTRATOR . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'surveyforce.php');
$GLOBALS['survey_version'] = '3.1.1.003';
global $survey_version;
if (!defined('_SURVEY_FORCE_COMP_NAME'))
define('_SURVEY_FORCE_COMP_NAME', JText::_('COM_SURVEYFORCE_SURVEYFORCE_DELUXE_VER') . $survey_version);
if (!defined('_SEL_CATEGORY'))
define('_SEL_CATEGORY', '- ' . JText::_('COM_SURVEYFORCE_SELECT_CATEGORY') . ' -');
if (!defined('_CMN_NEW_ITEM_FIRST'))
define('_CMN_NEW_ITEM_FIRST', JText::_('COM_SURVEYFORCE_NEW_ITEMS_DEFAULT_TO_THE_FIRST_PLACE'));
if (!defined('_PDF_GENERATED'))
define('_PDF_GENERATED', JText::_('COM_SURVEYFORCE_GENERATED'));
if (!defined('_CURRENT_SERVER_TIME_FORMAT'))
define('_CURRENT_SERVER_TIME_FORMAT', '%Y %m %d %H %M %S');
if (!defined('_CURRENT_SERVER_TIME'))
define('_CURRENT_SERVER_TIME', JHtml::_('date', time(), 'Y-m-d H:i'));
if (!defined('_PN_DISPLAY_NR'))
define('_PN_DISPLAY_NR', JText::_('COM_SURVEYFORCE_DISPLAY'));
$controller = JControllerLegacy::getInstance('Surveyforce');
$controller->execute(JFactory::getApplication()->input->getCmd('task'));
$controller->redirect();
|
gpl-2.0
|
Pengfei-Gao/source-Insight-3-for-centos7
|
SourceInsight3/NetFramework/ArrayLiteral.cs
|
270
|
public class ArrayLiteral : AST
{
// Constructors
public ArrayLiteral(Context context, ASTList elements) {}
// Methods
public Type GetType() {}
public virtual string ToString() {}
public virtual bool Equals(object obj) {}
public virtual int GetHashCode() {}
}
|
gpl-2.0
|
facebookexperimental/eden
|
eden/mononoke/manifest/src/derive_batch.rs
|
26840
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::{Entry, LeafInfo, Manifest, PathTree, TreeInfo};
use anyhow::{anyhow, Context, Error};
use blobstore::StoreLoadable;
use cloned::cloned;
use context::CoreContext;
use futures::{Future, FutureExt};
use mononoke_types::{ChangesetId, MPath, MPathElement};
use std::{collections::BTreeMap, fmt, hash::Hash, sync::Arc};
pub struct ManifestChanges<Leaf> {
pub cs_id: ChangesetId,
pub changes: Vec<(MPath, Option<Leaf>)>,
}
// Function that can derive manifests for a "simple" stack of commits. But what does "simple" mean?
// In this case "simple" means:
// 1) There are no merges i.e. we get just a linear stack of commits
// (`changes` parameter should be sorted from ancestors to descendant)
// 2) Paths that commits modify should not be prefixes of each other i.e.
// stack shouldn't have file changes ("dir/A" => "dir") and ("dir" => "file").
// The exception applies only to changes that were modified in the same commit
// i.e. if a single commit has ("dir" => None) and ("dir/A" => "content") then this
// commit can be derived by derive_manifests_for_simple_stack_of_commits.
#[allow(unused)]
pub async fn derive_manifests_for_simple_stack_of_commits<
'caller,
TreeId,
LeafId,
IntermediateLeafId,
Leaf,
T,
TFut,
L,
LFut,
Ctx,
Store,
>(
ctx: CoreContext,
store: Store,
parent: Option<TreeId>,
changes: Vec<ManifestChanges<Leaf>>,
create_tree: T,
create_leaf: L,
) -> Result<BTreeMap<ChangesetId, TreeId>, Error>
where
Store: Sync + Send + Clone + 'static,
LeafId: Send + Clone + Eq + Hash + fmt::Debug + 'static + Sync,
IntermediateLeafId: Clone + Send + From<LeafId> + 'static + Sync,
Leaf: Send + 'static,
TreeId: StoreLoadable<Store> + Clone + Eq + Hash + fmt::Debug + Send + Sync + 'static,
TreeId::Value: Manifest<TreeId = TreeId, LeafId = LeafId> + Sync,
<TreeId as StoreLoadable<Store>>::Value: Send,
T: Fn(TreeInfo<TreeId, IntermediateLeafId, Ctx>, ChangesetId) -> TFut + Send + Sync + 'static,
TFut: Future<Output = Result<(Ctx, TreeId), Error>> + Send + 'caller,
L: Fn(LeafInfo<IntermediateLeafId, Leaf>, ChangesetId) -> LFut + Send + Sync + 'static,
LFut: Future<Output = Result<(Ctx, IntermediateLeafId), Error>> + Send + 'caller,
Ctx: Clone + Send + Sync + 'static,
{
Deriver {
ctx,
store,
parent,
changes,
create_tree,
create_leaf,
_marker: std::marker::PhantomData,
}
.derive()
.await
}
// Stack of changes for a single file path - it can be either a tree or a leaf
struct EntryStack<TreeId, LeafId, Ctx> {
parent: Option<Entry<TreeId, LeafId>>,
values: Vec<(ChangesetId, Option<Ctx>, Option<Entry<TreeId, LeafId>>)>,
}
// This struct is not necessary, it just exists so that we don't need to repeat
// a long list of generic restrictions for each function
struct Deriver<TreeId, Leaf, IntermediateLeafId, T, L, Store> {
ctx: CoreContext,
store: Store,
parent: Option<TreeId>,
changes: Vec<ManifestChanges<Leaf>>,
create_tree: T,
create_leaf: L,
_marker: std::marker::PhantomData<IntermediateLeafId>,
}
fn convert_to_intermediate_entry<TreeId, LeafId, IntermediateLeafId>(
e: Entry<TreeId, LeafId>,
) -> Entry<TreeId, IntermediateLeafId>
where
IntermediateLeafId: From<LeafId>,
{
match e {
Entry::Tree(t) => Entry::Tree(t),
Entry::Leaf(l) => Entry::Leaf(l.into()),
}
}
impl<'caller, TreeId, LeafId, IntermediateLeafId, Leaf, T, TFut, L, LFut, Ctx, Store>
Deriver<TreeId, Leaf, IntermediateLeafId, T, L, Store>
where
Store: Sync + Send + Clone + 'static,
LeafId: Send + Clone + Eq + Hash + fmt::Debug + 'static + Sync,
IntermediateLeafId: Clone + Send + From<LeafId> + 'static + Sync,
Leaf: Send + 'static,
TreeId: StoreLoadable<Store> + Clone + Eq + Hash + fmt::Debug + Send + Sync + 'static,
TreeId::Value: Manifest<TreeId = TreeId, LeafId = LeafId> + Sync,
<TreeId as StoreLoadable<Store>>::Value: Send,
T: Fn(TreeInfo<TreeId, IntermediateLeafId, Ctx>, ChangesetId) -> TFut + Send + Sync + 'static,
TFut: Future<Output = Result<(Ctx, TreeId), Error>> + Send + 'caller,
L: Fn(LeafInfo<IntermediateLeafId, Leaf>, ChangesetId) -> LFut + Send + Sync + 'static,
LFut: Future<Output = Result<(Ctx, IntermediateLeafId), Error>> + Send + 'caller,
Ctx: Clone + Send + Sync + 'static,
{
async fn derive(self) -> Result<BTreeMap<ChangesetId, TreeId>, Error> {
let Deriver {
ctx,
store,
parent,
changes,
create_tree,
create_leaf,
..
} = self;
// This is a tree of paths, and for each path we store a list of
// (ChangesetId, Option<Leaf>) i.e. for each path we store
// changesets where it was modified and what this modification was.
// Each list of modifications is ordered in the same order as the commits
// in the stack.
let mut path_tree = PathTree::<Vec<(ChangesetId, Option<Leaf>)>>::default();
let mut stack_of_commits = vec![];
for mf_changes in changes {
for (path, leaf) in mf_changes.changes {
path_tree.insert_and_merge(Some(path), (mf_changes.cs_id, leaf));
}
stack_of_commits.push(mf_changes.cs_id);
}
struct UnfoldState<TreeId, LeafId, Leaf> {
path: Option<MPath>,
name: Option<MPathElement>,
parent: Option<Entry<TreeId, LeafId>>,
path_tree: PathTree<Vec<(ChangesetId, Leaf)>>,
}
enum FoldState<TreeId, LeafId, Leaf> {
Reuse(
Option<MPath>,
Option<MPathElement>,
Option<Entry<TreeId, LeafId>>,
),
CreateLeaves(
Option<MPath>,
MPathElement,
Option<Entry<TreeId, LeafId>>,
Vec<Leaf>,
),
CreateTrees(
Option<MPath>,
Option<MPathElement>,
Option<Entry<TreeId, LeafId>>,
// We might have a single file deletion, this field represents it
Option<ChangesetId>,
),
}
let stack_of_commits = Arc::new(stack_of_commits);
let (_, entry_stack) = bounded_traversal::bounded_traversal(
256,
UnfoldState {
path: None,
name: None,
parent: parent.clone().map(Entry::Tree),
path_tree,
},
// Unfold - during this traversal we visit all changed paths and decide what to do with them
{
cloned!(ctx, store);
move |
UnfoldState {
path,
name,
parent,
path_tree,
},
| {
cloned!(ctx, store);
async move {
let PathTree {
value: changes,
subentries,
} = path_tree;
if !changes.is_empty() && subentries.is_empty() {
// We have a stack of changes for a given leaf
let name = name.ok_or_else(|| anyhow!("unexpected empty path for leaf"))?;
Ok((FoldState::CreateLeaves(path, name, parent, changes), vec![]))
} else if !subentries.is_empty() {
// We need to recurse now - recurse into all parent entries and all subentries
let maybe_file_deletion = if !changes.is_empty() {
// So a file was changed and also some other subdirectories were
// changed. In most cases that would just mean that we are not dealing
// with the simple stack and we should just error out, however there's
// one exception. If a file was replaced with a directory in a single
// commit then we might have both deletion of a file and a few
// subentries with the same prefix (e.g. "R file; A file/subentry").
// Let's check if that's indeed the case.
let mut only_single_deletion = None;
if changes.len() == 1 {
let (cs_id, file_change) = &changes[0];
if file_change.is_none() {
only_single_deletion = Some(*cs_id);
}
}
if only_single_deletion.is_none() {
return Err(anyhow!(
"unsupported stack derive - {:?} is a prefix of other paths",
path
));
}
only_single_deletion
} else {
None
};
let mut deps: BTreeMap<MPathElement, _> = Default::default();
if let Some(Entry::Tree(tree_id)) = &parent {
let mf = tree_id.load(&ctx, &store).await?;
for (name, entry) in mf.list() {
let subentry =
deps.entry(name.clone()).or_insert_with(|| UnfoldState {
path: Some(MPath::join_opt_element(path.as_ref(), &name)),
name: Some(name),
parent: Default::default(),
path_tree: Default::default(),
});
subentry.parent = Some(entry);
}
}
for (name, path_tree) in subentries {
let subentry =
deps.entry(name.clone()).or_insert_with(|| UnfoldState {
path: Some(MPath::join_opt_element(path.as_ref(), &name)),
name: Some(name),
parent: Default::default(),
path_tree: Default::default(),
});
subentry.path_tree = path_tree;
}
let deps = deps.into_iter().map(|(_name, dep)| dep).collect();
Ok((
FoldState::CreateTrees(path, name, parent, maybe_file_deletion),
deps,
))
} else {
if path.is_none() && parent.is_none() {
// This is a weird case - we got an empty commit with no parent.
// In that case we want to create an empty root tree for this commit
Ok((FoldState::CreateTrees(None, None, None, None), vec![]))
} else {
// No changes, no subentries - just reuse the entry
Ok((FoldState::Reuse(path, name, parent.map(convert_to_intermediate_entry)), vec![]))
}
}
}
.boxed()
}
},
// Fold - actually create the entries
{
let create_leaf = Arc::new(create_leaf);
let create_tree = Arc::new(create_tree);
cloned!(ctx, store, stack_of_commits);
move |fold_state, subentries| {
cloned!(ctx, create_leaf, create_tree, stack_of_commits, store);
async move {
let subentries: BTreeMap<MPathElement, _> = subentries
.filter_map(|(maybe_path, val): (Option<_>, _)| {
maybe_path.map(|path| (path, val))
})
.collect();
match fold_state {
FoldState::CreateLeaves(path, name, parent, leaves) => {
if !subentries.is_empty() {
anyhow::bail!(
"Can't create entries for {:?} - have unexpected subentries",
path,
);
}
let path = path.clone().context("unexpected empty path for leaf")?;
let entry_stack = Self::create_leaves(
&ctx,
path,
parent.map(convert_to_intermediate_entry),
leaves,
create_leaf,
create_tree,
store,
)
.await?;
Ok((Some(name), entry_stack))
}
FoldState::CreateTrees(path, name, parent, maybe_file_deletion) => {
let entry_stack = Self::create_trees(
path,
parent.map(convert_to_intermediate_entry),
subentries,
create_tree,
stack_of_commits,
maybe_file_deletion,
)
.await?;
Ok((name, entry_stack))
}
FoldState::Reuse(_, name, maybe_entry) => {
let entry_stack = EntryStack {
parent: maybe_entry.map(convert_to_intermediate_entry),
values: vec![],
};
Ok((name, entry_stack))
}
}
}
.boxed()
}
},
)
.await?;
let derived: BTreeMap<_, _> = entry_stack
.values
.into_iter()
.filter_map(|(cs_id, _, maybe_entry)| {
let maybe_tree_id = match maybe_entry {
Some(entry) => Some(entry.into_tree()?),
None => None,
};
Some((cs_id, maybe_tree_id))
})
.collect();
let mut parent = parent;
// Make sure that we have entries for every commit
let mut res = BTreeMap::new();
for cs_id in stack_of_commits.iter() {
let new_mf_id = match derived.get(cs_id) {
Some(maybe_tree_id) => {
parent = maybe_tree_id.clone();
maybe_tree_id.clone()
}
None => parent.clone(),
};
let new_mf_id =
new_mf_id.ok_or_else(|| anyhow!("unexpected empty manifest for {}", cs_id))?;
res.insert(*cs_id, new_mf_id);
}
Ok(res)
}
async fn create_leaves(
ctx: &CoreContext,
path: MPath,
parent: Option<Entry<TreeId, IntermediateLeafId>>,
changes: Vec<(ChangesetId, Option<Leaf>)>,
create_leaf: Arc<L>,
create_tree: Arc<T>,
store: Store,
) -> Result<EntryStack<TreeId, IntermediateLeafId, Ctx>, Error> {
let mut entry_stack = EntryStack {
parent: parent.clone(),
values: vec![],
};
let mut parent = parent;
for (cs_id, maybe_leaf) in changes {
match maybe_leaf {
Some(leaf) => {
let (upload_ctx, leaf_id) = create_leaf(
LeafInfo {
leaf: Some(leaf),
path: path.clone(),
// Note that a parent can be a tree here - in that case
// directory is implicitly deleted and replaced with a file
parents: parent.and_then(Entry::into_leaf).into_iter().collect(),
},
cs_id,
)
.await?;
entry_stack.values.push((
cs_id,
Some(upload_ctx),
Some(Entry::Leaf(leaf_id.clone())),
));
parent = Some(Entry::Leaf(leaf_id));
}
None => {
if let Some(Entry::Tree(tree_id)) = parent {
// This is a weird logic in derive_manifest()
// If file is deleted and parent entry is a tree then
// we ignore the deletion and create a new object with
// existing parent tree entry as a parent.
// This is strange, but it's worth replicating what we have
// derive_manifest()
let parent_mf = tree_id.load(&ctx, &store).await?;
let subentries = parent_mf
.list()
.map(|(path, entry)| {
(path, (None, convert_to_intermediate_entry(entry)))
})
.collect();
let (upload_ctx, tree_id) = create_tree(
TreeInfo {
path: Some(path.clone()),
parents: vec![tree_id],
subentries,
},
cs_id,
)
.await?;
entry_stack.values.push((
cs_id,
Some(upload_ctx),
Some(Entry::Tree(tree_id.clone())),
));
parent = Some(Entry::Tree(tree_id));
} else {
entry_stack.values.push((cs_id, None, None));
parent = None;
}
}
}
}
Ok(entry_stack)
}
async fn create_trees(
path: Option<MPath>,
parent: Option<Entry<TreeId, IntermediateLeafId>>,
stack_sub_entries: BTreeMap<MPathElement, EntryStack<TreeId, IntermediateLeafId, Ctx>>,
create_tree: Arc<T>,
stack_of_commits: Arc<Vec<ChangesetId>>,
maybe_file_deletion: Option<ChangesetId>,
) -> Result<EntryStack<TreeId, IntermediateLeafId, Ctx>, Error> {
// These are all sub entries for the commit we are currently processing.
// We start with parent entries, and then apply delta changes on top.
let mut cur_sub_entries: BTreeMap<MPathElement, (Option<Ctx>, Entry<_, _>)> =
BTreeMap::new();
// `stack_sub_entries` is a mapping from (name -> list of changes).
// We want to pivot it into (Changeset id -> Map(name, entry)),
// so that we know how tree directory changed
let mut delta_sub_entries: BTreeMap<ChangesetId, BTreeMap<_, _>> = BTreeMap::new();
for (path_elem, entry_stack) in stack_sub_entries {
let EntryStack { values, parent } = entry_stack;
if let Some(parent) = parent {
cur_sub_entries.insert(path_elem.clone(), (None, parent));
}
for (cs_id, ctx, maybe_entry) in values {
delta_sub_entries
.entry(cs_id)
.or_default()
.insert(path_elem.clone(), (ctx, maybe_entry));
}
}
// Before we start with the actual logic of creating trees we have one corner case
// to deal with. A file can be replaced with a directory in a single commit. In that
// case we have a maybe_file_deletion set to the the commit where the file was deleted,
// and a parent should either be non-existent or a leaf. A case like that can only be
// the first in the stack of changes this tree because we use a simple stack.
// So let's check these two things if file deletion is set:
// 1) Check that parent is a leaf or non-existent
// 2) Check that deletion is the first change
match (&parent, maybe_file_deletion) {
(Some(Entry::Leaf(_)), Some(deletion_cs_id)) | (None, Some(deletion_cs_id)) => {
for cs_id in stack_of_commits.iter() {
if cs_id == &deletion_cs_id {
// File is deleted in this commit, and no previous commits had subentries.
// That's good, we can exit
break;
}
// There are subentries before the deletion - we don't support this, so
// let's exit.
if delta_sub_entries.contains_key(cs_id) {
return Err(anyhow!(
"Unexpected file deletion of {:?} in {}",
path,
deletion_cs_id
));
}
}
}
(Some(Entry::Tree(_)), Some(deletion_cs_id)) => {
// Something is odd here - parent is a tree but we try to delete it as a file
return Err(anyhow!(
"Unexpected file deletion of {:?} in {}",
path,
deletion_cs_id
));
}
(Some(Entry::Leaf(_)), None) => {
return Err(anyhow!("Unexpected file parent for a directory {:?}", path,));
}
(Some(Entry::Tree(_)), None) | (None, None) => {
// Simple cases, nothing to do here
}
};
let mut entry_stack = EntryStack {
values: vec![],
parent: parent.clone(),
};
let mut parent = parent.and_then(|e| e.into_tree());
for cs_id in stack_of_commits.iter() {
let delta = match delta_sub_entries.remove(cs_id) {
Some(delta) => delta,
None => {
// This directory hasn't been changed in `cs_id`, just continue...
if path.is_none() && cur_sub_entries.is_empty() && parent.is_none() {
// ... unless it's an empty root tree with no parents.
// That means we have an empty commit with no parents,
// and for that case let's create a new root object to match what
// derive_manifest() function is doing.
let (ctx, tree_id) = create_tree(
TreeInfo {
path: path.clone(),
parents: parent.clone().into_iter().collect(),
subentries: Default::default(),
},
*cs_id,
)
.await?;
parent = Some(tree_id.clone());
entry_stack
.values
.push((*cs_id, Some(ctx), Some(Entry::Tree(tree_id))));
}
continue;
}
};
// Let's apply delta to get the subentries for a given commit
for (path_elem, (ctx, maybe_entry)) in delta {
match maybe_entry {
Some(entry) => {
cur_sub_entries.insert(path_elem, (ctx, entry));
}
None => {
cur_sub_entries.remove(&path_elem);
}
}
}
// Finally let's create or delete the directory
if !cur_sub_entries.is_empty() {
let (ctx, tree_id) = create_tree(
TreeInfo {
path: path.clone(),
parents: parent.clone().into_iter().collect(),
subentries: cur_sub_entries.clone(),
},
*cs_id,
)
.await?;
parent = Some(tree_id.clone());
entry_stack
.values
.push((*cs_id, Some(ctx), Some(Entry::Tree(tree_id))));
} else {
if path.is_none() {
// Everything is deleted in the repo - let's create a new root
// object
let (ctx, tree_id) = create_tree(
TreeInfo {
path: path.clone(),
parents: parent.clone().into_iter().collect(),
subentries: Default::default(),
},
*cs_id,
)
.await?;
parent = Some(tree_id.clone());
entry_stack
.values
.push((*cs_id, Some(ctx), Some(Entry::Tree(tree_id))));
} else {
parent = None;
entry_stack.values.push((*cs_id, None, None));
}
}
}
Ok(entry_stack)
}
}
|
gpl-2.0
|
dangpin/cane
|
src/main/java/com/ebao/cane/ls/service/table/TAddressJpService.java
|
1792
|
package com.ebao.cane.ls.service.table;
import org.apache.commons.lang3.StringUtils;
import com.ebao.cane.ks.service.DMAddressService;
import com.ebao.cane.ks.service.DMService;
import com.ebao.cane.ks.table.DMAddress;
import com.ebao.cane.ls.object.table.TAddressJp;
public class TAddressJpService extends
TAbstractIteratorService<DMAddress, TAddressJp> {
private DMAddressService dmAddressService;
private TAddressService tAddressService;
@Override
public int compare(DMAddress o1, DMAddress o2) {
return tAddressService.compare(o1, o2);
}
@Override
protected TAddressJp convert(DMAddress dm) {
TAddressJp tAddressJp = new TAddressJp();
tAddressJp
.setAddressId(tAddressService.getByKSTable(dm).getAddressId());
tAddressJp.setAddress1Alias(dm.getFkAddress1Alias());
tAddressJp.setAddress2Alias(StringUtils.defaultIfBlank(
dm.getFkAddress2Alias(), null));
tAddressJp.setAddress3Alias(null);
tAddressJp.setAddress4Alias(null);
tAddressJp.setAddress5Alias(null);
tAddressJp.setAddress6Alias(null);
tAddressJp.setAddress7Alias(null);
tAddressJp.setPhone(dm.getFkPhone());
tAddressJp.setDisableReason(dm.getFkDisableReason());
tAddressJp.setDisableCargo(dm.getFkDisableCargo());
return tAddressJp;
}
public DMAddressService getDmAddressService() {
return dmAddressService;
}
public void setDmAddressService(DMAddressService dmAddressService) {
this.dmAddressService = dmAddressService;
}
public TAddressService gettAddressService() {
return tAddressService;
}
public void settAddressService(TAddressService tAddressService) {
this.tAddressService = tAddressService;
}
@Override
protected DMService<DMAddress> getDmService() {
return dmAddressService;
}
}
|
gpl-2.0
|
FrodeSolheim/fs-uae-launcher
|
amitools/vamos/lib/VamosTestLibrary.py
|
1571
|
from amitools.vamos.machine.regs import *
from amitools.vamos.libcore import LibImpl
from amitools.vamos.error import *
class VamosTestLibrary(LibImpl):
def setup_lib(self, ctx, base_addr):
self.cnt = 0
def finish_lib(self, ctx):
self.cnt = None
def open_lib(self, ctx, open_cnt):
self.cnt = open_cnt
def close_lib(self, ctx, open_cnt):
self.cnt = open_cnt
def get_version(self):
return 23
def get_cnt(self):
return self.cnt
def ignore_func(self):
"""a lower-case function that is ignored"""
pass
def InvalidFunc(self, ctx):
"""a test function that does not exist in the .fd file"""
pass
def PrintHello(self, ctx):
print("VamosTest: PrintHello()")
return 0
def PrintString(self, ctx):
str_addr = ctx.cpu.r_reg(REG_A0)
txt = ctx.mem.r_cstr(str_addr)
print("VamosTest: PrintString(%s)", txt)
return 0
def Add(self, ctx):
a = ctx.cpu.r_reg(REG_D0)
b = ctx.cpu.r_reg(REG_D1)
return a + b
def Swap(self, ctx):
a = ctx.cpu.r_reg(REG_D0)
b = ctx.cpu.r_reg(REG_D1)
return b, a
def RaiseError(self, ctx):
str_addr = ctx.cpu.r_reg(REG_A0)
txt = ctx.mem.r_cstr(str_addr)
if txt == "RuntimeError":
e = RuntimeError("VamosTest")
elif txt == "VamosInternalError":
e = VamosInternalError("VamosTest")
elif txt == "InvalidMemoryAccessError":
e = InvalidMemoryAccessError('R', 2, 0x200)
else:
print("VamosTest: Invalid Error:", txt)
return
print("VamosTest: raise", e.__class__.__name__)
raise e
|
gpl-2.0
|
ajmaurya99/rtPanel
|
wp-content/plugins/ajax-load-more/admin/views/licenses.php
|
19792
|
<div class="admin ajax-load-more" id="alm-licenses">
<div class="wrap">
<div class="header-wrap">
<h2><?php echo ALM_TITLE; ?>: <strong><?php _e('Licenses', ALM_NAME); ?></strong></h2>
<p><?php _e('Enter your license keys to enable automatic updates for <a href="admin.php?page=ajax-load-more-add-ons">ALM Add-ons</a>.', ALM_NAME); ?></p>
</div>
<div class="cnkt-main">
<div class="group">
<h3><?php _e('License Keys', ALM_NAME); ?></h3>
<p><?php _e('Manage your Ajax Load More license key\'s below - enter a key for each of your add-ons to receive plugin update notifications directly within the <a href="plugins.php">WP Plugins dashboard</a>.', ALM_NAME); ?></p>
<?php
// alm_cache_installed
// alm_unlimited_installed
// alm_preload_installed
// alm_paging_installed
// alm_seo_installed
// alm_theme_repeaters_installed
?>
<?php
// Check if any add ons are installed.
if(has_action('alm_cache_installed') || has_action('alm_unlimited_installed') || has_action('alm_preload_installed') || has_action('alm_paging_installed') || has_action('alm_seo_installed')) : ?>
<?php
if (has_action('alm_cache_installed')){
// CACHE
$alm_cache_license = get_option( 'alm_cache_license_key' );
$alm_cache_status = get_option( 'alm_cache_license_status' );
?>
<div class="license" id="license-paging">
<div class="license-title">
<div class="status <?php if($alm_cache_status == 'valid'){echo 'valid';}else{echo 'invalid';} ?> "></div>
<h2><?php _e('Cache', ALM_NAME); ?></h2>
</div>
<div class="license-wrap">
<form method="post" action="options.php">
<?php settings_fields('alm_cache_license'); ?>
<label class="description" for="alm_cache_license_key"><?php _e('Enter License Key', ALM_NAME); ?></label>
<div class="license-key-field">
<input id="alm_cache_license_key" name="alm_cache_license_key" type="text" class="regular-text" value="<?php esc_attr_e( $alm_cache_license ); ?>" placeholder="<?php _e('Enter License Key', ALM_NAME); ?>" />
<?php if( $alm_cache_status !== false && $alm_cache_status == 'valid' ) { ?>
<span class="status active">
<?php _e('Active', ALM_NAME); ?>
</span>
<?php } else { ?>
<span class="status inactive">
<?php _e('In-active', ALM_NAME); ?>
</span>
<?php } ?>
</div>
<?php wp_nonce_field( 'alm_cache_license_nonce', 'alm_cache_license_nonce' ); ?>
<?php if($alm_cache_status === '' || $alm_cache_status !== 'valid') {
submit_button(__('Save License Key', ALM_NAME), 'primary', '', false);
} ?>
<?php if( false !== $alm_cache_license ) { ?>
<?php if( $alm_cache_status !== false && $alm_cache_status == 'valid' ) { ?>
<input type="submit" class="button-secondary" name="alm_cache_license_deactivate" value="<?php _e('De-activate License', ALM_NAME); ?>"/>
<?php } else { ?>
<?php if(!empty($alm_cache_license)){ ?>
<input type="submit" class="button-secondary" name="alm_cache_license_activate" value="<?php _e('Activate License', ALM_NAME); ?>"/>
<?php } ?>
<?php } ?>
<?php } ?>
</form>
</div>
</div>
<?php
}
// End CACHE
?>
<?php
if (has_action('alm_unlimited_installed')){
// PAGING
$alm_unlimited_license = get_option( 'alm_unlimited_license_key' );
$alm_unlimited_status = get_option( 'alm_unlimited_license_status' );
?>
<div class="license" id="license-paging">
<div class="license-title">
<div class="status <?php if($alm_unlimited_status == 'valid'){echo 'valid';}else{echo 'invalid';} ?> "></div>
<h2><?php _e('Custom Repeaters', ALM_NAME); ?></h2>
</div>
<div class="license-wrap">
<form method="post" action="options.php">
<?php settings_fields('alm_unlimited_license'); ?>
<label class="description" for="alm_unlimited_license_key"><?php _e('Enter License Key', ALM_NAME); ?></label>
<div class="license-key-field">
<input id="alm_unlimited_license_key" name="alm_unlimited_license_key" type="text" class="regular-text" value="<?php esc_attr_e( $alm_unlimited_license ); ?>" placeholder="<?php _e('Enter License Key', ALM_NAME); ?>" />
<?php if( $alm_unlimited_status !== false && $alm_unlimited_status == 'valid' ) { ?>
<span class="status active">
<?php _e('Active', ALM_NAME); ?>
</span>
<?php } else { ?>
<span class="status inactive">
<?php _e('In-active', ALM_NAME); ?>
</span>
<?php } ?>
</div>
<?php wp_nonce_field( 'alm_unlimited_license_nonce', 'alm_unlimited_license_nonce' ); ?>
<?php if($alm_unlimited_status === '' || $alm_unlimited_status !== 'valid') {
submit_button(__('Save License Key', ALM_NAME), 'primary', '', false);
} ?>
<?php if( false !== $alm_unlimited_license ) { ?>
<?php if( $alm_unlimited_status !== false && $alm_unlimited_status == 'valid' ) { ?>
<input type="submit" class="button-secondary" name="alm_unlimited_license_deactivate" value="<?php _e('De-activate License', ALM_NAME); ?>"/>
<?php } else { ?>
<?php if(!empty($alm_unlimited_license)){ ?>
<input type="submit" class="button-secondary" name="alm_unlimited_license_activate" value="<?php _e('Activate License', ALM_NAME); ?>"/>
<?php } ?>
<?php } ?>
<?php } ?>
</form>
</div>
</div>
<?php
}
// End Custom Repeaters v2
?>
<?php
if (has_action('alm_paging_installed')){
// PAGING
$alm_paging_license = get_option( 'alm_paging_license_key' );
$alm_paging_status = get_option( 'alm_paging_license_status' );
?>
<div class="license" id="license-paging">
<div class="license-title">
<div class="status <?php if($alm_paging_status == 'valid'){echo 'valid';}else{echo 'invalid';} ?> "></div>
<h2><?php _e('Paging', ALM_NAME); ?></h2>
</div>
<div class="license-wrap">
<form method="post" action="options.php">
<?php settings_fields('alm_paging_license'); ?>
<label class="description" for="alm_paging_license_key"><?php _e('Enter License Key', ALM_NAME); ?></label>
<div class="license-key-field">
<input id="alm_paging_license_key" name="alm_paging_license_key" type="text" class="regular-text" value="<?php esc_attr_e( $alm_paging_license ); ?>" placeholder="<?php _e('Enter License Key', ALM_NAME); ?>" />
<?php if( $alm_paging_status !== false && $alm_paging_status == 'valid' ) { ?>
<span class="status active">
<?php _e('Active', ALM_NAME); ?>
</span>
<?php } else { ?>
<span class="status inactive">
<?php _e('In-active', ALM_NAME); ?>
</span>
<?php } ?>
</div>
<?php wp_nonce_field( 'alm_paging_license_nonce', 'alm_paging_license_nonce' ); ?>
<?php if($alm_paging_status === '' || $alm_paging_status !== 'valid') {
submit_button(__('Save License Key', ALM_NAME), 'primary', '', false);
} ?>
<?php if( false !== $alm_paging_license ) { ?>
<?php if( $alm_paging_status !== false && $alm_paging_status == 'valid' ) { ?>
<input type="submit" class="button-secondary" name="alm_paging_license_deactivate" value="<?php _e('De-activate License', ALM_NAME); ?>"/>
<?php } else { ?>
<?php if(!empty($alm_paging_license)){ ?>
<input type="submit" class="button-secondary" name="alm_paging_license_activate" value="<?php _e('Activate License', ALM_NAME); ?>"/>
<?php } ?>
<?php } ?>
<?php } ?>
</form>
</div>
</div>
<?php
}
// End PAGING
?>
<?php
if (has_action('alm_preload_installed')){
// PRELOADED
$alm_preloaded_license = get_option( 'alm_preloaded_license_key' );
$alm_preloaded_status = get_option( 'alm_preloaded_license_status' );
?>
<div class="license" id="license-paging">
<div class="license-title">
<div class="status <?php if($alm_preloaded_status == 'valid'){echo 'valid';}else{echo 'invalid';} ?> "></div>
<h2><?php _e('Preloaded', ALM_NAME); ?></h2>
</div>
<div class="license-wrap">
<form method="post" action="options.php">
<?php settings_fields('alm_preloaded_license'); ?>
<label class="description" for="alm_preloaded_license_key"><?php _e('Enter License Key', ALM_NAME); ?></label>
<div class="license-key-field">
<input id="alm_preloaded_license_key" name="alm_preloaded_license_key" type="text" class="regular-text" value="<?php esc_attr_e( $alm_preloaded_license ); ?>" placeholder="<?php _e('Enter License Key', ALM_NAME); ?>" />
<?php if( $alm_preloaded_status !== false && $alm_preloaded_status == 'valid' ) { ?>
<span class="status active">
<?php _e('Active', ALM_NAME); ?>
</span>
<?php } else { ?>
<span class="status inactive">
<?php _e('In-active', ALM_NAME); ?>
</span>
<?php } ?>
</div>
<?php wp_nonce_field( 'alm_preloaded_license_nonce', 'alm_preloaded_license_nonce' ); ?>
<?php if($alm_preloaded_status === '' || $alm_preloaded_status !== 'valid') {
submit_button(__('Save License Key', ALM_NAME), 'primary', '', false);
} ?>
<?php if( false !== $alm_preloaded_license ) { ?>
<?php if( $alm_preloaded_status !== false && $alm_preloaded_status == 'valid' ) { ?>
<input type="submit" class="button-secondary" name="alm_preloaded_license_deactivate" value="<?php _e('De-activate License', ALM_NAME); ?>"/>
<?php } else { ?>
<?php if(!empty($alm_preloaded_license)){ ?>
<input type="submit" class="button-secondary" name="alm_preloaded_license_activate" value="<?php _e('Activate License', ALM_NAME); ?>"/>
<?php } ?>
<?php } ?>
<?php } ?>
</form>
</div>
</div>
<?php
}
// End PRELOADED
?>
<?php
if (has_action('alm_seo_installed')){
// SEO
$alm_seo_license = get_option( 'alm_seo_license_key' );
$alm_seo_status = get_option( 'alm_seo_license_status' );
?>
<div class="license" id="license-paging">
<div class="license-title">
<div class="status <?php if($alm_seo_status == 'valid'){echo 'valid';}else{echo 'invalid';} ?> "></div>
<h2><?php _e('Search Engine Optimization', ALM_NAME); ?></h2>
</div>
<div class="license-wrap">
<form method="post" action="options.php">
<?php settings_fields('alm_seo_license'); ?>
<label class="description" for="alm_seo_license_key"><?php _e('Enter License Key', ALM_NAME); ?></label>
<div class="license-key-field">
<input id="alm_seo_license_key" name="alm_seo_license_key" type="text" class="regular-text" value="<?php esc_attr_e( $alm_seo_license ); ?>" placeholder="<?php _e('Enter License Key', ALM_NAME); ?>" />
<?php if( $alm_seo_status !== false && $alm_seo_status == 'valid' ) { ?>
<span class="status active">
<?php _e('Active', ALM_NAME); ?>
</span>
<?php } else { ?>
<span class="status inactive">
<?php _e('In-active', ALM_NAME); ?>
</span>
<?php } ?>
</div>
<?php wp_nonce_field( 'alm_seo_license_nonce', 'alm_seo_license_nonce' ); ?>
<?php if($alm_seo_status === '' || $alm_seo_status !== 'valid') {
submit_button(__('Save License Key', ALM_NAME), 'primary', '', false);
} ?>
<?php if( false !== $alm_seo_license ) { ?>
<?php if( $alm_seo_status !== false && $alm_seo_status == 'valid' ) { ?>
<input type="submit" class="button-secondary" name="alm_seo_license_deactivate" value="<?php _e('De-activate License', ALM_NAME); ?>"/>
<?php } else { ?>
<?php if(!empty($alm_seo_license)){ ?>
<input type="submit" class="button-secondary" name="alm_seo_license_activate" value="<?php _e('Activate License', ALM_NAME); ?>"/>
<?php } ?>
<?php } ?>
<?php } ?>
</form>
</div>
</div>
<?php
}
// End SEO
?>
<?php
if (has_action('alm_theme_repeaters_installed')){
// Theme Templates
$alm_theme_repeaters_license = get_option( 'alm_theme_repeaters_license_key' );
$alm_theme_repeaters_status = get_option( 'alm_theme_repeaters_license_status' );
?>
<div class="license" id="license-theme_repeaters">
<div class="license-title">
<div class="status <?php if($alm_theme_repeaters_status == 'valid'){echo 'valid';}else{echo 'invalid';} ?> "></div>
<h2><?php _e('Theme Repeaters', ALM_NAME); ?></h2>
</div>
<div class="license-wrap">
<form method="post" action="options.php">
<?php settings_fields('alm_theme_repeaters_license'); ?>
<label class="description" for="alm_theme_repeaters_license_key"><?php _e('Enter License Key', ALM_NAME); ?></label>
<div class="license-key-field">
<input id="alm_theme_repeaters_license_key" name="alm_theme_repeaters_license_key" type="text" class="regular-text" value="<?php esc_attr_e( $alm_theme_repeaters_license ); ?>" placeholder="<?php _e('Enter License Key', ALM_NAME); ?>" />
<?php if( $alm_theme_repeaters_status !== false && $alm_theme_repeaters_status == 'valid' ) { ?>
<span class="status active">
<?php _e('Active', ALM_NAME); ?>
</span>
<?php } else { ?>
<span class="status inactive">
<?php _e('In-active', ALM_NAME); ?>
</span>
<?php } ?>
</div>
<?php wp_nonce_field( 'alm_theme_repeaters_license_nonce', 'alm_theme_repeaters_license_nonce' ); ?>
<?php if($alm_theme_repeaters_status === '' || $alm_theme_repeaters_status !== 'valid') {
submit_button(__('Save License Key', ALM_NAME), 'primary', '', false);
} ?>
<?php if( false !== $alm_theme_repeaters_license ) { ?>
<?php if( $alm_theme_repeaters_status !== false && $alm_theme_repeaters_status == 'valid' ) { ?>
<input type="submit" class="button-secondary" name="alm_theme_repeaters_license_deactivate" value="<?php _e('De-activate License', ALM_NAME); ?>"/>
<?php } else { ?>
<?php if(!empty($alm_theme_repeaters_license)){ ?>
<input type="submit" class="button-secondary" name="alm_theme_repeaters_license_activate" value="<?php _e('Activate License', ALM_NAME); ?>"/>
<?php } ?>
<?php } ?>
<?php } ?>
</form>
</div>
</div>
<?php
}
// End Theme Repeaters
?>
<?php else : ?>
<div class="license-no-addons">
<p><?php _e('You do not have any Ajax Load More add-ons installed', ALM_NAME); ?>. » <a href="admin.php?page=ajax-load-more-add-ons"><strong><?php _e('Browse Add-ons', ALM_NAME); ?></strong></a></p>
</div>
<?php endif; ?>
</div>
</div>
<div class="cnkt-sidebar">
<div class="cta">
<h3><?php _e('About Licenses', ALM_NAME); ?></h3>
<div class="cta-wrap">
<ul>
<li><?php _e('Add-on licenses will enable updates directly in your WP dashboard.', ALM_NAME);?></li>
<li><?php _e('License keys are found in the purchase receipt email that was sent immediately after your successful purchase.', ALM_NAME);?></li>
<li><?php _e('If you cannot locate your key please use the <a href="https://connekthq.com/contact/">contact form</a> on our website and reference the email address used when you completed the purchase.', ALM_NAME); ?></li>
</ul>
</div>
</div>
<div class="cta">
<h3><?php _e('Legacy Users', ALM_NAME); ?></h3>
<div class="cta-wrap">
<ul>
<li>If you have made a purchase prior to <u>July 6, 2015</u> you will require a license after updating your add-ons. Please <a href="https://connekthq.com/contact/">email us</a> with a reference to the email address used when you completed the add-on purchase and we will send your license key.</li>
</ul>
</div>
</div>
</div>
</div>
</div>
|
gpl-2.0
|
DavidKMartel/GameAdminHelper
|
StartSession.php
|
1382
|
<?php
include 'UsefulFunctions.php';
getNavHeader();
getServHeader();
define("DEFAULT_ADDRESS","172.17.0.106");
define("DEFAULT_PORT","27015");
define("DEFAULT_PASSWORD","pass");
if(!defined($_SESSION['address'])) {
$_SESSION['address'] = DEFAULT_ADDRESS;
}
if(!defined($_SESSION['port'])) {
$_SESSION['port'] = DEFAULT_PORT;
}
if(!defined($_SESSION['password'])) {
$_SESSION['password'] = DEFAULT_PASSWORD;
}
if($_SERVER["REQUEST_METHOD"] == "POST") {
$_SESSION['address'] = $_POST["address"];
$_SESSION['port'] = $_POST["port"];
$_SESSION['password'] = $_POST["password"];
$_SESSION['valid'] = testLogin($_SESSION['address'],
$_SESSION['port'], $_SESSION['password']);
}
?>
<html>
<body>
<form name="Login" method="POST">
<table>
<tr><td>Address:</td> <td><input type="text" name="address" value="<?php echo $_SESSION['address'];?>"></text></td></tr>
<tr><td>Port:</td> <td><input type="text" name="port" value="<?php echo $_SESSION['port'];?>"></text></td></tr>
<tr><td>Password:</td> <td><input type="text" name="password" value="<?php echo $_SESSION['password'];?>"></text></td></tr>
<tr><td><input type="submit" name="submit" value="Login"></td></tr>
</table>
</form>
<?php
if($_SESSION['valid']) {
echo "Login Successful <a href=\"index.php\">Continue</a>";
} else {
echo "<b><font color=\"red\">Invalid Login</font></a>";
}
?>
<html>
<body>
|
gpl-2.0
|
ugeneunipro/ugene
|
src/plugins/dotplot/transl/russian.ts
|
29950
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ru_RU">
<context>
<name>DotPlotDialog</name>
<message>
<location filename="../src/DotPlotDialog.ui" line="20"/>
<source>Compare sequences using Dotplot</source>
<translation>Сравнение последовательностей при помощи Dotplot</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="33"/>
<source>Dotplot parameters</source>
<translation>Dotplot параметры</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="55"/>
<source>Custom algorithm</source>
<translation>Алгоритм по умолчанию</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="102"/>
<source>X axis sequence</source>
<translation>Последовательность оси X</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="115"/>
<source>Minimum repeat length</source>
<translation>Мин длина повторов</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="122"/>
<source>Y axis sequence</source>
<translation>Последовательность оси Y</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="129"/>
<source>Repeats identity</source>
<translation>Идентичность повторов</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="154"/>
<source>bp</source>
<translation>нк</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="182"/>
<source>Heuristic based selection of repeat length so the number of repeats in the sequence will not exceed 1000</source>
<translation>Эвристический подбор длины повторов, с тем чтобы кол-во повторов в последовательности не превысило 1000</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="185"/>
<source>1k</source>
<translation>1к</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="210"/>
<source>%</source>
<translation>%</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="232"/>
<source>Resets repeats identity to 100%</source>
<translation>Сбросить к 100%</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="235"/>
<source>100</source>
<translation>100</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="290"/>
<source>Search inverted repeats</source>
<translation>Искать инвертированные повторы</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="297"/>
<source>Search direct repeats</source>
<translation>Искать прямые повторы</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="336"/>
<location filename="../src/DotPlotDialog.ui" line="343"/>
<source>default</source>
<translation>По умолчанию</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="368"/>
<source>Click to load a sequence from the file system. The sequence will be added to the combo boxes when it is loaded to the project</source>
<translation>Нажмите, чтобы загрузить последовательности из файловой системы. Последовательности будут добавлены в комбо-боксы, когда они будут загружены в проект</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.ui" line="371"/>
<source>Load Sequence</source>
<translation>Загрузить</translation>
</message>
</context>
<context>
<name>DotPlotFilesDialog</name>
<message>
<location filename="../src/DotPlotFilesDialog.ui" line="38"/>
<location filename="../src/DotPlotFilesDialog.ui" line="72"/>
<source>...</source>
<translation>...</translation>
</message>
<message>
<location filename="../src/DotPlotFilesDialog.ui" line="23"/>
<source>Build Dotplot from Sequences</source>
<translation>Построить dotplot последовательностей</translation>
</message>
<message>
<location filename="../src/DotPlotFilesDialog.ui" line="55"/>
<source>File with first sequence</source>
<translation>Файл с первой последовательностью</translation>
</message>
<message>
<location filename="../src/DotPlotFilesDialog.ui" line="45"/>
<location filename="../src/DotPlotFilesDialog.ui" line="96"/>
<source>Join all sequences found in the file</source>
<translation>Соединить последовательности</translation>
</message>
<message>
<location filename="../src/DotPlotFilesDialog.ui" line="62"/>
<location filename="../src/DotPlotFilesDialog.ui" line="130"/>
<source>Gap size:</source>
<translation>Длина пробела:</translation>
</message>
<message>
<location filename="../src/DotPlotFilesDialog.ui" line="79"/>
<source>Compare sequence against itself</source>
<translation>Саму с собой</translation>
</message>
<message>
<location filename="../src/DotPlotFilesDialog.ui" line="103"/>
<source>File with second sequence</source>
<translation>Файл со второй последовательностью</translation>
</message>
</context>
<context>
<name>DotPlotFilterDialog</name>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="17"/>
<source>DotPlot</source>
<translation>DotPlot</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="30"/>
<source>Dotplot parameters</source>
<translation>Параметры фильтрации</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="42"/>
<source>No filtration applied</source>
<translation>Фильтрация не применяется</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="45"/>
<source>No Filtration</source>
<translation>Без фильтрации</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="55"/>
<source>Show results that intersect the features</source>
<translation>показывать результаты, которые пересекают аннотации</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="58"/>
<source>Features Intersection</source>
<translation>Пересечение аннотаций</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="65"/>
<source>Intersection Parameters</source>
<translation>Параметры пересечения</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="72"/>
<source>Feature Name</source>
<translation>Имя аннотации</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="80"/>
<source>Select all names</source>
<translation>Выбрать все имена</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="83"/>
<source>Select All</source>
<translation>Выбрать все</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="90"/>
<source>Invert the current selection</source>
<translation>Инвертировать текущее выделение</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="93"/>
<source>Invert Selection</source>
<translation>Инвертировать</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="100"/>
<source>Clear the current selection</source>
<translation>Очистить текущее выделение</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="103"/>
<source>Clear Selection</source>
<translation>Очистить</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="110"/>
<source>Select names of the features to intersection</source>
<translation>Выберете имена аннотаций для пересечения</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="113"/>
<source>Features Selection</source>
<translation>Выбор аннотаций</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="139"/>
<source>Select only different names</source>
<translation>Выбрать только различные имена</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.ui" line="142"/>
<source>Different Only</source>
<translation>Различные</translation>
</message>
</context>
<context>
<name>U2::DotPlotDialog</name>
<message>
<location filename="../src/DotPlotDialog.cpp" line="54"/>
<source>OK</source>
<translation>OK</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.cpp" line="55"/>
<source>Cancel</source>
<translation>Отмена</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.cpp" line="65"/>
<source>Auto</source>
<translation>Автовыбор</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.cpp" line="66"/>
<source>Suffix index</source>
<translation>Суффиксный индекс</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.cpp" line="67"/>
<source>Diagonals</source>
<translation>Диагональный</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.cpp" line="312"/>
<source>Open file</source>
<translation>Открыть файл</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.cpp" line="341"/>
<source>Error</source>
<translation>Ошибка</translation>
</message>
<message>
<location filename="../src/DotPlotDialog.cpp" line="341"/>
<source>Error opening files</source>
<translation>Ошибка открытия файлов</translation>
</message>
</context>
<context>
<name>U2::DotPlotFilesDialog</name>
<message>
<location filename="../src/DotPlotFilesDialog.cpp" line="41"/>
<source>Next</source>
<translation>Далее</translation>
</message>
<message>
<location filename="../src/DotPlotFilesDialog.cpp" line="42"/>
<source>Cancel</source>
<translation>Отмена</translation>
</message>
<message>
<location filename="../src/DotPlotFilesDialog.cpp" line="73"/>
<source>Open first file</source>
<translation>Открыть первый файл</translation>
</message>
<message>
<location filename="../src/DotPlotFilesDialog.cpp" line="104"/>
<source>Open second file</source>
<translation>Открыть второй файл</translation>
</message>
<message>
<location filename="../src/DotPlotFilesDialog.cpp" line="140"/>
<source>Select a file with a sequence to build dotplot!</source>
<translation>Выберите файл с последовательностью!</translation>
</message>
<message>
<location filename="../src/DotPlotFilesDialog.cpp" line="140"/>
<source>Select first file with a sequence to build dotplot!</source>
<translation>Выберите первый файл с последовательностью!</translation>
</message>
<message>
<location filename="../src/DotPlotFilesDialog.cpp" line="141"/>
<source>Input the second sequence or check the 'Compare sequence against itself' option.</source>
<translation>Выберите вторую последовательность или выберите опцию 'Сравнить последовательность саму с собой'.</translation>
</message>
<message>
<location filename="../src/DotPlotFilesDialog.cpp" line="150"/>
<location filename="../src/DotPlotFilesDialog.cpp" line="158"/>
<source>Unable to detect file format %1.</source>
<translation>Невозможно определить формат файла %1.</translation>
</message>
<message>
<location filename="../src/DotPlotFilesDialog.cpp" line="142"/>
<location filename="../src/DotPlotFilesDialog.cpp" line="150"/>
<location filename="../src/DotPlotFilesDialog.cpp" line="158"/>
<source>Select files</source>
<translation>Выберите файлы</translation>
</message>
</context>
<context>
<name>U2::DotPlotFilterDialog</name>
<message>
<location filename="../src/DotPlotFilterDialog.cpp" line="45"/>
<source>OK</source>
<translation>OK</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.cpp" line="46"/>
<source>Cancel</source>
<translation>Отмена</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.cpp" line="139"/>
<source>Feature names</source>
<translation>Имена аннотаций</translation>
</message>
<message>
<location filename="../src/DotPlotFilterDialog.cpp" line="139"/>
<source>No feature names have been selected. In that case dotplot will be empty. Note, If the feature names list is empty your sequences don't have annotations. Select some feature names or choose another filtration method</source>
<translation>Имена аннотаций не были выбраны. В этом случае dotplot будет пустым. Если список аннотаций пустой, то ваши последовательности не содержат аннотации. Выберете несколько имен аннотаций или другой метод фильтрации</translation>
</message>
</context>
<context>
<name>U2::DotPlotFilterTask</name>
<message>
<location filename="../src/DotPlotTasks.cpp" line="311"/>
<source>Applying filter to dotplot</source>
<translation>Применение фильтра к dotplot</translation>
</message>
</context>
<context>
<name>U2::DotPlotImageExportController</name>
<message>
<location filename="../src/DotPlotImageExportTask.cpp" line="60"/>
<source>Dotplot widget is NULL</source>
<translation>Dotplot widget is NULL</translation>
</message>
<message>
<location filename="../src/DotPlotImageExportTask.cpp" line="61"/>
<source>Dotplot</source>
<translation>Dotplot</translation>
</message>
<message>
<location filename="../src/DotPlotImageExportTask.cpp" line="78"/>
<source>Include area selection</source>
<translation>Включить область выделения</translation>
</message>
<message>
<location filename="../src/DotPlotImageExportTask.cpp" line="79"/>
<source>Include repeat selection</source>
<translation>Включить повторяющиеся выделения</translation>
</message>
</context>
<context>
<name>U2::DotPlotImageExportToBitmapTask</name>
<message>
<location filename="../src/DotPlotImageExportTask.cpp" line="49"/>
<source>Incorrect DPI parameter</source>
<translation>Incorrect DPI parameter</translation>
</message>
</context>
<context>
<name>U2::DotPlotLoadDocumentsTask</name>
<message>
<location filename="../src/DotPlotTasks.cpp" line="218"/>
<source>DotPlot loading</source>
<translation>Dotplot загружается</translation>
</message>
<message>
<location filename="../src/DotPlotTasks.cpp" line="260"/>
<source>Detecting format error for file %1</source>
<translation>Ошибка определения формата файла %1</translation>
</message>
</context>
<context>
<name>U2::DotPlotPlugin</name>
<message>
<location filename="../src/DotPlotPlugin.cpp" line="54"/>
<source>Dotplot</source>
<translation>Dotplot</translation>
</message>
<message>
<location filename="../src/DotPlotPlugin.cpp" line="54"/>
<source>Build dotplot for sequences</source>
<translation>Построение dotplot для последовательностей</translation>
</message>
</context>
<context>
<name>U2::DotPlotSplitter</name>
<message>
<location filename="../src/DotPlotSplitter.cpp" line="46"/>
<source>Multiple view synchronization lock</source>
<translation>Синхронизация нескольких окон</translation>
</message>
<message>
<location filename="../src/DotPlotSplitter.cpp" line="47"/>
<source>Filter results</source>
<translation>Фильтрация результатов</translation>
</message>
<message>
<location filename="../src/DotPlotSplitter.cpp" line="48"/>
<source>Zoom in (<b> + </b>)</source>
<translation>Приблизить (<b> + </b>)</translation>
</message>
<message>
<location filename="../src/DotPlotSplitter.cpp" line="49"/>
<source>Zoom out (<b> - </b>)</source>
<translation>Удалить (<b> - </b>)</translation>
</message>
<message>
<location filename="../src/DotPlotSplitter.cpp" line="50"/>
<source>Reset zooming (<b>0</b>)</source>
<translation>Масштабировать к исходному размеру (<b> 0 </b>)</translation>
</message>
<message>
<location filename="../src/DotPlotSplitter.cpp" line="51"/>
<source>Select tool (<b>S</b>)</source>
<translation>Выделение (<b>S</b>)</translation>
</message>
<message>
<location filename="../src/DotPlotSplitter.cpp" line="52"/>
<source>Hand tool (<b>H</b>)</source>
<translation>Рука (<b>H</b>)</translation>
</message>
<message>
<location filename="../src/DotPlotSplitter.cpp" line="279"/>
<source>One of the sequences in dotplot is NULL</source>
<translation>One of the sequences in dotplot is NULL</translation>
</message>
</context>
<context>
<name>U2::DotPlotViewAction</name>
<message>
<location filename="../src/DotPlotPlugin.h" line="82"/>
<source>Show dot plot</source>
<translation>Показать dotplot</translation>
</message>
</context>
<context>
<name>U2::DotPlotViewContext</name>
<message>
<location filename="../src/DotPlotPlugin.cpp" line="72"/>
<location filename="../src/DotPlotPlugin.cpp" line="218"/>
<source>Build dotplot...</source>
<translation>Построение точечной диаграммы (dotplot)...</translation>
</message>
<message>
<location filename="../src/DotPlotPlugin.cpp" line="91"/>
<source>Error</source>
<translation>Ошибка</translation>
</message>
<message>
<location filename="../src/DotPlotPlugin.cpp" line="91"/>
<source>Error opening files</source>
<translation>Ошибка открытия файлов</translation>
</message>
</context>
<context>
<name>U2::DotPlotWidget</name>
<message>
<location filename="../src/DotPlotWidget.cpp" line="115"/>
<source>Parameters</source>
<translation>Параметры</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="118"/>
<source>Save as image</source>
<translation>Сохранить как изображение</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="122"/>
<source>Save</source>
<translation>Сохранить</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="126"/>
<source>Load</source>
<translation>Загрузить</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="129"/>
<source>Remove</source>
<translation>Удалить</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="133"/>
<source>Filter Results</source>
<translation>Фильтрация результатов</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="203"/>
<source>Save/Load</source>
<translation>Сохранить/Загрузить</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="380"/>
<source>Too many results</source>
<translation>Слишком много результатов</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="380"/>
<source>Too many results. Try to increase minimum repeat length</source>
<translation>Слишком много результатов. Попробуйте уменьшить минимальную длину повтора</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="529"/>
<location filename="../src/DotPlotWidget.cpp" line="586"/>
<source>File opening error</source>
<translation>Ошибка открытия файла</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="529"/>
<location filename="../src/DotPlotWidget.cpp" line="586"/>
<source>Error opening file %1</source>
<translation>Ошибка открытия файла %1</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="537"/>
<location filename="../src/DotPlotWidget.cpp" line="568"/>
<location filename="../src/DotPlotWidget.cpp" line="636"/>
<source>Task is already running</source>
<translation>Задача уже запущена</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="537"/>
<location filename="../src/DotPlotWidget.cpp" line="568"/>
<location filename="../src/DotPlotWidget.cpp" line="636"/>
<source>Build or Load DotPlot task is already running</source>
<translation>Задача построения или загрузки dotplot уже запущена</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="590"/>
<source>Sequences are different</source>
<translation>Последовательности отличаются</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="590"/>
<source>Current and loading sequences are different. Continue loading dot-plot anyway?</source>
<translation>Текущая и загружаемая последовательность различаются. Продолжить загрузку?</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="691"/>
<location filename="../src/DotPlotWidget.cpp" line="696"/>
<source>Invalid sequence</source>
<translation>Некорректная последовательность</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="691"/>
<source>First selected sequence is invalid</source>
<translation>Первая выделенная последовательность некорректна</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="696"/>
<source>Second selected sequence is invalid</source>
<translation>Вторая выделенная последовательность некорректна</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="704"/>
<source>Wrong alphabet types</source>
<translation>Неправильные типы алфавитов</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="704"/>
<source>Both sequence must have the same alphabet</source>
<translation>Обе последовательности должны иметь одинаковый алфавит</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="781"/>
<source>Save dot-plot</source>
<translation>Сохранить dotplot</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="781"/>
<source>Save dot-plot data before closing?</source>
<translation>Сохранить данные dotplot перед закрытием?</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="919"/>
<source>Invalid weight and height parameters!</source>
<translation>Некорректные параметры!</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="970"/>
<source>Dotplot is calculating...</source>
<translation>Выполняется расчёт...</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="1017"/>
<source> (min length %1, identity %2%)</source>
<translation>(мин. длина %1, идентичность %2%)</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="201"/>
<source>Dotplot</source>
<translation>Dotplot</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="514"/>
<source>Error Saving Dotplot</source>
<translation>Ошибка сохранения</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="514"/>
<source>The dotplot can't be saved as it is empty.</source>
<translation>Дотплот не может быть сохранён, т.к. он пуст.</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="518"/>
<source>Save Dotplot</source>
<translation>Сохранить dotplot</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="518"/>
<location filename="../src/DotPlotWidget.cpp" line="561"/>
<source>Dotplot files (*.dpt)</source>
<translation>Файлы dotplot (*.dpt)</translation>
</message>
<message>
<location filename="../src/DotPlotWidget.cpp" line="561"/>
<source>Load Dotplot</source>
<translation>Загрузить dotplot</translation>
</message>
</context>
<context>
<name>U2::LoadDotPlotTask</name>
<message>
<location filename="../src/DotPlotTasks.cpp" line="59"/>
<source>Wrong dotplot format</source>
<translation>Неправильный формат файла dotplot</translation>
</message>
<message>
<location filename="../src/DotPlotTasks.h" line="88"/>
<source>DotPlot loading</source>
<translation>Dotplot загружается</translation>
</message>
</context>
<context>
<name>U2::SaveDotPlotTask</name>
<message>
<location filename="../src/DotPlotTasks.h" line="50"/>
<source>DotPlot saving</source>
<translation>Dotplot сохраняется</translation>
</message>
</context>
</TS>
|
gpl-2.0
|
weSPOT/wespot_iwe
|
mod/elastic/views/default/page/elements/footer/footer_left.php
|
200
|
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
?>
<p>
<?php echo elgg_echo('admin:plugins:label:copyright'); ?> © weSPOT project.
</p>
|
gpl-2.0
|
SupermeReturns/ImageProcessor
|
src/Main.java
|
179
|
package com.sdl.ImageProcessor;
import com.sdl.ImageProcessor.Frames.MainFrame;
public class Main{
public static void main(String[] args) {
new MainFrame();
}
}
|
gpl-2.0
|
redeanisioteixeira/aew_github
|
library/Zend/Feed/Writer/Extension/DublinCore/Renderer/Entry.php
|
2784
|
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Feed_Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Entry.php 1 2016-05-25 16:47:26Z admin $
*/
/**
* @see Zend_Feed_Writer_Extension_RendererAbstract
*/
require_once 'Zend/Feed/Writer/Extension/RendererAbstract.php';
/**
* @category Zend
* @package Zend_Feed_Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Feed_Writer_Extension_DublinCore_Renderer_Entry
extends Zend_Feed_Writer_Extension_RendererAbstract
{
/**
* Set to TRUE if a rendering method actually renders something. This
* is used to prevent premature appending of a XML namespace declaration
* until an element which requires it is actually appended.
*
* @var bool
*/
protected $_called = false;
/**
* Render entry
*
* @return void
*/
public function render()
{
if (strtolower($this->getType()) == 'atom') {
return;
}
$this->_setAuthors($this->_dom, $this->_base);
if ($this->_called) {
$this->_appendNamespaces();
}
}
/**
* Append namespaces to entry
*
* @return void
*/
protected function _appendNamespaces()
{
$this->getRootElement()->setAttribute('xmlns:dc',
'http://purl.org/dc/elements/1.1/');
}
/**
* Set entry author elements
*
* @param DOMDocument $dom
* @param DOMElement $root
* @return void
*/
protected function _setAuthors(DOMDocument $dom, DOMElement $root)
{
$authors = $this->getDataContainer()->getAuthors();
if (!$authors || empty($authors)) {
return;
}
foreach ($authors as $data) {
$author = $this->_dom->createElement('dc:creator');
if (array_key_exists('name', $data)) {
$text = $dom->createTextNode($data['name']);
$author->appendChild($text);
$root->appendChild($author);
}
}
$this->_called = true;
}
}
|
gpl-2.0
|
Exiv2/exiv2
|
tests/bugfixes/redmine/test_issue_1153.py
|
4714
|
# -*- coding: utf-8 -*-
import system_tests
import itertools
class CheckSony6000WithoutLensModels(metaclass=system_tests.CaseMeta):
url = "http://dev.exiv2.org/issues/1153"
filenames = [
"$data_path/exiv2-bug1153{E}{i}.exv".format(E=E, i=i)
for E, i in itertools.product(
['A', 'J'],
"a b c d e f g h i j k".split()
)
]
commands = [
"$exiv2 -pa -g LensSpecification -g LensModel -g LensID {!s}".format(fname) for fname in filenames
]
stdout = [
"""Exif.Sony2.LensID Long 1 Sony E 50mm F1.8 OSS
Exif.Photo.LensSpecification Rational 4 500/10 500/10 18/10 18/10
Exif.Photo.LensModel Ascii 16 E 50mm F1.8 OSS
""",
"""Exif.Sony2.LensID Long 1 Sony E 50mm F1.8 OSS
Exif.Photo.LensSpecification Rational 4 500/10 500/10 18/10 18/10
Exif.Photo.LensModel Ascii 16 E 50mm F1.8 OSS
""",
"""Exif.Sony2.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
Exif.Photo.LensSpecification Rational 4 160/10 500/10 35/10 56/10
Exif.Photo.LensModel Ascii 26 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony2.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
Exif.Photo.LensSpecification Rational 4 160/10 500/10 35/10 56/10
Exif.Photo.LensModel Ascii 26 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony2.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
Exif.Photo.LensSpecification Rational 4 160/10 500/10 35/10 56/10
Exif.Photo.LensModel Ascii 26 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony2.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
Exif.Photo.LensSpecification Rational 4 160/10 500/10 35/10 56/10
Exif.Photo.LensModel Ascii 26 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony2.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
Exif.Photo.LensSpecification Rational 4 160/10 500/10 35/10 56/10
Exif.Photo.LensModel Ascii 26 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony2.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
Exif.Photo.LensSpecification Rational 4 160/10 500/10 35/10 56/10
Exif.Photo.LensModel Ascii 26 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony2.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
Exif.Photo.LensSpecification Rational 4 160/10 500/10 35/10 56/10
Exif.Photo.LensModel Ascii 26 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony2.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
Exif.Photo.LensSpecification Rational 4 160/10 500/10 35/10 56/10
Exif.Photo.LensModel Ascii 26 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony2.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
Exif.Photo.LensSpecification Rational 4 160/10 500/10 35/10 56/10
Exif.Photo.LensModel Ascii 26 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony1.LensID Long 1 Sony E 50mm F1.8 OSS
""",
"""Exif.Sony1.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony1.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony1.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony1.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony1.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony1.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony1.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony1.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony1.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
""",
"""Exif.Sony1.LensID Long 1 E PZ 16-50mm F3.5-5.6 OSS
""",
]
stderr = [""] * len(commands)
retval = [0] * len(commands)
|
gpl-2.0
|
jacobembree/DrupalGap
|
jquery-ui-1.12.1.custom/jquery-ui.js
|
198251
|
/*! jQuery UI - v1.12.1 - 2017-01-13
* http://jqueryui.com
* Includes: widget.js, position.js, data.js, disable-selection.js, focusable.js, form-reset-mixin.js, jquery-1-7.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/draggable.js, widgets/droppable.js, widgets/selectable.js, widgets/sortable.js, widgets/mouse.js, effect.js, effects/effect-slide.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "jquery" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
$.ui = $.ui || {};
var version = $.ui.version = "1.12.1";
/*!
* jQuery UI Widget 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Widget
//>>group: Core
//>>description: Provides a factory for creating stateful widgets with a common API.
//>>docs: http://api.jqueryui.com/jQuery.widget/
//>>demos: http://jqueryui.com/widget/
var widgetUuid = 0;
var widgetSlice = Array.prototype.slice;
$.cleanData = ( function( orig ) {
return function( elems ) {
var events, elem, i;
for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
try {
// Only trigger remove when necessary to save time
events = $._data( elem, "events" );
if ( events && events.remove ) {
$( elem ).triggerHandler( "remove" );
}
// Http://bugs.jquery.com/ticket/8235
} catch ( e ) {}
}
orig( elems );
};
} )( $.cleanData );
$.widget = function( name, base, prototype ) {
var existingConstructor, constructor, basePrototype;
// ProxiedPrototype allows the provided prototype to remain unmodified
// so that it can be used as a mixin for multiple widgets (#8876)
var proxiedPrototype = {};
var namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
var fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
if ( $.isArray( prototype ) ) {
prototype = $.extend.apply( null, [ {} ].concat( prototype ) );
}
// Create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// Allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// Allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// Extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// Copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// Track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
} );
basePrototype = new base();
// We need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( !$.isFunction( value ) ) {
proxiedPrototype[ prop ] = value;
return;
}
proxiedPrototype[ prop ] = ( function() {
function _super() {
return base.prototype[ prop ].apply( this, arguments );
}
function _superApply( args ) {
return base.prototype[ prop ].apply( this, args );
}
return function() {
var __super = this._super;
var __superApply = this._superApply;
var returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
} )();
} );
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name
}, proxiedPrototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
} );
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// Redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor,
child._proto );
} );
// Remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
return constructor;
};
$.widget.extend = function( target ) {
var input = widgetSlice.call( arguments, 1 );
var inputIndex = 0;
var inputLength = input.length;
var key;
var value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string";
var args = widgetSlice.call( arguments, 1 );
var returnValue = this;
if ( isMethodCall ) {
// If this is an empty collection, we need to have the instance method
// return undefined instead of the jQuery instance
if ( !this.length && options === "instance" ) {
returnValue = undefined;
} else {
this.each( function() {
var methodValue;
var instance = $.data( this, fullName );
if ( options === "instance" ) {
returnValue = instance;
return false;
}
if ( !instance ) {
return $.error( "cannot call methods on " + name +
" prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[ options ] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name +
" widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
} );
}
} else {
// Allow multiple hashes to be passed on init
if ( args.length ) {
options = $.widget.extend.apply( null, [ options ].concat( args ) );
}
this.each( function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} );
if ( instance._init ) {
instance._init();
}
} else {
$.data( this, fullName, new object( options, this ) );
}
} );
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
classes: {},
disabled: false,
// Callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = widgetUuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.bindings = $();
this.hoverable = $();
this.focusable = $();
this.classesElementLookup = {};
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
} );
this.document = $( element.style ?
// Element within the document
element.ownerDocument :
// Element is window or document
element.document || element );
this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow );
}
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this._create();
if ( this.options.disabled ) {
this._setOptionDisabled( this.options.disabled );
}
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: function() {
return {};
},
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
var that = this;
this._destroy();
$.each( this.classesElementLookup, function( key, value ) {
that._removeClass( value, key );
} );
// We can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.off( this.eventNamespace )
.removeData( this.widgetFullName );
this.widget()
.off( this.eventNamespace )
.removeAttr( "aria-disabled" );
// Clean up events and states
this.bindings.off( this.eventNamespace );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key;
var parts;
var curOption;
var i;
if ( arguments.length === 0 ) {
// Don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( arguments.length === 1 ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( arguments.length === 1 ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
if ( key === "classes" ) {
this._setOptionClasses( value );
}
this.options[ key ] = value;
if ( key === "disabled" ) {
this._setOptionDisabled( value );
}
return this;
},
_setOptionClasses: function( value ) {
var classKey, elements, currentElements;
for ( classKey in value ) {
currentElements = this.classesElementLookup[ classKey ];
if ( value[ classKey ] === this.options.classes[ classKey ] ||
!currentElements ||
!currentElements.length ) {
continue;
}
// We are doing this to create a new jQuery object because the _removeClass() call
// on the next line is going to destroy the reference to the current elements being
// tracked. We need to save a copy of this collection so that we can add the new classes
// below.
elements = $( currentElements.get() );
this._removeClass( currentElements, classKey );
// We don't use _addClass() here, because that uses this.options.classes
// for generating the string of classes. We want to use the value passed in from
// _setOption(), this is the new value of the classes option which was passed to
// _setOption(). We pass this value directly to _classes().
elements.addClass( this._classes( {
element: elements,
keys: classKey,
classes: value,
add: true
} ) );
}
},
_setOptionDisabled: function( value ) {
this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value );
// If the widget is becoming disabled, then nothing is interactive
if ( value ) {
this._removeClass( this.hoverable, null, "ui-state-hover" );
this._removeClass( this.focusable, null, "ui-state-focus" );
}
},
enable: function() {
return this._setOptions( { disabled: false } );
},
disable: function() {
return this._setOptions( { disabled: true } );
},
_classes: function( options ) {
var full = [];
var that = this;
options = $.extend( {
element: this.element,
classes: this.options.classes || {}
}, options );
function processClassString( classes, checkOption ) {
var current, i;
for ( i = 0; i < classes.length; i++ ) {
current = that.classesElementLookup[ classes[ i ] ] || $();
if ( options.add ) {
current = $( $.unique( current.get().concat( options.element.get() ) ) );
} else {
current = $( current.not( options.element ).get() );
}
that.classesElementLookup[ classes[ i ] ] = current;
full.push( classes[ i ] );
if ( checkOption && options.classes[ classes[ i ] ] ) {
full.push( options.classes[ classes[ i ] ] );
}
}
}
this._on( options.element, {
"remove": "_untrackClassesElement"
} );
if ( options.keys ) {
processClassString( options.keys.match( /\S+/g ) || [], true );
}
if ( options.extra ) {
processClassString( options.extra.match( /\S+/g ) || [] );
}
return full.join( " " );
},
_untrackClassesElement: function( event ) {
var that = this;
$.each( that.classesElementLookup, function( key, value ) {
if ( $.inArray( event.target, value ) !== -1 ) {
that.classesElementLookup[ key ] = $( value.not( event.target ).get() );
}
} );
},
_removeClass: function( element, keys, extra ) {
return this._toggleClass( element, keys, extra, false );
},
_addClass: function( element, keys, extra ) {
return this._toggleClass( element, keys, extra, true );
},
_toggleClass: function( element, keys, extra, add ) {
add = ( typeof add === "boolean" ) ? add : extra;
var shift = ( typeof element === "string" || element === null ),
options = {
extra: shift ? keys : extra,
keys: shift ? element : keys,
element: shift ? this.element : element,
add: add
};
options.element.toggleClass( this._classes( options ), add );
return this;
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement;
var instance = this;
// No suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// No element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// Allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// Copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^([\w:-]*)\s*(.*)$/ );
var eventName = match[ 1 ] + instance.eventNamespace;
var selector = match[ 2 ];
if ( selector ) {
delegateElement.on( eventName, selector, handlerProxy );
} else {
element.on( eventName, handlerProxy );
}
} );
},
_off: function( element, eventName ) {
eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) +
this.eventNamespace;
element.off( eventName ).off( eventName );
// Clear the stack to avoid memory leaks (#10056)
this.bindings = $( this.bindings.not( element ).get() );
this.focusable = $( this.focusable.not( element ).get() );
this.hoverable = $( this.hoverable.not( element ).get() );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
this._addClass( $( event.currentTarget ), null, "ui-state-hover" );
},
mouseleave: function( event ) {
this._removeClass( $( event.currentTarget ), null, "ui-state-hover" );
}
} );
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
this._addClass( $( event.currentTarget ), null, "ui-state-focus" );
},
focusout: function( event ) {
this._removeClass( $( event.currentTarget ), null, "ui-state-focus" );
}
} );
},
_trigger: function( type, event, data ) {
var prop, orig;
var callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// The original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// Copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions;
var effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue( function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
} );
}
};
} );
var widget = $.widget;
/*!
* jQuery UI Position 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/position/
*/
//>>label: Position
//>>group: Core
//>>description: Positions elements relative to other elements.
//>>docs: http://api.jqueryui.com/position/
//>>demos: http://jqueryui.com/position/
( function() {
var cachedScrollbarWidth,
max = Math.max,
abs = Math.abs,
rhorizontal = /left|center|right/,
rvertical = /top|center|bottom/,
roffset = /[\+\-]\d+(\.[\d]+)?%?/,
rposition = /^\w+/,
rpercent = /%$/,
_position = $.fn.position;
function getOffsets( offsets, width, height ) {
return [
parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
];
}
function parseCss( element, property ) {
return parseInt( $.css( element, property ), 10 ) || 0;
}
function getDimensions( elem ) {
var raw = elem[ 0 ];
if ( raw.nodeType === 9 ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: 0, left: 0 }
};
}
if ( $.isWindow( raw ) ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
};
}
if ( raw.preventDefault ) {
return {
width: 0,
height: 0,
offset: { top: raw.pageY, left: raw.pageX }
};
}
return {
width: elem.outerWidth(),
height: elem.outerHeight(),
offset: elem.offset()
};
}
$.position = {
scrollbarWidth: function() {
if ( cachedScrollbarWidth !== undefined ) {
return cachedScrollbarWidth;
}
var w1, w2,
div = $( "<div " +
"style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'>" +
"<div style='height:100px;width:auto;'></div></div>" ),
innerDiv = div.children()[ 0 ];
$( "body" ).append( div );
w1 = innerDiv.offsetWidth;
div.css( "overflow", "scroll" );
w2 = innerDiv.offsetWidth;
if ( w1 === w2 ) {
w2 = div[ 0 ].clientWidth;
}
div.remove();
return ( cachedScrollbarWidth = w1 - w2 );
},
getScrollInfo: function( within ) {
var overflowX = within.isWindow || within.isDocument ? "" :
within.element.css( "overflow-x" ),
overflowY = within.isWindow || within.isDocument ? "" :
within.element.css( "overflow-y" ),
hasOverflowX = overflowX === "scroll" ||
( overflowX === "auto" && within.width < within.element[ 0 ].scrollWidth ),
hasOverflowY = overflowY === "scroll" ||
( overflowY === "auto" && within.height < within.element[ 0 ].scrollHeight );
return {
width: hasOverflowY ? $.position.scrollbarWidth() : 0,
height: hasOverflowX ? $.position.scrollbarWidth() : 0
};
},
getWithinInfo: function( element ) {
var withinElement = $( element || window ),
isWindow = $.isWindow( withinElement[ 0 ] ),
isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9,
hasOffset = !isWindow && !isDocument;
return {
element: withinElement,
isWindow: isWindow,
isDocument: isDocument,
offset: hasOffset ? $( element ).offset() : { left: 0, top: 0 },
scrollLeft: withinElement.scrollLeft(),
scrollTop: withinElement.scrollTop(),
width: withinElement.outerWidth(),
height: withinElement.outerHeight()
};
}
};
$.fn.position = function( options ) {
if ( !options || !options.of ) {
return _position.apply( this, arguments );
}
// Make a copy, we don't want to modify arguments
options = $.extend( {}, options );
var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
target = $( options.of ),
within = $.position.getWithinInfo( options.within ),
scrollInfo = $.position.getScrollInfo( within ),
collision = ( options.collision || "flip" ).split( " " ),
offsets = {};
dimensions = getDimensions( target );
if ( target[ 0 ].preventDefault ) {
// Force left top to allow flipping
options.at = "left top";
}
targetWidth = dimensions.width;
targetHeight = dimensions.height;
targetOffset = dimensions.offset;
// Clone to reuse original targetOffset later
basePosition = $.extend( {}, targetOffset );
// Force my and at to have valid horizontal and vertical positions
// if a value is missing or invalid, it will be converted to center
$.each( [ "my", "at" ], function() {
var pos = ( options[ this ] || "" ).split( " " ),
horizontalOffset,
verticalOffset;
if ( pos.length === 1 ) {
pos = rhorizontal.test( pos[ 0 ] ) ?
pos.concat( [ "center" ] ) :
rvertical.test( pos[ 0 ] ) ?
[ "center" ].concat( pos ) :
[ "center", "center" ];
}
pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
// Calculate offsets
horizontalOffset = roffset.exec( pos[ 0 ] );
verticalOffset = roffset.exec( pos[ 1 ] );
offsets[ this ] = [
horizontalOffset ? horizontalOffset[ 0 ] : 0,
verticalOffset ? verticalOffset[ 0 ] : 0
];
// Reduce to just the positions without the offsets
options[ this ] = [
rposition.exec( pos[ 0 ] )[ 0 ],
rposition.exec( pos[ 1 ] )[ 0 ]
];
} );
// Normalize collision option
if ( collision.length === 1 ) {
collision[ 1 ] = collision[ 0 ];
}
if ( options.at[ 0 ] === "right" ) {
basePosition.left += targetWidth;
} else if ( options.at[ 0 ] === "center" ) {
basePosition.left += targetWidth / 2;
}
if ( options.at[ 1 ] === "bottom" ) {
basePosition.top += targetHeight;
} else if ( options.at[ 1 ] === "center" ) {
basePosition.top += targetHeight / 2;
}
atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
basePosition.left += atOffset[ 0 ];
basePosition.top += atOffset[ 1 ];
return this.each( function() {
var collisionPosition, using,
elem = $( this ),
elemWidth = elem.outerWidth(),
elemHeight = elem.outerHeight(),
marginLeft = parseCss( this, "marginLeft" ),
marginTop = parseCss( this, "marginTop" ),
collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) +
scrollInfo.width,
collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) +
scrollInfo.height,
position = $.extend( {}, basePosition ),
myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
if ( options.my[ 0 ] === "right" ) {
position.left -= elemWidth;
} else if ( options.my[ 0 ] === "center" ) {
position.left -= elemWidth / 2;
}
if ( options.my[ 1 ] === "bottom" ) {
position.top -= elemHeight;
} else if ( options.my[ 1 ] === "center" ) {
position.top -= elemHeight / 2;
}
position.left += myOffset[ 0 ];
position.top += myOffset[ 1 ];
collisionPosition = {
marginLeft: marginLeft,
marginTop: marginTop
};
$.each( [ "left", "top" ], function( i, dir ) {
if ( $.ui.position[ collision[ i ] ] ) {
$.ui.position[ collision[ i ] ][ dir ]( position, {
targetWidth: targetWidth,
targetHeight: targetHeight,
elemWidth: elemWidth,
elemHeight: elemHeight,
collisionPosition: collisionPosition,
collisionWidth: collisionWidth,
collisionHeight: collisionHeight,
offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
my: options.my,
at: options.at,
within: within,
elem: elem
} );
}
} );
if ( options.using ) {
// Adds feedback as second argument to using callback, if present
using = function( props ) {
var left = targetOffset.left - position.left,
right = left + targetWidth - elemWidth,
top = targetOffset.top - position.top,
bottom = top + targetHeight - elemHeight,
feedback = {
target: {
element: target,
left: targetOffset.left,
top: targetOffset.top,
width: targetWidth,
height: targetHeight
},
element: {
element: elem,
left: position.left,
top: position.top,
width: elemWidth,
height: elemHeight
},
horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
};
if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
feedback.horizontal = "center";
}
if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
feedback.vertical = "middle";
}
if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
feedback.important = "horizontal";
} else {
feedback.important = "vertical";
}
options.using.call( this, props, feedback );
};
}
elem.offset( $.extend( position, { using: using } ) );
} );
};
$.ui.position = {
fit: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
outerWidth = within.width,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = withinOffset - collisionPosLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
newOverRight;
// Element is wider than within
if ( data.collisionWidth > outerWidth ) {
// Element is initially over the left side of within
if ( overLeft > 0 && overRight <= 0 ) {
newOverRight = position.left + overLeft + data.collisionWidth - outerWidth -
withinOffset;
position.left += overLeft - newOverRight;
// Element is initially over right side of within
} else if ( overRight > 0 && overLeft <= 0 ) {
position.left = withinOffset;
// Element is initially over both left and right sides of within
} else {
if ( overLeft > overRight ) {
position.left = withinOffset + outerWidth - data.collisionWidth;
} else {
position.left = withinOffset;
}
}
// Too far left -> align with left edge
} else if ( overLeft > 0 ) {
position.left += overLeft;
// Too far right -> align with right edge
} else if ( overRight > 0 ) {
position.left -= overRight;
// Adjust based on position and margin
} else {
position.left = max( position.left - collisionPosLeft, position.left );
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
outerHeight = data.within.height,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = withinOffset - collisionPosTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
newOverBottom;
// Element is taller than within
if ( data.collisionHeight > outerHeight ) {
// Element is initially over the top of within
if ( overTop > 0 && overBottom <= 0 ) {
newOverBottom = position.top + overTop + data.collisionHeight - outerHeight -
withinOffset;
position.top += overTop - newOverBottom;
// Element is initially over bottom of within
} else if ( overBottom > 0 && overTop <= 0 ) {
position.top = withinOffset;
// Element is initially over both top and bottom of within
} else {
if ( overTop > overBottom ) {
position.top = withinOffset + outerHeight - data.collisionHeight;
} else {
position.top = withinOffset;
}
}
// Too far up -> align with top
} else if ( overTop > 0 ) {
position.top += overTop;
// Too far down -> align with bottom edge
} else if ( overBottom > 0 ) {
position.top -= overBottom;
// Adjust based on position and margin
} else {
position.top = max( position.top - collisionPosTop, position.top );
}
}
},
flip: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.offset.left + within.scrollLeft,
outerWidth = within.width,
offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = collisionPosLeft - offsetLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
myOffset = data.my[ 0 ] === "left" ?
-data.elemWidth :
data.my[ 0 ] === "right" ?
data.elemWidth :
0,
atOffset = data.at[ 0 ] === "left" ?
data.targetWidth :
data.at[ 0 ] === "right" ?
-data.targetWidth :
0,
offset = -2 * data.offset[ 0 ],
newOverRight,
newOverLeft;
if ( overLeft < 0 ) {
newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth -
outerWidth - withinOffset;
if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
position.left += myOffset + atOffset + offset;
}
} else if ( overRight > 0 ) {
newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset +
atOffset + offset - offsetLeft;
if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
position.left += myOffset + atOffset + offset;
}
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.offset.top + within.scrollTop,
outerHeight = within.height,
offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = collisionPosTop - offsetTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
top = data.my[ 1 ] === "top",
myOffset = top ?
-data.elemHeight :
data.my[ 1 ] === "bottom" ?
data.elemHeight :
0,
atOffset = data.at[ 1 ] === "top" ?
data.targetHeight :
data.at[ 1 ] === "bottom" ?
-data.targetHeight :
0,
offset = -2 * data.offset[ 1 ],
newOverTop,
newOverBottom;
if ( overTop < 0 ) {
newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight -
outerHeight - withinOffset;
if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) {
position.top += myOffset + atOffset + offset;
}
} else if ( overBottom > 0 ) {
newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset +
offset - offsetTop;
if ( newOverTop > 0 || abs( newOverTop ) < overBottom ) {
position.top += myOffset + atOffset + offset;
}
}
}
},
flipfit: {
left: function() {
$.ui.position.flip.left.apply( this, arguments );
$.ui.position.fit.left.apply( this, arguments );
},
top: function() {
$.ui.position.flip.top.apply( this, arguments );
$.ui.position.fit.top.apply( this, arguments );
}
}
};
} )();
var position = $.ui.position;
/*!
* jQuery UI :data 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: :data Selector
//>>group: Core
//>>description: Selects elements which have data stored under the specified key.
//>>docs: http://api.jqueryui.com/data-selector/
var data = $.extend( $.expr[ ":" ], {
data: $.expr.createPseudo ?
$.expr.createPseudo( function( dataName ) {
return function( elem ) {
return !!$.data( elem, dataName );
};
} ) :
// Support: jQuery <1.8
function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
}
} );
/*!
* jQuery UI Disable Selection 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: disableSelection
//>>group: Core
//>>description: Disable selection of text content within the set of matched elements.
//>>docs: http://api.jqueryui.com/disableSelection/
// This file is deprecated
var disableSelection = $.fn.extend( {
disableSelection: ( function() {
var eventType = "onselectstart" in document.createElement( "div" ) ?
"selectstart" :
"mousedown";
return function() {
return this.on( eventType + ".ui-disableSelection", function( event ) {
event.preventDefault();
} );
};
} )(),
enableSelection: function() {
return this.off( ".ui-disableSelection" );
}
} );
/*!
* jQuery UI Focusable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: http://api.jqueryui.com/focusable-selector/
// Selectors
$.ui.focusable = function( element, hasTabindex ) {
var map, mapName, img, focusableIfVisible, fieldset,
nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap='#" + mapName + "']" );
return img.length > 0 && img.is( ":visible" );
}
if ( /^(input|select|textarea|button|object)$/.test( nodeName ) ) {
focusableIfVisible = !element.disabled;
if ( focusableIfVisible ) {
// Form controls within a disabled fieldset are disabled.
// However, controls within the fieldset's legend do not get disabled.
// Since controls generally aren't placed inside legends, we skip
// this portion of the check.
fieldset = $( element ).closest( "fieldset" )[ 0 ];
if ( fieldset ) {
focusableIfVisible = !fieldset.disabled;
}
}
} else if ( "a" === nodeName ) {
focusableIfVisible = element.href || hasTabindex;
} else {
focusableIfVisible = hasTabindex;
}
return focusableIfVisible && $( element ).is( ":visible" ) && visible( $( element ) );
};
// Support: IE 8 only
// IE 8 doesn't resolve inherit to visible/hidden for computed values
function visible( element ) {
var visibility = element.css( "visibility" );
while ( visibility === "inherit" ) {
element = element.parent();
visibility = element.css( "visibility" );
}
return visibility !== "hidden";
}
$.extend( $.expr[ ":" ], {
focusable: function( element ) {
return $.ui.focusable( element, $.attr( element, "tabindex" ) != null );
}
} );
var focusable = $.ui.focusable;
// Support: IE8 Only
// IE8 does not support the form attribute and when it is supplied. It overwrites the form prop
// with a string, so we need to find the proper form.
var form = $.fn.form = function() {
return typeof this[ 0 ].form === "string" ? this.closest( "form" ) : $( this[ 0 ].form );
};
/*!
* jQuery UI Form Reset Mixin 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Form Reset Mixin
//>>group: Core
//>>description: Refresh input widgets when their form is reset
//>>docs: http://api.jqueryui.com/form-reset-mixin/
var formResetMixin = $.ui.formResetMixin = {
_formResetHandler: function() {
var form = $( this );
// Wait for the form reset to actually happen before refreshing
setTimeout( function() {
var instances = form.data( "ui-form-reset-instances" );
$.each( instances, function() {
this.refresh();
} );
} );
},
_bindFormResetHandler: function() {
this.form = this.element.form();
if ( !this.form.length ) {
return;
}
var instances = this.form.data( "ui-form-reset-instances" ) || [];
if ( !instances.length ) {
// We don't use _on() here because we use a single event handler per form
this.form.on( "reset.ui-form-reset", this._formResetHandler );
}
instances.push( this );
this.form.data( "ui-form-reset-instances", instances );
},
_unbindFormResetHandler: function() {
if ( !this.form.length ) {
return;
}
var instances = this.form.data( "ui-form-reset-instances" );
instances.splice( $.inArray( this, instances ), 1 );
if ( instances.length ) {
this.form.data( "ui-form-reset-instances", instances );
} else {
this.form
.removeData( "ui-form-reset-instances" )
.off( "reset.ui-form-reset" );
}
}
};
/*!
* jQuery UI Support for jQuery core 1.7.x 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
*/
//>>label: jQuery 1.7 Support
//>>group: Core
//>>description: Support version 1.7.x of jQuery core
// Support: jQuery 1.7 only
// Not a great way to check versions, but since we only support 1.7+ and only
// need to detect <1.8, this is a simple check that should suffice. Checking
// for "1.7." would be a bit safer, but the version string is 1.7, not 1.7.0
// and we'll never reach 1.70.0 (if we do, we certainly won't be supporting
// 1.7 anymore). See #11197 for why we're not using feature detection.
if ( $.fn.jquery.substring( 0, 3 ) === "1.7" ) {
// Setters for .innerWidth(), .innerHeight(), .outerWidth(), .outerHeight()
// Unlike jQuery Core 1.8+, these only support numeric values to set the
// dimensions in pixels
$.each( [ "Width", "Height" ], function( i, name ) {
var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
type = name.toLowerCase(),
orig = {
innerWidth: $.fn.innerWidth,
innerHeight: $.fn.innerHeight,
outerWidth: $.fn.outerWidth,
outerHeight: $.fn.outerHeight
};
function reduce( elem, size, border, margin ) {
$.each( side, function() {
size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
if ( border ) {
size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
}
if ( margin ) {
size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
}
} );
return size;
}
$.fn[ "inner" + name ] = function( size ) {
if ( size === undefined ) {
return orig[ "inner" + name ].call( this );
}
return this.each( function() {
$( this ).css( type, reduce( this, size ) + "px" );
} );
};
$.fn[ "outer" + name ] = function( size, margin ) {
if ( typeof size !== "number" ) {
return orig[ "outer" + name ].call( this, size );
}
return this.each( function() {
$( this ).css( type, reduce( this, size, true, margin ) + "px" );
} );
};
} );
$.fn.addBack = function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
};
}
;
/*!
* jQuery UI Keycode 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Keycode
//>>group: Core
//>>description: Provide keycodes as keynames
//>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/
var keycode = $.ui.keyCode = {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
};
// Internal use only
var escapeSelector = $.ui.escapeSelector = ( function() {
var selectorEscape = /([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g;
return function( selector ) {
return selector.replace( selectorEscape, "\\$1" );
};
} )();
/*!
* jQuery UI Labels 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: labels
//>>group: Core
//>>description: Find all the labels associated with a given input
//>>docs: http://api.jqueryui.com/labels/
var labels = $.fn.labels = function() {
var ancestor, selector, id, labels, ancestors;
// Check control.labels first
if ( this[ 0 ].labels && this[ 0 ].labels.length ) {
return this.pushStack( this[ 0 ].labels );
}
// Support: IE <= 11, FF <= 37, Android <= 2.3 only
// Above browsers do not support control.labels. Everything below is to support them
// as well as document fragments. control.labels does not work on document fragments
labels = this.eq( 0 ).parents( "label" );
// Look for the label based on the id
id = this.attr( "id" );
if ( id ) {
// We don't search against the document in case the element
// is disconnected from the DOM
ancestor = this.eq( 0 ).parents().last();
// Get a full set of top level ancestors
ancestors = ancestor.add( ancestor.length ? ancestor.siblings() : this.siblings() );
// Create a selector for the label based on the id
selector = "label[for='" + $.ui.escapeSelector( id ) + "']";
labels = labels.add( ancestors.find( selector ).addBack( selector ) );
}
// Return whatever we have found for labels
return this.pushStack( labels );
};
/*!
* jQuery UI Scroll Parent 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: scrollParent
//>>group: Core
//>>description: Get the closest ancestor element that is scrollable.
//>>docs: http://api.jqueryui.com/scrollParent/
var scrollParent = $.fn.scrollParent = function( includeHidden ) {
var position = this.css( "position" ),
excludeStaticParent = position === "absolute",
overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
scrollParent = this.parents().filter( function() {
var parent = $( this );
if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
return false;
}
return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) +
parent.css( "overflow-x" ) );
} ).eq( 0 );
return position === "fixed" || !scrollParent.length ?
$( this[ 0 ].ownerDocument || document ) :
scrollParent;
};
/*!
* jQuery UI Tabbable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: :tabbable Selector
//>>group: Core
//>>description: Selects elements which can be tabbed to.
//>>docs: http://api.jqueryui.com/tabbable-selector/
var tabbable = $.extend( $.expr[ ":" ], {
tabbable: function( element ) {
var tabIndex = $.attr( element, "tabindex" ),
hasTabindex = tabIndex != null;
return ( !hasTabindex || tabIndex >= 0 ) && $.ui.focusable( element, hasTabindex );
}
} );
/*!
* jQuery UI Unique ID 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: uniqueId
//>>group: Core
//>>description: Functions to generate and remove uniqueId's
//>>docs: http://api.jqueryui.com/uniqueId/
var uniqueId = $.fn.extend( {
uniqueId: ( function() {
var uuid = 0;
return function() {
return this.each( function() {
if ( !this.id ) {
this.id = "ui-id-" + ( ++uuid );
}
} );
};
} )(),
removeUniqueId: function() {
return this.each( function() {
if ( /^ui-id-\d+$/.test( this.id ) ) {
$( this ).removeAttr( "id" );
}
} );
}
} );
// This file is deprecated
var ie = $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
/*!
* jQuery UI Mouse 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Mouse
//>>group: Widgets
//>>description: Abstracts mouse-based interactions to assist in creating certain widgets.
//>>docs: http://api.jqueryui.com/mouse/
var mouseHandled = false;
$( document ).on( "mouseup", function() {
mouseHandled = false;
} );
var widgetsMouse = $.widget( "ui.mouse", {
version: "1.12.1",
options: {
cancel: "input, textarea, button, select, option",
distance: 1,
delay: 0
},
_mouseInit: function() {
var that = this;
this.element
.on( "mousedown." + this.widgetName, function( event ) {
return that._mouseDown( event );
} )
.on( "click." + this.widgetName, function( event ) {
if ( true === $.data( event.target, that.widgetName + ".preventClickEvent" ) ) {
$.removeData( event.target, that.widgetName + ".preventClickEvent" );
event.stopImmediatePropagation();
return false;
}
} );
this.started = false;
},
// TODO: make sure destroying one instance of mouse doesn't mess with
// other instances of mouse
_mouseDestroy: function() {
this.element.off( "." + this.widgetName );
if ( this._mouseMoveDelegate ) {
this.document
.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
.off( "mouseup." + this.widgetName, this._mouseUpDelegate );
}
},
_mouseDown: function( event ) {
// don't let more than one widget handle mouseStart
if ( mouseHandled ) {
return;
}
this._mouseMoved = false;
// We may have missed mouseup (out of window)
( this._mouseStarted && this._mouseUp( event ) );
this._mouseDownEvent = event;
var that = this,
btnIsLeft = ( event.which === 1 ),
// event.target.nodeName works around a bug in IE 8 with
// disabled inputs (#7620)
elIsCancel = ( typeof this.options.cancel === "string" && event.target.nodeName ?
$( event.target ).closest( this.options.cancel ).length : false );
if ( !btnIsLeft || elIsCancel || !this._mouseCapture( event ) ) {
return true;
}
this.mouseDelayMet = !this.options.delay;
if ( !this.mouseDelayMet ) {
this._mouseDelayTimer = setTimeout( function() {
that.mouseDelayMet = true;
}, this.options.delay );
}
if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
this._mouseStarted = ( this._mouseStart( event ) !== false );
if ( !this._mouseStarted ) {
event.preventDefault();
return true;
}
}
// Click event may never have fired (Gecko & Opera)
if ( true === $.data( event.target, this.widgetName + ".preventClickEvent" ) ) {
$.removeData( event.target, this.widgetName + ".preventClickEvent" );
}
// These delegates are required to keep context
this._mouseMoveDelegate = function( event ) {
return that._mouseMove( event );
};
this._mouseUpDelegate = function( event ) {
return that._mouseUp( event );
};
this.document
.on( "mousemove." + this.widgetName, this._mouseMoveDelegate )
.on( "mouseup." + this.widgetName, this._mouseUpDelegate );
event.preventDefault();
mouseHandled = true;
return true;
},
_mouseMove: function( event ) {
// Only check for mouseups outside the document if you've moved inside the document
// at least once. This prevents the firing of mouseup in the case of IE<9, which will
// fire a mousemove event if content is placed under the cursor. See #7778
// Support: IE <9
if ( this._mouseMoved ) {
// IE mouseup check - mouseup happened when mouse was out of window
if ( $.ui.ie && ( !document.documentMode || document.documentMode < 9 ) &&
!event.button ) {
return this._mouseUp( event );
// Iframe mouseup check - mouseup occurred in another document
} else if ( !event.which ) {
// Support: Safari <=8 - 9
// Safari sets which to 0 if you press any of the following keys
// during a drag (#14461)
if ( event.originalEvent.altKey || event.originalEvent.ctrlKey ||
event.originalEvent.metaKey || event.originalEvent.shiftKey ) {
this.ignoreMissingWhich = true;
} else if ( !this.ignoreMissingWhich ) {
return this._mouseUp( event );
}
}
}
if ( event.which || event.button ) {
this._mouseMoved = true;
}
if ( this._mouseStarted ) {
this._mouseDrag( event );
return event.preventDefault();
}
if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
this._mouseStarted =
( this._mouseStart( this._mouseDownEvent, event ) !== false );
( this._mouseStarted ? this._mouseDrag( event ) : this._mouseUp( event ) );
}
return !this._mouseStarted;
},
_mouseUp: function( event ) {
this.document
.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
.off( "mouseup." + this.widgetName, this._mouseUpDelegate );
if ( this._mouseStarted ) {
this._mouseStarted = false;
if ( event.target === this._mouseDownEvent.target ) {
$.data( event.target, this.widgetName + ".preventClickEvent", true );
}
this._mouseStop( event );
}
if ( this._mouseDelayTimer ) {
clearTimeout( this._mouseDelayTimer );
delete this._mouseDelayTimer;
}
this.ignoreMissingWhich = false;
mouseHandled = false;
event.preventDefault();
},
_mouseDistanceMet: function( event ) {
return ( Math.max(
Math.abs( this._mouseDownEvent.pageX - event.pageX ),
Math.abs( this._mouseDownEvent.pageY - event.pageY )
) >= this.options.distance
);
},
_mouseDelayMet: function( /* event */ ) {
return this.mouseDelayMet;
},
// These are placeholder methods, to be overriden by extending plugin
_mouseStart: function( /* event */ ) {},
_mouseDrag: function( /* event */ ) {},
_mouseStop: function( /* event */ ) {},
_mouseCapture: function( /* event */ ) { return true; }
} );
// $.ui.plugin is deprecated. Use $.widget() extensions instead.
var plugin = $.ui.plugin = {
add: function( module, option, set ) {
var i,
proto = $.ui[ module ].prototype;
for ( i in set ) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push( [ option, set[ i ] ] );
}
},
call: function( instance, name, args, allowDisconnected ) {
var i,
set = instance.plugins[ name ];
if ( !set ) {
return;
}
if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode ||
instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
return;
}
for ( i = 0; i < set.length; i++ ) {
if ( instance.options[ set[ i ][ 0 ] ] ) {
set[ i ][ 1 ].apply( instance.element, args );
}
}
}
};
var safeActiveElement = $.ui.safeActiveElement = function( document ) {
var activeElement;
// Support: IE 9 only
// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
try {
activeElement = document.activeElement;
} catch ( error ) {
activeElement = document.body;
}
// Support: IE 9 - 11 only
// IE may return null instead of an element
// Interestingly, this only seems to occur when NOT in an iframe
if ( !activeElement ) {
activeElement = document.body;
}
// Support: IE 11 only
// IE11 returns a seemingly empty object in some cases when accessing
// document.activeElement from an <iframe>
if ( !activeElement.nodeName ) {
activeElement = document.body;
}
return activeElement;
};
var safeBlur = $.ui.safeBlur = function( element ) {
// Support: IE9 - 10 only
// If the <body> is blurred, IE will switch windows, see #9420
if ( element && element.nodeName.toLowerCase() !== "body" ) {
$( element ).trigger( "blur" );
}
};
/*!
* jQuery UI Draggable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Draggable
//>>group: Interactions
//>>description: Enables dragging functionality for any element.
//>>docs: http://api.jqueryui.com/draggable/
//>>demos: http://jqueryui.com/draggable/
//>>css.structure: ../../themes/base/draggable.css
$.widget( "ui.draggable", $.ui.mouse, {
version: "1.12.1",
widgetEventPrefix: "drag",
options: {
addClasses: true,
appendTo: "parent",
axis: false,
connectToSortable: false,
containment: false,
cursor: "auto",
cursorAt: false,
grid: false,
handle: false,
helper: "original",
iframeFix: false,
opacity: false,
refreshPositions: false,
revert: false,
revertDuration: 500,
scope: "default",
scroll: true,
scrollSensitivity: 20,
scrollSpeed: 20,
snap: false,
snapMode: "both",
snapTolerance: 20,
stack: false,
zIndex: false,
// Callbacks
drag: null,
start: null,
stop: null
},
_create: function() {
if ( this.options.helper === "original" ) {
this._setPositionRelative();
}
if ( this.options.addClasses ) {
this._addClass( "ui-draggable" );
}
this._setHandleClassName();
this._mouseInit();
},
_setOption: function( key, value ) {
this._super( key, value );
if ( key === "handle" ) {
this._removeHandleClassName();
this._setHandleClassName();
}
},
_destroy: function() {
if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) {
this.destroyOnClear = true;
return;
}
this._removeHandleClassName();
this._mouseDestroy();
},
_mouseCapture: function( event ) {
var o = this.options;
// Among others, prevent a drag on a resizable-handle
if ( this.helper || o.disabled ||
$( event.target ).closest( ".ui-resizable-handle" ).length > 0 ) {
return false;
}
//Quit if we're not on a valid handle
this.handle = this._getHandle( event );
if ( !this.handle ) {
return false;
}
this._blurActiveElement( event );
this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix );
return true;
},
_blockFrames: function( selector ) {
this.iframeBlocks = this.document.find( selector ).map( function() {
var iframe = $( this );
return $( "<div>" )
.css( "position", "absolute" )
.appendTo( iframe.parent() )
.outerWidth( iframe.outerWidth() )
.outerHeight( iframe.outerHeight() )
.offset( iframe.offset() )[ 0 ];
} );
},
_unblockFrames: function() {
if ( this.iframeBlocks ) {
this.iframeBlocks.remove();
delete this.iframeBlocks;
}
},
_blurActiveElement: function( event ) {
var activeElement = $.ui.safeActiveElement( this.document[ 0 ] ),
target = $( event.target );
// Don't blur if the event occurred on an element that is within
// the currently focused element
// See #10527, #12472
if ( target.closest( activeElement ).length ) {
return;
}
// Blur any element that currently has focus, see #4261
$.ui.safeBlur( activeElement );
},
_mouseStart: function( event ) {
var o = this.options;
//Create and append the visible helper
this.helper = this._createHelper( event );
this._addClass( this.helper, "ui-draggable-dragging" );
//Cache the helper size
this._cacheHelperProportions();
//If ddmanager is used for droppables, set the global draggable
if ( $.ui.ddmanager ) {
$.ui.ddmanager.current = this;
}
/*
* - Position generation -
* This block generates everything position related - it's the core of draggables.
*/
//Cache the margins of the original element
this._cacheMargins();
//Store the helper's css position
this.cssPosition = this.helper.css( "position" );
this.scrollParent = this.helper.scrollParent( true );
this.offsetParent = this.helper.offsetParent();
this.hasFixedAncestor = this.helper.parents().filter( function() {
return $( this ).css( "position" ) === "fixed";
} ).length > 0;
//The element's absolute position on the page minus margins
this.positionAbs = this.element.offset();
this._refreshOffsets( event );
//Generate the original position
this.originalPosition = this.position = this._generatePosition( event, false );
this.originalPageX = event.pageX;
this.originalPageY = event.pageY;
//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
( o.cursorAt && this._adjustOffsetFromHelper( o.cursorAt ) );
//Set a containment if given in the options
this._setContainment();
//Trigger event + callbacks
if ( this._trigger( "start", event ) === false ) {
this._clear();
return false;
}
//Recache the helper size
this._cacheHelperProportions();
//Prepare the droppable offsets
if ( $.ui.ddmanager && !o.dropBehaviour ) {
$.ui.ddmanager.prepareOffsets( this, event );
}
// Execute the drag once - this causes the helper not to be visible before getting its
// correct position
this._mouseDrag( event, true );
// If the ddmanager is used for droppables, inform the manager that dragging has started
// (see #5003)
if ( $.ui.ddmanager ) {
$.ui.ddmanager.dragStart( this, event );
}
return true;
},
_refreshOffsets: function( event ) {
this.offset = {
top: this.positionAbs.top - this.margins.top,
left: this.positionAbs.left - this.margins.left,
scroll: false,
parent: this._getParentOffset(),
relative: this._getRelativeOffset()
};
this.offset.click = {
left: event.pageX - this.offset.left,
top: event.pageY - this.offset.top
};
},
_mouseDrag: function( event, noPropagation ) {
// reset any necessary cached properties (see #5009)
if ( this.hasFixedAncestor ) {
this.offset.parent = this._getParentOffset();
}
//Compute the helpers position
this.position = this._generatePosition( event, true );
this.positionAbs = this._convertPositionTo( "absolute" );
//Call plugins and callbacks and use the resulting position if something is returned
if ( !noPropagation ) {
var ui = this._uiHash();
if ( this._trigger( "drag", event, ui ) === false ) {
this._mouseUp( new $.Event( "mouseup", event ) );
return false;
}
this.position = ui.position;
}
this.helper[ 0 ].style.left = this.position.left + "px";
this.helper[ 0 ].style.top = this.position.top + "px";
if ( $.ui.ddmanager ) {
$.ui.ddmanager.drag( this, event );
}
return false;
},
_mouseStop: function( event ) {
//If we are using droppables, inform the manager about the drop
var that = this,
dropped = false;
if ( $.ui.ddmanager && !this.options.dropBehaviour ) {
dropped = $.ui.ddmanager.drop( this, event );
}
//if a drop comes from outside (a sortable)
if ( this.dropped ) {
dropped = this.dropped;
this.dropped = false;
}
if ( ( this.options.revert === "invalid" && !dropped ) ||
( this.options.revert === "valid" && dropped ) ||
this.options.revert === true || ( $.isFunction( this.options.revert ) &&
this.options.revert.call( this.element, dropped ) )
) {
$( this.helper ).animate(
this.originalPosition,
parseInt( this.options.revertDuration, 10 ),
function() {
if ( that._trigger( "stop", event ) !== false ) {
that._clear();
}
}
);
} else {
if ( this._trigger( "stop", event ) !== false ) {
this._clear();
}
}
return false;
},
_mouseUp: function( event ) {
this._unblockFrames();
// If the ddmanager is used for droppables, inform the manager that dragging has stopped
// (see #5003)
if ( $.ui.ddmanager ) {
$.ui.ddmanager.dragStop( this, event );
}
// Only need to focus if the event occurred on the draggable itself, see #10527
if ( this.handleElement.is( event.target ) ) {
// The interaction is over; whether or not the click resulted in a drag,
// focus the element
this.element.trigger( "focus" );
}
return $.ui.mouse.prototype._mouseUp.call( this, event );
},
cancel: function() {
if ( this.helper.is( ".ui-draggable-dragging" ) ) {
this._mouseUp( new $.Event( "mouseup", { target: this.element[ 0 ] } ) );
} else {
this._clear();
}
return this;
},
_getHandle: function( event ) {
return this.options.handle ?
!!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
true;
},
_setHandleClassName: function() {
this.handleElement = this.options.handle ?
this.element.find( this.options.handle ) : this.element;
this._addClass( this.handleElement, "ui-draggable-handle" );
},
_removeHandleClassName: function() {
this._removeClass( this.handleElement, "ui-draggable-handle" );
},
_createHelper: function( event ) {
var o = this.options,
helperIsFunction = $.isFunction( o.helper ),
helper = helperIsFunction ?
$( o.helper.apply( this.element[ 0 ], [ event ] ) ) :
( o.helper === "clone" ?
this.element.clone().removeAttr( "id" ) :
this.element );
if ( !helper.parents( "body" ).length ) {
helper.appendTo( ( o.appendTo === "parent" ?
this.element[ 0 ].parentNode :
o.appendTo ) );
}
// Http://bugs.jqueryui.com/ticket/9446
// a helper function can return the original element
// which wouldn't have been set to relative in _create
if ( helperIsFunction && helper[ 0 ] === this.element[ 0 ] ) {
this._setPositionRelative();
}
if ( helper[ 0 ] !== this.element[ 0 ] &&
!( /(fixed|absolute)/ ).test( helper.css( "position" ) ) ) {
helper.css( "position", "absolute" );
}
return helper;
},
_setPositionRelative: function() {
if ( !( /^(?:r|a|f)/ ).test( this.element.css( "position" ) ) ) {
this.element[ 0 ].style.position = "relative";
}
},
_adjustOffsetFromHelper: function( obj ) {
if ( typeof obj === "string" ) {
obj = obj.split( " " );
}
if ( $.isArray( obj ) ) {
obj = { left: +obj[ 0 ], top: +obj[ 1 ] || 0 };
}
if ( "left" in obj ) {
this.offset.click.left = obj.left + this.margins.left;
}
if ( "right" in obj ) {
this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
}
if ( "top" in obj ) {
this.offset.click.top = obj.top + this.margins.top;
}
if ( "bottom" in obj ) {
this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
}
},
_isRootNode: function( element ) {
return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ];
},
_getParentOffset: function() {
//Get the offsetParent and cache its position
var po = this.offsetParent.offset(),
document = this.document[ 0 ];
// This is a special case where we need to modify a offset calculated on start, since the
// following happened:
// 1. The position of the helper is absolute, so it's position is calculated based on the
// next positioned parent
// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
// the document, which means that the scroll is included in the initial calculation of the
// offset of the parent, and never recalculated upon drag
if ( this.cssPosition === "absolute" && this.scrollParent[ 0 ] !== document &&
$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) {
po.left += this.scrollParent.scrollLeft();
po.top += this.scrollParent.scrollTop();
}
if ( this._isRootNode( this.offsetParent[ 0 ] ) ) {
po = { top: 0, left: 0 };
}
return {
top: po.top + ( parseInt( this.offsetParent.css( "borderTopWidth" ), 10 ) || 0 ),
left: po.left + ( parseInt( this.offsetParent.css( "borderLeftWidth" ), 10 ) || 0 )
};
},
_getRelativeOffset: function() {
if ( this.cssPosition !== "relative" ) {
return { top: 0, left: 0 };
}
var p = this.element.position(),
scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );
return {
top: p.top - ( parseInt( this.helper.css( "top" ), 10 ) || 0 ) +
( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ),
left: p.left - ( parseInt( this.helper.css( "left" ), 10 ) || 0 ) +
( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 )
};
},
_cacheMargins: function() {
this.margins = {
left: ( parseInt( this.element.css( "marginLeft" ), 10 ) || 0 ),
top: ( parseInt( this.element.css( "marginTop" ), 10 ) || 0 ),
right: ( parseInt( this.element.css( "marginRight" ), 10 ) || 0 ),
bottom: ( parseInt( this.element.css( "marginBottom" ), 10 ) || 0 )
};
},
_cacheHelperProportions: function() {
this.helperProportions = {
width: this.helper.outerWidth(),
height: this.helper.outerHeight()
};
},
_setContainment: function() {
var isUserScrollable, c, ce,
o = this.options,
document = this.document[ 0 ];
this.relativeContainer = null;
if ( !o.containment ) {
this.containment = null;
return;
}
if ( o.containment === "window" ) {
this.containment = [
$( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
$( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top,
$( window ).scrollLeft() + $( window ).width() -
this.helperProportions.width - this.margins.left,
$( window ).scrollTop() +
( $( window ).height() || document.body.parentNode.scrollHeight ) -
this.helperProportions.height - this.margins.top
];
return;
}
if ( o.containment === "document" ) {
this.containment = [
0,
0,
$( document ).width() - this.helperProportions.width - this.margins.left,
( $( document ).height() || document.body.parentNode.scrollHeight ) -
this.helperProportions.height - this.margins.top
];
return;
}
if ( o.containment.constructor === Array ) {
this.containment = o.containment;
return;
}
if ( o.containment === "parent" ) {
o.containment = this.helper[ 0 ].parentNode;
}
c = $( o.containment );
ce = c[ 0 ];
if ( !ce ) {
return;
}
isUserScrollable = /(scroll|auto)/.test( c.css( "overflow" ) );
this.containment = [
( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) +
( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ),
( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) +
( parseInt( c.css( "paddingTop" ), 10 ) || 0 ),
( isUserScrollable ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) -
( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) -
this.helperProportions.width -
this.margins.left -
this.margins.right,
( isUserScrollable ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) -
( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) -
this.helperProportions.height -
this.margins.top -
this.margins.bottom
];
this.relativeContainer = c;
},
_convertPositionTo: function( d, pos ) {
if ( !pos ) {
pos = this.position;
}
var mod = d === "absolute" ? 1 : -1,
scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );
return {
top: (
// The absolute mouse position
pos.top +
// Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.relative.top * mod +
// The offsetParent's offset without borders (offset + border)
this.offset.parent.top * mod -
( ( this.cssPosition === "fixed" ?
-this.offset.scroll.top :
( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod )
),
left: (
// The absolute mouse position
pos.left +
// Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.relative.left * mod +
// The offsetParent's offset without borders (offset + border)
this.offset.parent.left * mod -
( ( this.cssPosition === "fixed" ?
-this.offset.scroll.left :
( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod )
)
};
},
_generatePosition: function( event, constrainPosition ) {
var containment, co, top, left,
o = this.options,
scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ),
pageX = event.pageX,
pageY = event.pageY;
// Cache the scroll
if ( !scrollIsRootNode || !this.offset.scroll ) {
this.offset.scroll = {
top: this.scrollParent.scrollTop(),
left: this.scrollParent.scrollLeft()
};
}
/*
* - Position constraining -
* Constrain the position to a mix of grid, containment.
*/
// If we are not dragging yet, we won't check for options
if ( constrainPosition ) {
if ( this.containment ) {
if ( this.relativeContainer ) {
co = this.relativeContainer.offset();
containment = [
this.containment[ 0 ] + co.left,
this.containment[ 1 ] + co.top,
this.containment[ 2 ] + co.left,
this.containment[ 3 ] + co.top
];
} else {
containment = this.containment;
}
if ( event.pageX - this.offset.click.left < containment[ 0 ] ) {
pageX = containment[ 0 ] + this.offset.click.left;
}
if ( event.pageY - this.offset.click.top < containment[ 1 ] ) {
pageY = containment[ 1 ] + this.offset.click.top;
}
if ( event.pageX - this.offset.click.left > containment[ 2 ] ) {
pageX = containment[ 2 ] + this.offset.click.left;
}
if ( event.pageY - this.offset.click.top > containment[ 3 ] ) {
pageY = containment[ 3 ] + this.offset.click.top;
}
}
if ( o.grid ) {
//Check for grid elements set to 0 to prevent divide by 0 error causing invalid
// argument errors in IE (see ticket #6950)
top = o.grid[ 1 ] ? this.originalPageY + Math.round( ( pageY -
this.originalPageY ) / o.grid[ 1 ] ) * o.grid[ 1 ] : this.originalPageY;
pageY = containment ? ( ( top - this.offset.click.top >= containment[ 1 ] ||
top - this.offset.click.top > containment[ 3 ] ) ?
top :
( ( top - this.offset.click.top >= containment[ 1 ] ) ?
top - o.grid[ 1 ] : top + o.grid[ 1 ] ) ) : top;
left = o.grid[ 0 ] ? this.originalPageX +
Math.round( ( pageX - this.originalPageX ) / o.grid[ 0 ] ) * o.grid[ 0 ] :
this.originalPageX;
pageX = containment ? ( ( left - this.offset.click.left >= containment[ 0 ] ||
left - this.offset.click.left > containment[ 2 ] ) ?
left :
( ( left - this.offset.click.left >= containment[ 0 ] ) ?
left - o.grid[ 0 ] : left + o.grid[ 0 ] ) ) : left;
}
if ( o.axis === "y" ) {
pageX = this.originalPageX;
}
if ( o.axis === "x" ) {
pageY = this.originalPageY;
}
}
return {
top: (
// The absolute mouse position
pageY -
// Click offset (relative to the element)
this.offset.click.top -
// Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.relative.top -
// The offsetParent's offset without borders (offset + border)
this.offset.parent.top +
( this.cssPosition === "fixed" ?
-this.offset.scroll.top :
( scrollIsRootNode ? 0 : this.offset.scroll.top ) )
),
left: (
// The absolute mouse position
pageX -
// Click offset (relative to the element)
this.offset.click.left -
// Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.relative.left -
// The offsetParent's offset without borders (offset + border)
this.offset.parent.left +
( this.cssPosition === "fixed" ?
-this.offset.scroll.left :
( scrollIsRootNode ? 0 : this.offset.scroll.left ) )
)
};
},
_clear: function() {
this._removeClass( this.helper, "ui-draggable-dragging" );
if ( this.helper[ 0 ] !== this.element[ 0 ] && !this.cancelHelperRemoval ) {
this.helper.remove();
}
this.helper = null;
this.cancelHelperRemoval = false;
if ( this.destroyOnClear ) {
this.destroy();
}
},
// From now on bulk stuff - mainly helpers
_trigger: function( type, event, ui ) {
ui = ui || this._uiHash();
$.ui.plugin.call( this, type, [ event, ui, this ], true );
// Absolute position and offset (see #6884 ) have to be recalculated after plugins
if ( /^(drag|start|stop)/.test( type ) ) {
this.positionAbs = this._convertPositionTo( "absolute" );
ui.offset = this.positionAbs;
}
return $.Widget.prototype._trigger.call( this, type, event, ui );
},
plugins: {},
_uiHash: function() {
return {
helper: this.helper,
position: this.position,
originalPosition: this.originalPosition,
offset: this.positionAbs
};
}
} );
$.ui.plugin.add( "draggable", "connectToSortable", {
start: function( event, ui, draggable ) {
var uiSortable = $.extend( {}, ui, {
item: draggable.element
} );
draggable.sortables = [];
$( draggable.options.connectToSortable ).each( function() {
var sortable = $( this ).sortable( "instance" );
if ( sortable && !sortable.options.disabled ) {
draggable.sortables.push( sortable );
// RefreshPositions is called at drag start to refresh the containerCache
// which is used in drag. This ensures it's initialized and synchronized
// with any changes that might have happened on the page since initialization.
sortable.refreshPositions();
sortable._trigger( "activate", event, uiSortable );
}
} );
},
stop: function( event, ui, draggable ) {
var uiSortable = $.extend( {}, ui, {
item: draggable.element
} );
draggable.cancelHelperRemoval = false;
$.each( draggable.sortables, function() {
var sortable = this;
if ( sortable.isOver ) {
sortable.isOver = 0;
// Allow this sortable to handle removing the helper
draggable.cancelHelperRemoval = true;
sortable.cancelHelperRemoval = false;
// Use _storedCSS To restore properties in the sortable,
// as this also handles revert (#9675) since the draggable
// may have modified them in unexpected ways (#8809)
sortable._storedCSS = {
position: sortable.placeholder.css( "position" ),
top: sortable.placeholder.css( "top" ),
left: sortable.placeholder.css( "left" )
};
sortable._mouseStop( event );
// Once drag has ended, the sortable should return to using
// its original helper, not the shared helper from draggable
sortable.options.helper = sortable.options._helper;
} else {
// Prevent this Sortable from removing the helper.
// However, don't set the draggable to remove the helper
// either as another connected Sortable may yet handle the removal.
sortable.cancelHelperRemoval = true;
sortable._trigger( "deactivate", event, uiSortable );
}
} );
},
drag: function( event, ui, draggable ) {
$.each( draggable.sortables, function() {
var innermostIntersecting = false,
sortable = this;
// Copy over variables that sortable's _intersectsWith uses
sortable.positionAbs = draggable.positionAbs;
sortable.helperProportions = draggable.helperProportions;
sortable.offset.click = draggable.offset.click;
if ( sortable._intersectsWith( sortable.containerCache ) ) {
innermostIntersecting = true;
$.each( draggable.sortables, function() {
// Copy over variables that sortable's _intersectsWith uses
this.positionAbs = draggable.positionAbs;
this.helperProportions = draggable.helperProportions;
this.offset.click = draggable.offset.click;
if ( this !== sortable &&
this._intersectsWith( this.containerCache ) &&
$.contains( sortable.element[ 0 ], this.element[ 0 ] ) ) {
innermostIntersecting = false;
}
return innermostIntersecting;
} );
}
if ( innermostIntersecting ) {
// If it intersects, we use a little isOver variable and set it once,
// so that the move-in stuff gets fired only once.
if ( !sortable.isOver ) {
sortable.isOver = 1;
// Store draggable's parent in case we need to reappend to it later.
draggable._parent = ui.helper.parent();
sortable.currentItem = ui.helper
.appendTo( sortable.element )
.data( "ui-sortable-item", true );
// Store helper option to later restore it
sortable.options._helper = sortable.options.helper;
sortable.options.helper = function() {
return ui.helper[ 0 ];
};
// Fire the start events of the sortable with our passed browser event,
// and our own helper (so it doesn't create a new one)
event.target = sortable.currentItem[ 0 ];
sortable._mouseCapture( event, true );
sortable._mouseStart( event, true, true );
// Because the browser event is way off the new appended portlet,
// modify necessary variables to reflect the changes
sortable.offset.click.top = draggable.offset.click.top;
sortable.offset.click.left = draggable.offset.click.left;
sortable.offset.parent.left -= draggable.offset.parent.left -
sortable.offset.parent.left;
sortable.offset.parent.top -= draggable.offset.parent.top -
sortable.offset.parent.top;
draggable._trigger( "toSortable", event );
// Inform draggable that the helper is in a valid drop zone,
// used solely in the revert option to handle "valid/invalid".
draggable.dropped = sortable.element;
// Need to refreshPositions of all sortables in the case that
// adding to one sortable changes the location of the other sortables (#9675)
$.each( draggable.sortables, function() {
this.refreshPositions();
} );
// Hack so receive/update callbacks work (mostly)
draggable.currentItem = draggable.element;
sortable.fromOutside = draggable;
}
if ( sortable.currentItem ) {
sortable._mouseDrag( event );
// Copy the sortable's position because the draggable's can potentially reflect
// a relative position, while sortable is always absolute, which the dragged
// element has now become. (#8809)
ui.position = sortable.position;
}
} else {
// If it doesn't intersect with the sortable, and it intersected before,
// we fake the drag stop of the sortable, but make sure it doesn't remove
// the helper by using cancelHelperRemoval.
if ( sortable.isOver ) {
sortable.isOver = 0;
sortable.cancelHelperRemoval = true;
// Calling sortable's mouseStop would trigger a revert,
// so revert must be temporarily false until after mouseStop is called.
sortable.options._revert = sortable.options.revert;
sortable.options.revert = false;
sortable._trigger( "out", event, sortable._uiHash( sortable ) );
sortable._mouseStop( event, true );
// Restore sortable behaviors that were modfied
// when the draggable entered the sortable area (#9481)
sortable.options.revert = sortable.options._revert;
sortable.options.helper = sortable.options._helper;
if ( sortable.placeholder ) {
sortable.placeholder.remove();
}
// Restore and recalculate the draggable's offset considering the sortable
// may have modified them in unexpected ways. (#8809, #10669)
ui.helper.appendTo( draggable._parent );
draggable._refreshOffsets( event );
ui.position = draggable._generatePosition( event, true );
draggable._trigger( "fromSortable", event );
// Inform draggable that the helper is no longer in a valid drop zone
draggable.dropped = false;
// Need to refreshPositions of all sortables just in case removing
// from one sortable changes the location of other sortables (#9675)
$.each( draggable.sortables, function() {
this.refreshPositions();
} );
}
}
} );
}
} );
$.ui.plugin.add( "draggable", "cursor", {
start: function( event, ui, instance ) {
var t = $( "body" ),
o = instance.options;
if ( t.css( "cursor" ) ) {
o._cursor = t.css( "cursor" );
}
t.css( "cursor", o.cursor );
},
stop: function( event, ui, instance ) {
var o = instance.options;
if ( o._cursor ) {
$( "body" ).css( "cursor", o._cursor );
}
}
} );
$.ui.plugin.add( "draggable", "opacity", {
start: function( event, ui, instance ) {
var t = $( ui.helper ),
o = instance.options;
if ( t.css( "opacity" ) ) {
o._opacity = t.css( "opacity" );
}
t.css( "opacity", o.opacity );
},
stop: function( event, ui, instance ) {
var o = instance.options;
if ( o._opacity ) {
$( ui.helper ).css( "opacity", o._opacity );
}
}
} );
$.ui.plugin.add( "draggable", "scroll", {
start: function( event, ui, i ) {
if ( !i.scrollParentNotHidden ) {
i.scrollParentNotHidden = i.helper.scrollParent( false );
}
if ( i.scrollParentNotHidden[ 0 ] !== i.document[ 0 ] &&
i.scrollParentNotHidden[ 0 ].tagName !== "HTML" ) {
i.overflowOffset = i.scrollParentNotHidden.offset();
}
},
drag: function( event, ui, i ) {
var o = i.options,
scrolled = false,
scrollParent = i.scrollParentNotHidden[ 0 ],
document = i.document[ 0 ];
if ( scrollParent !== document && scrollParent.tagName !== "HTML" ) {
if ( !o.axis || o.axis !== "x" ) {
if ( ( i.overflowOffset.top + scrollParent.offsetHeight ) - event.pageY <
o.scrollSensitivity ) {
scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed;
} else if ( event.pageY - i.overflowOffset.top < o.scrollSensitivity ) {
scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed;
}
}
if ( !o.axis || o.axis !== "y" ) {
if ( ( i.overflowOffset.left + scrollParent.offsetWidth ) - event.pageX <
o.scrollSensitivity ) {
scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed;
} else if ( event.pageX - i.overflowOffset.left < o.scrollSensitivity ) {
scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed;
}
}
} else {
if ( !o.axis || o.axis !== "x" ) {
if ( event.pageY - $( document ).scrollTop() < o.scrollSensitivity ) {
scrolled = $( document ).scrollTop( $( document ).scrollTop() - o.scrollSpeed );
} else if ( $( window ).height() - ( event.pageY - $( document ).scrollTop() ) <
o.scrollSensitivity ) {
scrolled = $( document ).scrollTop( $( document ).scrollTop() + o.scrollSpeed );
}
}
if ( !o.axis || o.axis !== "y" ) {
if ( event.pageX - $( document ).scrollLeft() < o.scrollSensitivity ) {
scrolled = $( document ).scrollLeft(
$( document ).scrollLeft() - o.scrollSpeed
);
} else if ( $( window ).width() - ( event.pageX - $( document ).scrollLeft() ) <
o.scrollSensitivity ) {
scrolled = $( document ).scrollLeft(
$( document ).scrollLeft() + o.scrollSpeed
);
}
}
}
if ( scrolled !== false && $.ui.ddmanager && !o.dropBehaviour ) {
$.ui.ddmanager.prepareOffsets( i, event );
}
}
} );
$.ui.plugin.add( "draggable", "snap", {
start: function( event, ui, i ) {
var o = i.options;
i.snapElements = [];
$( o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap )
.each( function() {
var $t = $( this ),
$o = $t.offset();
if ( this !== i.element[ 0 ] ) {
i.snapElements.push( {
item: this,
width: $t.outerWidth(), height: $t.outerHeight(),
top: $o.top, left: $o.left
} );
}
} );
},
drag: function( event, ui, inst ) {
var ts, bs, ls, rs, l, r, t, b, i, first,
o = inst.options,
d = o.snapTolerance,
x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;
for ( i = inst.snapElements.length - 1; i >= 0; i-- ) {
l = inst.snapElements[ i ].left - inst.margins.left;
r = l + inst.snapElements[ i ].width;
t = inst.snapElements[ i ].top - inst.margins.top;
b = t + inst.snapElements[ i ].height;
if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d ||
!$.contains( inst.snapElements[ i ].item.ownerDocument,
inst.snapElements[ i ].item ) ) {
if ( inst.snapElements[ i ].snapping ) {
( inst.options.snap.release &&
inst.options.snap.release.call(
inst.element,
event,
$.extend( inst._uiHash(), { snapItem: inst.snapElements[ i ].item } )
) );
}
inst.snapElements[ i ].snapping = false;
continue;
}
if ( o.snapMode !== "inner" ) {
ts = Math.abs( t - y2 ) <= d;
bs = Math.abs( b - y1 ) <= d;
ls = Math.abs( l - x2 ) <= d;
rs = Math.abs( r - x1 ) <= d;
if ( ts ) {
ui.position.top = inst._convertPositionTo( "relative", {
top: t - inst.helperProportions.height,
left: 0
} ).top;
}
if ( bs ) {
ui.position.top = inst._convertPositionTo( "relative", {
top: b,
left: 0
} ).top;
}
if ( ls ) {
ui.position.left = inst._convertPositionTo( "relative", {
top: 0,
left: l - inst.helperProportions.width
} ).left;
}
if ( rs ) {
ui.position.left = inst._convertPositionTo( "relative", {
top: 0,
left: r
} ).left;
}
}
first = ( ts || bs || ls || rs );
if ( o.snapMode !== "outer" ) {
ts = Math.abs( t - y1 ) <= d;
bs = Math.abs( b - y2 ) <= d;
ls = Math.abs( l - x1 ) <= d;
rs = Math.abs( r - x2 ) <= d;
if ( ts ) {
ui.position.top = inst._convertPositionTo( "relative", {
top: t,
left: 0
} ).top;
}
if ( bs ) {
ui.position.top = inst._convertPositionTo( "relative", {
top: b - inst.helperProportions.height,
left: 0
} ).top;
}
if ( ls ) {
ui.position.left = inst._convertPositionTo( "relative", {
top: 0,
left: l
} ).left;
}
if ( rs ) {
ui.position.left = inst._convertPositionTo( "relative", {
top: 0,
left: r - inst.helperProportions.width
} ).left;
}
}
if ( !inst.snapElements[ i ].snapping && ( ts || bs || ls || rs || first ) ) {
( inst.options.snap.snap &&
inst.options.snap.snap.call(
inst.element,
event,
$.extend( inst._uiHash(), {
snapItem: inst.snapElements[ i ].item
} ) ) );
}
inst.snapElements[ i ].snapping = ( ts || bs || ls || rs || first );
}
}
} );
$.ui.plugin.add( "draggable", "stack", {
start: function( event, ui, instance ) {
var min,
o = instance.options,
group = $.makeArray( $( o.stack ) ).sort( function( a, b ) {
return ( parseInt( $( a ).css( "zIndex" ), 10 ) || 0 ) -
( parseInt( $( b ).css( "zIndex" ), 10 ) || 0 );
} );
if ( !group.length ) { return; }
min = parseInt( $( group[ 0 ] ).css( "zIndex" ), 10 ) || 0;
$( group ).each( function( i ) {
$( this ).css( "zIndex", min + i );
} );
this.css( "zIndex", ( min + group.length ) );
}
} );
$.ui.plugin.add( "draggable", "zIndex", {
start: function( event, ui, instance ) {
var t = $( ui.helper ),
o = instance.options;
if ( t.css( "zIndex" ) ) {
o._zIndex = t.css( "zIndex" );
}
t.css( "zIndex", o.zIndex );
},
stop: function( event, ui, instance ) {
var o = instance.options;
if ( o._zIndex ) {
$( ui.helper ).css( "zIndex", o._zIndex );
}
}
} );
var widgetsDraggable = $.ui.draggable;
/*!
* jQuery UI Droppable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Droppable
//>>group: Interactions
//>>description: Enables drop targets for draggable elements.
//>>docs: http://api.jqueryui.com/droppable/
//>>demos: http://jqueryui.com/droppable/
$.widget( "ui.droppable", {
version: "1.12.1",
widgetEventPrefix: "drop",
options: {
accept: "*",
addClasses: true,
greedy: false,
scope: "default",
tolerance: "intersect",
// Callbacks
activate: null,
deactivate: null,
drop: null,
out: null,
over: null
},
_create: function() {
var proportions,
o = this.options,
accept = o.accept;
this.isover = false;
this.isout = true;
this.accept = $.isFunction( accept ) ? accept : function( d ) {
return d.is( accept );
};
this.proportions = function( /* valueToWrite */ ) {
if ( arguments.length ) {
// Store the droppable's proportions
proportions = arguments[ 0 ];
} else {
// Retrieve or derive the droppable's proportions
return proportions ?
proportions :
proportions = {
width: this.element[ 0 ].offsetWidth,
height: this.element[ 0 ].offsetHeight
};
}
};
this._addToManager( o.scope );
o.addClasses && this._addClass( "ui-droppable" );
},
_addToManager: function( scope ) {
// Add the reference and positions to the manager
$.ui.ddmanager.droppables[ scope ] = $.ui.ddmanager.droppables[ scope ] || [];
$.ui.ddmanager.droppables[ scope ].push( this );
},
_splice: function( drop ) {
var i = 0;
for ( ; i < drop.length; i++ ) {
if ( drop[ i ] === this ) {
drop.splice( i, 1 );
}
}
},
_destroy: function() {
var drop = $.ui.ddmanager.droppables[ this.options.scope ];
this._splice( drop );
},
_setOption: function( key, value ) {
if ( key === "accept" ) {
this.accept = $.isFunction( value ) ? value : function( d ) {
return d.is( value );
};
} else if ( key === "scope" ) {
var drop = $.ui.ddmanager.droppables[ this.options.scope ];
this._splice( drop );
this._addToManager( value );
}
this._super( key, value );
},
_activate: function( event ) {
var draggable = $.ui.ddmanager.current;
this._addActiveClass();
if ( draggable ) {
this._trigger( "activate", event, this.ui( draggable ) );
}
},
_deactivate: function( event ) {
var draggable = $.ui.ddmanager.current;
this._removeActiveClass();
if ( draggable ) {
this._trigger( "deactivate", event, this.ui( draggable ) );
}
},
_over: function( event ) {
var draggable = $.ui.ddmanager.current;
// Bail if draggable and droppable are same element
if ( !draggable || ( draggable.currentItem ||
draggable.element )[ 0 ] === this.element[ 0 ] ) {
return;
}
if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem ||
draggable.element ) ) ) {
this._addHoverClass();
this._trigger( "over", event, this.ui( draggable ) );
}
},
_out: function( event ) {
var draggable = $.ui.ddmanager.current;
// Bail if draggable and droppable are same element
if ( !draggable || ( draggable.currentItem ||
draggable.element )[ 0 ] === this.element[ 0 ] ) {
return;
}
if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem ||
draggable.element ) ) ) {
this._removeHoverClass();
this._trigger( "out", event, this.ui( draggable ) );
}
},
_drop: function( event, custom ) {
var draggable = custom || $.ui.ddmanager.current,
childrenIntersection = false;
// Bail if draggable and droppable are same element
if ( !draggable || ( draggable.currentItem ||
draggable.element )[ 0 ] === this.element[ 0 ] ) {
return false;
}
this.element
.find( ":data(ui-droppable)" )
.not( ".ui-draggable-dragging" )
.each( function() {
var inst = $( this ).droppable( "instance" );
if (
inst.options.greedy &&
!inst.options.disabled &&
inst.options.scope === draggable.options.scope &&
inst.accept.call(
inst.element[ 0 ], ( draggable.currentItem || draggable.element )
) &&
intersect(
draggable,
$.extend( inst, { offset: inst.element.offset() } ),
inst.options.tolerance, event
)
) {
childrenIntersection = true;
return false; }
} );
if ( childrenIntersection ) {
return false;
}
if ( this.accept.call( this.element[ 0 ],
( draggable.currentItem || draggable.element ) ) ) {
this._removeActiveClass();
this._removeHoverClass();
this._trigger( "drop", event, this.ui( draggable ) );
return this.element;
}
return false;
},
ui: function( c ) {
return {
draggable: ( c.currentItem || c.element ),
helper: c.helper,
position: c.position,
offset: c.positionAbs
};
},
// Extension points just to make backcompat sane and avoid duplicating logic
// TODO: Remove in 1.13 along with call to it below
_addHoverClass: function() {
this._addClass( "ui-droppable-hover" );
},
_removeHoverClass: function() {
this._removeClass( "ui-droppable-hover" );
},
_addActiveClass: function() {
this._addClass( "ui-droppable-active" );
},
_removeActiveClass: function() {
this._removeClass( "ui-droppable-active" );
}
} );
var intersect = $.ui.intersect = ( function() {
function isOverAxis( x, reference, size ) {
return ( x >= reference ) && ( x < ( reference + size ) );
}
return function( draggable, droppable, toleranceMode, event ) {
if ( !droppable.offset ) {
return false;
}
var x1 = ( draggable.positionAbs ||
draggable.position.absolute ).left + draggable.margins.left,
y1 = ( draggable.positionAbs ||
draggable.position.absolute ).top + draggable.margins.top,
x2 = x1 + draggable.helperProportions.width,
y2 = y1 + draggable.helperProportions.height,
l = droppable.offset.left,
t = droppable.offset.top,
r = l + droppable.proportions().width,
b = t + droppable.proportions().height;
switch ( toleranceMode ) {
case "fit":
return ( l <= x1 && x2 <= r && t <= y1 && y2 <= b );
case "intersect":
return ( l < x1 + ( draggable.helperProportions.width / 2 ) && // Right Half
x2 - ( draggable.helperProportions.width / 2 ) < r && // Left Half
t < y1 + ( draggable.helperProportions.height / 2 ) && // Bottom Half
y2 - ( draggable.helperProportions.height / 2 ) < b ); // Top Half
case "pointer":
return isOverAxis( event.pageY, t, droppable.proportions().height ) &&
isOverAxis( event.pageX, l, droppable.proportions().width );
case "touch":
return (
( y1 >= t && y1 <= b ) || // Top edge touching
( y2 >= t && y2 <= b ) || // Bottom edge touching
( y1 < t && y2 > b ) // Surrounded vertically
) && (
( x1 >= l && x1 <= r ) || // Left edge touching
( x2 >= l && x2 <= r ) || // Right edge touching
( x1 < l && x2 > r ) // Surrounded horizontally
);
default:
return false;
}
};
} )();
/*
This manager tracks offsets of draggables and droppables
*/
$.ui.ddmanager = {
current: null,
droppables: { "default": [] },
prepareOffsets: function( t, event ) {
var i, j,
m = $.ui.ddmanager.droppables[ t.options.scope ] || [],
type = event ? event.type : null, // workaround for #2317
list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack();
droppablesLoop: for ( i = 0; i < m.length; i++ ) {
// No disabled and non-accepted
if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ],
( t.currentItem || t.element ) ) ) ) {
continue;
}
// Filter out elements in the current dragged item
for ( j = 0; j < list.length; j++ ) {
if ( list[ j ] === m[ i ].element[ 0 ] ) {
m[ i ].proportions().height = 0;
continue droppablesLoop;
}
}
m[ i ].visible = m[ i ].element.css( "display" ) !== "none";
if ( !m[ i ].visible ) {
continue;
}
// Activate the droppable if used directly from draggables
if ( type === "mousedown" ) {
m[ i ]._activate.call( m[ i ], event );
}
m[ i ].offset = m[ i ].element.offset();
m[ i ].proportions( {
width: m[ i ].element[ 0 ].offsetWidth,
height: m[ i ].element[ 0 ].offsetHeight
} );
}
},
drop: function( draggable, event ) {
var dropped = false;
// Create a copy of the droppables in case the list changes during the drop (#9116)
$.each( ( $.ui.ddmanager.droppables[ draggable.options.scope ] || [] ).slice(), function() {
if ( !this.options ) {
return;
}
if ( !this.options.disabled && this.visible &&
intersect( draggable, this, this.options.tolerance, event ) ) {
dropped = this._drop.call( this, event ) || dropped;
}
if ( !this.options.disabled && this.visible && this.accept.call( this.element[ 0 ],
( draggable.currentItem || draggable.element ) ) ) {
this.isout = true;
this.isover = false;
this._deactivate.call( this, event );
}
} );
return dropped;
},
dragStart: function( draggable, event ) {
// Listen for scrolling so that if the dragging causes scrolling the position of the
// droppables can be recalculated (see #5003)
draggable.element.parentsUntil( "body" ).on( "scroll.droppable", function() {
if ( !draggable.options.refreshPositions ) {
$.ui.ddmanager.prepareOffsets( draggable, event );
}
} );
},
drag: function( draggable, event ) {
// If you have a highly dynamic page, you might try this option. It renders positions
// every time you move the mouse.
if ( draggable.options.refreshPositions ) {
$.ui.ddmanager.prepareOffsets( draggable, event );
}
// Run through all droppables and check their positions based on specific tolerance options
$.each( $.ui.ddmanager.droppables[ draggable.options.scope ] || [], function() {
if ( this.options.disabled || this.greedyChild || !this.visible ) {
return;
}
var parentInstance, scope, parent,
intersects = intersect( draggable, this, this.options.tolerance, event ),
c = !intersects && this.isover ?
"isout" :
( intersects && !this.isover ? "isover" : null );
if ( !c ) {
return;
}
if ( this.options.greedy ) {
// find droppable parents with same scope
scope = this.options.scope;
parent = this.element.parents( ":data(ui-droppable)" ).filter( function() {
return $( this ).droppable( "instance" ).options.scope === scope;
} );
if ( parent.length ) {
parentInstance = $( parent[ 0 ] ).droppable( "instance" );
parentInstance.greedyChild = ( c === "isover" );
}
}
// We just moved into a greedy child
if ( parentInstance && c === "isover" ) {
parentInstance.isover = false;
parentInstance.isout = true;
parentInstance._out.call( parentInstance, event );
}
this[ c ] = true;
this[ c === "isout" ? "isover" : "isout" ] = false;
this[ c === "isover" ? "_over" : "_out" ].call( this, event );
// We just moved out of a greedy child
if ( parentInstance && c === "isout" ) {
parentInstance.isout = false;
parentInstance.isover = true;
parentInstance._over.call( parentInstance, event );
}
} );
},
dragStop: function( draggable, event ) {
draggable.element.parentsUntil( "body" ).off( "scroll.droppable" );
// Call prepareOffsets one final time since IE does not fire return scroll events when
// overflow was caused by drag (see #5003)
if ( !draggable.options.refreshPositions ) {
$.ui.ddmanager.prepareOffsets( draggable, event );
}
}
};
// DEPRECATED
// TODO: switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat !== false ) {
// Backcompat for activeClass and hoverClass options
$.widget( "ui.droppable", $.ui.droppable, {
options: {
hoverClass: false,
activeClass: false
},
_addActiveClass: function() {
this._super();
if ( this.options.activeClass ) {
this.element.addClass( this.options.activeClass );
}
},
_removeActiveClass: function() {
this._super();
if ( this.options.activeClass ) {
this.element.removeClass( this.options.activeClass );
}
},
_addHoverClass: function() {
this._super();
if ( this.options.hoverClass ) {
this.element.addClass( this.options.hoverClass );
}
},
_removeHoverClass: function() {
this._super();
if ( this.options.hoverClass ) {
this.element.removeClass( this.options.hoverClass );
}
}
} );
}
var widgetsDroppable = $.ui.droppable;
/*!
* jQuery UI Selectable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Selectable
//>>group: Interactions
//>>description: Allows groups of elements to be selected with the mouse.
//>>docs: http://api.jqueryui.com/selectable/
//>>demos: http://jqueryui.com/selectable/
//>>css.structure: ../../themes/base/selectable.css
var widgetsSelectable = $.widget( "ui.selectable", $.ui.mouse, {
version: "1.12.1",
options: {
appendTo: "body",
autoRefresh: true,
distance: 0,
filter: "*",
tolerance: "touch",
// Callbacks
selected: null,
selecting: null,
start: null,
stop: null,
unselected: null,
unselecting: null
},
_create: function() {
var that = this;
this._addClass( "ui-selectable" );
this.dragged = false;
// Cache selectee children based on filter
this.refresh = function() {
that.elementPos = $( that.element[ 0 ] ).offset();
that.selectees = $( that.options.filter, that.element[ 0 ] );
that._addClass( that.selectees, "ui-selectee" );
that.selectees.each( function() {
var $this = $( this ),
selecteeOffset = $this.offset(),
pos = {
left: selecteeOffset.left - that.elementPos.left,
top: selecteeOffset.top - that.elementPos.top
};
$.data( this, "selectable-item", {
element: this,
$element: $this,
left: pos.left,
top: pos.top,
right: pos.left + $this.outerWidth(),
bottom: pos.top + $this.outerHeight(),
startselected: false,
selected: $this.hasClass( "ui-selected" ),
selecting: $this.hasClass( "ui-selecting" ),
unselecting: $this.hasClass( "ui-unselecting" )
} );
} );
};
this.refresh();
this._mouseInit();
this.helper = $( "<div>" );
this._addClass( this.helper, "ui-selectable-helper" );
},
_destroy: function() {
this.selectees.removeData( "selectable-item" );
this._mouseDestroy();
},
_mouseStart: function( event ) {
var that = this,
options = this.options;
this.opos = [ event.pageX, event.pageY ];
this.elementPos = $( this.element[ 0 ] ).offset();
if ( this.options.disabled ) {
return;
}
this.selectees = $( options.filter, this.element[ 0 ] );
this._trigger( "start", event );
$( options.appendTo ).append( this.helper );
// position helper (lasso)
this.helper.css( {
"left": event.pageX,
"top": event.pageY,
"width": 0,
"height": 0
} );
if ( options.autoRefresh ) {
this.refresh();
}
this.selectees.filter( ".ui-selected" ).each( function() {
var selectee = $.data( this, "selectable-item" );
selectee.startselected = true;
if ( !event.metaKey && !event.ctrlKey ) {
that._removeClass( selectee.$element, "ui-selected" );
selectee.selected = false;
that._addClass( selectee.$element, "ui-unselecting" );
selectee.unselecting = true;
// selectable UNSELECTING callback
that._trigger( "unselecting", event, {
unselecting: selectee.element
} );
}
} );
$( event.target ).parents().addBack().each( function() {
var doSelect,
selectee = $.data( this, "selectable-item" );
if ( selectee ) {
doSelect = ( !event.metaKey && !event.ctrlKey ) ||
!selectee.$element.hasClass( "ui-selected" );
that._removeClass( selectee.$element, doSelect ? "ui-unselecting" : "ui-selected" )
._addClass( selectee.$element, doSelect ? "ui-selecting" : "ui-unselecting" );
selectee.unselecting = !doSelect;
selectee.selecting = doSelect;
selectee.selected = doSelect;
// selectable (UN)SELECTING callback
if ( doSelect ) {
that._trigger( "selecting", event, {
selecting: selectee.element
} );
} else {
that._trigger( "unselecting", event, {
unselecting: selectee.element
} );
}
return false;
}
} );
},
_mouseDrag: function( event ) {
this.dragged = true;
if ( this.options.disabled ) {
return;
}
var tmp,
that = this,
options = this.options,
x1 = this.opos[ 0 ],
y1 = this.opos[ 1 ],
x2 = event.pageX,
y2 = event.pageY;
if ( x1 > x2 ) { tmp = x2; x2 = x1; x1 = tmp; }
if ( y1 > y2 ) { tmp = y2; y2 = y1; y1 = tmp; }
this.helper.css( { left: x1, top: y1, width: x2 - x1, height: y2 - y1 } );
this.selectees.each( function() {
var selectee = $.data( this, "selectable-item" ),
hit = false,
offset = {};
//prevent helper from being selected if appendTo: selectable
if ( !selectee || selectee.element === that.element[ 0 ] ) {
return;
}
offset.left = selectee.left + that.elementPos.left;
offset.right = selectee.right + that.elementPos.left;
offset.top = selectee.top + that.elementPos.top;
offset.bottom = selectee.bottom + that.elementPos.top;
if ( options.tolerance === "touch" ) {
hit = ( !( offset.left > x2 || offset.right < x1 || offset.top > y2 ||
offset.bottom < y1 ) );
} else if ( options.tolerance === "fit" ) {
hit = ( offset.left > x1 && offset.right < x2 && offset.top > y1 &&
offset.bottom < y2 );
}
if ( hit ) {
// SELECT
if ( selectee.selected ) {
that._removeClass( selectee.$element, "ui-selected" );
selectee.selected = false;
}
if ( selectee.unselecting ) {
that._removeClass( selectee.$element, "ui-unselecting" );
selectee.unselecting = false;
}
if ( !selectee.selecting ) {
that._addClass( selectee.$element, "ui-selecting" );
selectee.selecting = true;
// selectable SELECTING callback
that._trigger( "selecting", event, {
selecting: selectee.element
} );
}
} else {
// UNSELECT
if ( selectee.selecting ) {
if ( ( event.metaKey || event.ctrlKey ) && selectee.startselected ) {
that._removeClass( selectee.$element, "ui-selecting" );
selectee.selecting = false;
that._addClass( selectee.$element, "ui-selected" );
selectee.selected = true;
} else {
that._removeClass( selectee.$element, "ui-selecting" );
selectee.selecting = false;
if ( selectee.startselected ) {
that._addClass( selectee.$element, "ui-unselecting" );
selectee.unselecting = true;
}
// selectable UNSELECTING callback
that._trigger( "unselecting", event, {
unselecting: selectee.element
} );
}
}
if ( selectee.selected ) {
if ( !event.metaKey && !event.ctrlKey && !selectee.startselected ) {
that._removeClass( selectee.$element, "ui-selected" );
selectee.selected = false;
that._addClass( selectee.$element, "ui-unselecting" );
selectee.unselecting = true;
// selectable UNSELECTING callback
that._trigger( "unselecting", event, {
unselecting: selectee.element
} );
}
}
}
} );
return false;
},
_mouseStop: function( event ) {
var that = this;
this.dragged = false;
$( ".ui-unselecting", this.element[ 0 ] ).each( function() {
var selectee = $.data( this, "selectable-item" );
that._removeClass( selectee.$element, "ui-unselecting" );
selectee.unselecting = false;
selectee.startselected = false;
that._trigger( "unselected", event, {
unselected: selectee.element
} );
} );
$( ".ui-selecting", this.element[ 0 ] ).each( function() {
var selectee = $.data( this, "selectable-item" );
that._removeClass( selectee.$element, "ui-selecting" )
._addClass( selectee.$element, "ui-selected" );
selectee.selecting = false;
selectee.selected = true;
selectee.startselected = true;
that._trigger( "selected", event, {
selected: selectee.element
} );
} );
this._trigger( "stop", event );
this.helper.remove();
return false;
}
} );
/*!
* jQuery UI Sortable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Sortable
//>>group: Interactions
//>>description: Enables items in a list to be sorted using the mouse.
//>>docs: http://api.jqueryui.com/sortable/
//>>demos: http://jqueryui.com/sortable/
//>>css.structure: ../../themes/base/sortable.css
var widgetsSortable = $.widget( "ui.sortable", $.ui.mouse, {
version: "1.12.1",
widgetEventPrefix: "sort",
ready: false,
options: {
appendTo: "parent",
axis: false,
connectWith: false,
containment: false,
cursor: "auto",
cursorAt: false,
dropOnEmpty: true,
forcePlaceholderSize: false,
forceHelperSize: false,
grid: false,
handle: false,
helper: "original",
items: "> *",
opacity: false,
placeholder: false,
revert: false,
scroll: true,
scrollSensitivity: 20,
scrollSpeed: 20,
scope: "default",
tolerance: "intersect",
zIndex: 1000,
// Callbacks
activate: null,
beforeStop: null,
change: null,
deactivate: null,
out: null,
over: null,
receive: null,
remove: null,
sort: null,
start: null,
stop: null,
update: null
},
_isOverAxis: function( x, reference, size ) {
return ( x >= reference ) && ( x < ( reference + size ) );
},
_isFloating: function( item ) {
return ( /left|right/ ).test( item.css( "float" ) ) ||
( /inline|table-cell/ ).test( item.css( "display" ) );
},
_create: function() {
this.containerCache = {};
this._addClass( "ui-sortable" );
//Get the items
this.refresh();
//Let's determine the parent's offset
this.offset = this.element.offset();
//Initialize mouse events for interaction
this._mouseInit();
this._setHandleClassName();
//We're ready to go
this.ready = true;
},
_setOption: function( key, value ) {
this._super( key, value );
if ( key === "handle" ) {
this._setHandleClassName();
}
},
_setHandleClassName: function() {
var that = this;
this._removeClass( this.element.find( ".ui-sortable-handle" ), "ui-sortable-handle" );
$.each( this.items, function() {
that._addClass(
this.instance.options.handle ?
this.item.find( this.instance.options.handle ) :
this.item,
"ui-sortable-handle"
);
} );
},
_destroy: function() {
this._mouseDestroy();
for ( var i = this.items.length - 1; i >= 0; i-- ) {
this.items[ i ].item.removeData( this.widgetName + "-item" );
}
return this;
},
_mouseCapture: function( event, overrideHandle ) {
var currentItem = null,
validHandle = false,
that = this;
if ( this.reverting ) {
return false;
}
if ( this.options.disabled || this.options.type === "static" ) {
return false;
}
//We have to refresh the items data once first
this._refreshItems( event );
//Find out if the clicked node (or one of its parents) is a actual item in this.items
$( event.target ).parents().each( function() {
if ( $.data( this, that.widgetName + "-item" ) === that ) {
currentItem = $( this );
return false;
}
} );
if ( $.data( event.target, that.widgetName + "-item" ) === that ) {
currentItem = $( event.target );
}
if ( !currentItem ) {
return false;
}
if ( this.options.handle && !overrideHandle ) {
$( this.options.handle, currentItem ).find( "*" ).addBack().each( function() {
if ( this === event.target ) {
validHandle = true;
}
} );
if ( !validHandle ) {
return false;
}
}
this.currentItem = currentItem;
this._removeCurrentsFromItems();
return true;
},
_mouseStart: function( event, overrideHandle, noActivation ) {
var i, body,
o = this.options;
this.currentContainer = this;
//We only need to call refreshPositions, because the refreshItems call has been moved to
// mouseCapture
this.refreshPositions();
//Create and append the visible helper
this.helper = this._createHelper( event );
//Cache the helper size
this._cacheHelperProportions();
/*
* - Position generation -
* This block generates everything position related - it's the core of draggables.
*/
//Cache the margins of the original element
this._cacheMargins();
//Get the next scrolling parent
this.scrollParent = this.helper.scrollParent();
//The element's absolute position on the page minus margins
this.offset = this.currentItem.offset();
this.offset = {
top: this.offset.top - this.margins.top,
left: this.offset.left - this.margins.left
};
$.extend( this.offset, {
click: { //Where the click happened, relative to the element
left: event.pageX - this.offset.left,
top: event.pageY - this.offset.top
},
parent: this._getParentOffset(),
// This is a relative to absolute position minus the actual position calculation -
// only used for relative positioned helper
relative: this._getRelativeOffset()
} );
// Only after we got the offset, we can change the helper's position to absolute
// TODO: Still need to figure out a way to make relative sorting possible
this.helper.css( "position", "absolute" );
this.cssPosition = this.helper.css( "position" );
//Generate the original position
this.originalPosition = this._generatePosition( event );
this.originalPageX = event.pageX;
this.originalPageY = event.pageY;
//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
( o.cursorAt && this._adjustOffsetFromHelper( o.cursorAt ) );
//Cache the former DOM position
this.domPosition = {
prev: this.currentItem.prev()[ 0 ],
parent: this.currentItem.parent()[ 0 ]
};
// If the helper is not the original, hide the original so it's not playing any role during
// the drag, won't cause anything bad this way
if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) {
this.currentItem.hide();
}
//Create the placeholder
this._createPlaceholder();
//Set a containment if given in the options
if ( o.containment ) {
this._setContainment();
}
if ( o.cursor && o.cursor !== "auto" ) { // cursor option
body = this.document.find( "body" );
// Support: IE
this.storedCursor = body.css( "cursor" );
body.css( "cursor", o.cursor );
this.storedStylesheet =
$( "<style>*{ cursor: " + o.cursor + " !important; }</style>" ).appendTo( body );
}
if ( o.opacity ) { // opacity option
if ( this.helper.css( "opacity" ) ) {
this._storedOpacity = this.helper.css( "opacity" );
}
this.helper.css( "opacity", o.opacity );
}
if ( o.zIndex ) { // zIndex option
if ( this.helper.css( "zIndex" ) ) {
this._storedZIndex = this.helper.css( "zIndex" );
}
this.helper.css( "zIndex", o.zIndex );
}
//Prepare scrolling
if ( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
this.scrollParent[ 0 ].tagName !== "HTML" ) {
this.overflowOffset = this.scrollParent.offset();
}
//Call callbacks
this._trigger( "start", event, this._uiHash() );
//Recache the helper size
if ( !this._preserveHelperProportions ) {
this._cacheHelperProportions();
}
//Post "activate" events to possible containers
if ( !noActivation ) {
for ( i = this.containers.length - 1; i >= 0; i-- ) {
this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
}
}
//Prepare possible droppables
if ( $.ui.ddmanager ) {
$.ui.ddmanager.current = this;
}
if ( $.ui.ddmanager && !o.dropBehaviour ) {
$.ui.ddmanager.prepareOffsets( this, event );
}
this.dragging = true;
this._addClass( this.helper, "ui-sortable-helper" );
// Execute the drag once - this causes the helper not to be visiblebefore getting its
// correct position
this._mouseDrag( event );
return true;
},
_mouseDrag: function( event ) {
var i, item, itemElement, intersection,
o = this.options,
scrolled = false;
//Compute the helpers position
this.position = this._generatePosition( event );
this.positionAbs = this._convertPositionTo( "absolute" );
if ( !this.lastPositionAbs ) {
this.lastPositionAbs = this.positionAbs;
}
//Do scrolling
if ( this.options.scroll ) {
if ( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
this.scrollParent[ 0 ].tagName !== "HTML" ) {
if ( ( this.overflowOffset.top + this.scrollParent[ 0 ].offsetHeight ) -
event.pageY < o.scrollSensitivity ) {
this.scrollParent[ 0 ].scrollTop =
scrolled = this.scrollParent[ 0 ].scrollTop + o.scrollSpeed;
} else if ( event.pageY - this.overflowOffset.top < o.scrollSensitivity ) {
this.scrollParent[ 0 ].scrollTop =
scrolled = this.scrollParent[ 0 ].scrollTop - o.scrollSpeed;
}
if ( ( this.overflowOffset.left + this.scrollParent[ 0 ].offsetWidth ) -
event.pageX < o.scrollSensitivity ) {
this.scrollParent[ 0 ].scrollLeft = scrolled =
this.scrollParent[ 0 ].scrollLeft + o.scrollSpeed;
} else if ( event.pageX - this.overflowOffset.left < o.scrollSensitivity ) {
this.scrollParent[ 0 ].scrollLeft = scrolled =
this.scrollParent[ 0 ].scrollLeft - o.scrollSpeed;
}
} else {
if ( event.pageY - this.document.scrollTop() < o.scrollSensitivity ) {
scrolled = this.document.scrollTop( this.document.scrollTop() - o.scrollSpeed );
} else if ( this.window.height() - ( event.pageY - this.document.scrollTop() ) <
o.scrollSensitivity ) {
scrolled = this.document.scrollTop( this.document.scrollTop() + o.scrollSpeed );
}
if ( event.pageX - this.document.scrollLeft() < o.scrollSensitivity ) {
scrolled = this.document.scrollLeft(
this.document.scrollLeft() - o.scrollSpeed
);
} else if ( this.window.width() - ( event.pageX - this.document.scrollLeft() ) <
o.scrollSensitivity ) {
scrolled = this.document.scrollLeft(
this.document.scrollLeft() + o.scrollSpeed
);
}
}
if ( scrolled !== false && $.ui.ddmanager && !o.dropBehaviour ) {
$.ui.ddmanager.prepareOffsets( this, event );
}
}
//Regenerate the absolute position used for position checks
this.positionAbs = this._convertPositionTo( "absolute" );
//Set the helper position
if ( !this.options.axis || this.options.axis !== "y" ) {
this.helper[ 0 ].style.left = this.position.left + "px";
}
if ( !this.options.axis || this.options.axis !== "x" ) {
this.helper[ 0 ].style.top = this.position.top + "px";
}
//Rearrange
for ( i = this.items.length - 1; i >= 0; i-- ) {
//Cache variables and intersection, continue if no intersection
item = this.items[ i ];
itemElement = item.item[ 0 ];
intersection = this._intersectsWithPointer( item );
if ( !intersection ) {
continue;
}
// Only put the placeholder inside the current Container, skip all
// items from other containers. This works because when moving
// an item from one container to another the
// currentContainer is switched before the placeholder is moved.
//
// Without this, moving items in "sub-sortables" can cause
// the placeholder to jitter between the outer and inner container.
if ( item.instance !== this.currentContainer ) {
continue;
}
// Cannot intersect with itself
// no useless actions that have been done before
// no action if the item moved is the parent of the item checked
if ( itemElement !== this.currentItem[ 0 ] &&
this.placeholder[ intersection === 1 ? "next" : "prev" ]()[ 0 ] !== itemElement &&
!$.contains( this.placeholder[ 0 ], itemElement ) &&
( this.options.type === "semi-dynamic" ?
!$.contains( this.element[ 0 ], itemElement ) :
true
)
) {
this.direction = intersection === 1 ? "down" : "up";
if ( this.options.tolerance === "pointer" || this._intersectsWithSides( item ) ) {
this._rearrange( event, item );
} else {
break;
}
this._trigger( "change", event, this._uiHash() );
break;
}
}
//Post events to containers
this._contactContainers( event );
//Interconnect with droppables
if ( $.ui.ddmanager ) {
$.ui.ddmanager.drag( this, event );
}
//Call callbacks
this._trigger( "sort", event, this._uiHash() );
this.lastPositionAbs = this.positionAbs;
return false;
},
_mouseStop: function( event, noPropagation ) {
if ( !event ) {
return;
}
//If we are using droppables, inform the manager about the drop
if ( $.ui.ddmanager && !this.options.dropBehaviour ) {
$.ui.ddmanager.drop( this, event );
}
if ( this.options.revert ) {
var that = this,
cur = this.placeholder.offset(),
axis = this.options.axis,
animation = {};
if ( !axis || axis === "x" ) {
animation.left = cur.left - this.offset.parent.left - this.margins.left +
( this.offsetParent[ 0 ] === this.document[ 0 ].body ?
0 :
this.offsetParent[ 0 ].scrollLeft
);
}
if ( !axis || axis === "y" ) {
animation.top = cur.top - this.offset.parent.top - this.margins.top +
( this.offsetParent[ 0 ] === this.document[ 0 ].body ?
0 :
this.offsetParent[ 0 ].scrollTop
);
}
this.reverting = true;
$( this.helper ).animate(
animation,
parseInt( this.options.revert, 10 ) || 500,
function() {
that._clear( event );
}
);
} else {
this._clear( event, noPropagation );
}
return false;
},
cancel: function() {
if ( this.dragging ) {
this._mouseUp( new $.Event( "mouseup", { target: null } ) );
if ( this.options.helper === "original" ) {
this.currentItem.css( this._storedCSS );
this._removeClass( this.currentItem, "ui-sortable-helper" );
} else {
this.currentItem.show();
}
//Post deactivating events to containers
for ( var i = this.containers.length - 1; i >= 0; i-- ) {
this.containers[ i ]._trigger( "deactivate", null, this._uiHash( this ) );
if ( this.containers[ i ].containerCache.over ) {
this.containers[ i ]._trigger( "out", null, this._uiHash( this ) );
this.containers[ i ].containerCache.over = 0;
}
}
}
if ( this.placeholder ) {
//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately,
// it unbinds ALL events from the original node!
if ( this.placeholder[ 0 ].parentNode ) {
this.placeholder[ 0 ].parentNode.removeChild( this.placeholder[ 0 ] );
}
if ( this.options.helper !== "original" && this.helper &&
this.helper[ 0 ].parentNode ) {
this.helper.remove();
}
$.extend( this, {
helper: null,
dragging: false,
reverting: false,
_noFinalSort: null
} );
if ( this.domPosition.prev ) {
$( this.domPosition.prev ).after( this.currentItem );
} else {
$( this.domPosition.parent ).prepend( this.currentItem );
}
}
return this;
},
serialize: function( o ) {
var items = this._getItemsAsjQuery( o && o.connected ),
str = [];
o = o || {};
$( items ).each( function() {
var res = ( $( o.item || this ).attr( o.attribute || "id" ) || "" )
.match( o.expression || ( /(.+)[\-=_](.+)/ ) );
if ( res ) {
str.push(
( o.key || res[ 1 ] + "[]" ) +
"=" + ( o.key && o.expression ? res[ 1 ] : res[ 2 ] ) );
}
} );
if ( !str.length && o.key ) {
str.push( o.key + "=" );
}
return str.join( "&" );
},
toArray: function( o ) {
var items = this._getItemsAsjQuery( o && o.connected ),
ret = [];
o = o || {};
items.each( function() {
ret.push( $( o.item || this ).attr( o.attribute || "id" ) || "" );
} );
return ret;
},
/* Be careful with the following core functions */
_intersectsWith: function( item ) {
var x1 = this.positionAbs.left,
x2 = x1 + this.helperProportions.width,
y1 = this.positionAbs.top,
y2 = y1 + this.helperProportions.height,
l = item.left,
r = l + item.width,
t = item.top,
b = t + item.height,
dyClick = this.offset.click.top,
dxClick = this.offset.click.left,
isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t &&
( y1 + dyClick ) < b ),
isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l &&
( x1 + dxClick ) < r ),
isOverElement = isOverElementHeight && isOverElementWidth;
if ( this.options.tolerance === "pointer" ||
this.options.forcePointerForContainers ||
( this.options.tolerance !== "pointer" &&
this.helperProportions[ this.floating ? "width" : "height" ] >
item[ this.floating ? "width" : "height" ] )
) {
return isOverElement;
} else {
return ( l < x1 + ( this.helperProportions.width / 2 ) && // Right Half
x2 - ( this.helperProportions.width / 2 ) < r && // Left Half
t < y1 + ( this.helperProportions.height / 2 ) && // Bottom Half
y2 - ( this.helperProportions.height / 2 ) < b ); // Top Half
}
},
_intersectsWithPointer: function( item ) {
var verticalDirection, horizontalDirection,
isOverElementHeight = ( this.options.axis === "x" ) ||
this._isOverAxis(
this.positionAbs.top + this.offset.click.top, item.top, item.height ),
isOverElementWidth = ( this.options.axis === "y" ) ||
this._isOverAxis(
this.positionAbs.left + this.offset.click.left, item.left, item.width ),
isOverElement = isOverElementHeight && isOverElementWidth;
if ( !isOverElement ) {
return false;
}
verticalDirection = this._getDragVerticalDirection();
horizontalDirection = this._getDragHorizontalDirection();
return this.floating ?
( ( horizontalDirection === "right" || verticalDirection === "down" ) ? 2 : 1 )
: ( verticalDirection && ( verticalDirection === "down" ? 2 : 1 ) );
},
_intersectsWithSides: function( item ) {
var isOverBottomHalf = this._isOverAxis( this.positionAbs.top +
this.offset.click.top, item.top + ( item.height / 2 ), item.height ),
isOverRightHalf = this._isOverAxis( this.positionAbs.left +
this.offset.click.left, item.left + ( item.width / 2 ), item.width ),
verticalDirection = this._getDragVerticalDirection(),
horizontalDirection = this._getDragHorizontalDirection();
if ( this.floating && horizontalDirection ) {
return ( ( horizontalDirection === "right" && isOverRightHalf ) ||
( horizontalDirection === "left" && !isOverRightHalf ) );
} else {
return verticalDirection && ( ( verticalDirection === "down" && isOverBottomHalf ) ||
( verticalDirection === "up" && !isOverBottomHalf ) );
}
},
_getDragVerticalDirection: function() {
var delta = this.positionAbs.top - this.lastPositionAbs.top;
return delta !== 0 && ( delta > 0 ? "down" : "up" );
},
_getDragHorizontalDirection: function() {
var delta = this.positionAbs.left - this.lastPositionAbs.left;
return delta !== 0 && ( delta > 0 ? "right" : "left" );
},
refresh: function( event ) {
this._refreshItems( event );
this._setHandleClassName();
this.refreshPositions();
return this;
},
_connectWith: function() {
var options = this.options;
return options.connectWith.constructor === String ?
[ options.connectWith ] :
options.connectWith;
},
_getItemsAsjQuery: function( connected ) {
var i, j, cur, inst,
items = [],
queries = [],
connectWith = this._connectWith();
if ( connectWith && connected ) {
for ( i = connectWith.length - 1; i >= 0; i-- ) {
cur = $( connectWith[ i ], this.document[ 0 ] );
for ( j = cur.length - 1; j >= 0; j-- ) {
inst = $.data( cur[ j ], this.widgetFullName );
if ( inst && inst !== this && !inst.options.disabled ) {
queries.push( [ $.isFunction( inst.options.items ) ?
inst.options.items.call( inst.element ) :
$( inst.options.items, inst.element )
.not( ".ui-sortable-helper" )
.not( ".ui-sortable-placeholder" ), inst ] );
}
}
}
}
queries.push( [ $.isFunction( this.options.items ) ?
this.options.items
.call( this.element, null, { options: this.options, item: this.currentItem } ) :
$( this.options.items, this.element )
.not( ".ui-sortable-helper" )
.not( ".ui-sortable-placeholder" ), this ] );
function addItems() {
items.push( this );
}
for ( i = queries.length - 1; i >= 0; i-- ) {
queries[ i ][ 0 ].each( addItems );
}
return $( items );
},
_removeCurrentsFromItems: function() {
var list = this.currentItem.find( ":data(" + this.widgetName + "-item)" );
this.items = $.grep( this.items, function( item ) {
for ( var j = 0; j < list.length; j++ ) {
if ( list[ j ] === item.item[ 0 ] ) {
return false;
}
}
return true;
} );
},
_refreshItems: function( event ) {
this.items = [];
this.containers = [ this ];
var i, j, cur, inst, targetData, _queries, item, queriesLength,
items = this.items,
queries = [ [ $.isFunction( this.options.items ) ?
this.options.items.call( this.element[ 0 ], event, { item: this.currentItem } ) :
$( this.options.items, this.element ), this ] ],
connectWith = this._connectWith();
//Shouldn't be run the first time through due to massive slow-down
if ( connectWith && this.ready ) {
for ( i = connectWith.length - 1; i >= 0; i-- ) {
cur = $( connectWith[ i ], this.document[ 0 ] );
for ( j = cur.length - 1; j >= 0; j-- ) {
inst = $.data( cur[ j ], this.widgetFullName );
if ( inst && inst !== this && !inst.options.disabled ) {
queries.push( [ $.isFunction( inst.options.items ) ?
inst.options.items
.call( inst.element[ 0 ], event, { item: this.currentItem } ) :
$( inst.options.items, inst.element ), inst ] );
this.containers.push( inst );
}
}
}
}
for ( i = queries.length - 1; i >= 0; i-- ) {
targetData = queries[ i ][ 1 ];
_queries = queries[ i ][ 0 ];
for ( j = 0, queriesLength = _queries.length; j < queriesLength; j++ ) {
item = $( _queries[ j ] );
// Data for target checking (mouse manager)
item.data( this.widgetName + "-item", targetData );
items.push( {
item: item,
instance: targetData,
width: 0, height: 0,
left: 0, top: 0
} );
}
}
},
refreshPositions: function( fast ) {
// Determine whether items are being displayed horizontally
this.floating = this.items.length ?
this.options.axis === "x" || this._isFloating( this.items[ 0 ].item ) :
false;
//This has to be redone because due to the item being moved out/into the offsetParent,
// the offsetParent's position will change
if ( this.offsetParent && this.helper ) {
this.offset.parent = this._getParentOffset();
}
var i, item, t, p;
for ( i = this.items.length - 1; i >= 0; i-- ) {
item = this.items[ i ];
//We ignore calculating positions of all connected containers when we're not over them
if ( item.instance !== this.currentContainer && this.currentContainer &&
item.item[ 0 ] !== this.currentItem[ 0 ] ) {
continue;
}
t = this.options.toleranceElement ?
$( this.options.toleranceElement, item.item ) :
item.item;
if ( !fast ) {
item.width = t.outerWidth();
item.height = t.outerHeight();
}
p = t.offset();
item.left = p.left;
item.top = p.top;
}
if ( this.options.custom && this.options.custom.refreshContainers ) {
this.options.custom.refreshContainers.call( this );
} else {
for ( i = this.containers.length - 1; i >= 0; i-- ) {
p = this.containers[ i ].element.offset();
this.containers[ i ].containerCache.left = p.left;
this.containers[ i ].containerCache.top = p.top;
this.containers[ i ].containerCache.width =
this.containers[ i ].element.outerWidth();
this.containers[ i ].containerCache.height =
this.containers[ i ].element.outerHeight();
}
}
return this;
},
_createPlaceholder: function( that ) {
that = that || this;
var className,
o = that.options;
if ( !o.placeholder || o.placeholder.constructor === String ) {
className = o.placeholder;
o.placeholder = {
element: function() {
var nodeName = that.currentItem[ 0 ].nodeName.toLowerCase(),
element = $( "<" + nodeName + ">", that.document[ 0 ] );
that._addClass( element, "ui-sortable-placeholder",
className || that.currentItem[ 0 ].className )
._removeClass( element, "ui-sortable-helper" );
if ( nodeName === "tbody" ) {
that._createTrPlaceholder(
that.currentItem.find( "tr" ).eq( 0 ),
$( "<tr>", that.document[ 0 ] ).appendTo( element )
);
} else if ( nodeName === "tr" ) {
that._createTrPlaceholder( that.currentItem, element );
} else if ( nodeName === "img" ) {
element.attr( "src", that.currentItem.attr( "src" ) );
}
if ( !className ) {
element.css( "visibility", "hidden" );
}
return element;
},
update: function( container, p ) {
// 1. If a className is set as 'placeholder option, we don't force sizes -
// the class is responsible for that
// 2. The option 'forcePlaceholderSize can be enabled to force it even if a
// class name is specified
if ( className && !o.forcePlaceholderSize ) {
return;
}
//If the element doesn't have a actual height by itself (without styles coming
// from a stylesheet), it receives the inline height from the dragged item
if ( !p.height() ) {
p.height(
that.currentItem.innerHeight() -
parseInt( that.currentItem.css( "paddingTop" ) || 0, 10 ) -
parseInt( that.currentItem.css( "paddingBottom" ) || 0, 10 ) );
}
if ( !p.width() ) {
p.width(
that.currentItem.innerWidth() -
parseInt( that.currentItem.css( "paddingLeft" ) || 0, 10 ) -
parseInt( that.currentItem.css( "paddingRight" ) || 0, 10 ) );
}
}
};
}
//Create the placeholder
that.placeholder = $( o.placeholder.element.call( that.element, that.currentItem ) );
//Append it after the actual current item
that.currentItem.after( that.placeholder );
//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
o.placeholder.update( that, that.placeholder );
},
_createTrPlaceholder: function( sourceTr, targetTr ) {
var that = this;
sourceTr.children().each( function() {
$( "<td> </td>", that.document[ 0 ] )
.attr( "colspan", $( this ).attr( "colspan" ) || 1 )
.appendTo( targetTr );
} );
},
_contactContainers: function( event ) {
var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, cur, nearBottom,
floating, axis,
innermostContainer = null,
innermostIndex = null;
// Get innermost container that intersects with item
for ( i = this.containers.length - 1; i >= 0; i-- ) {
// Never consider a container that's located within the item itself
if ( $.contains( this.currentItem[ 0 ], this.containers[ i ].element[ 0 ] ) ) {
continue;
}
if ( this._intersectsWith( this.containers[ i ].containerCache ) ) {
// If we've already found a container and it's more "inner" than this, then continue
if ( innermostContainer &&
$.contains(
this.containers[ i ].element[ 0 ],
innermostContainer.element[ 0 ] ) ) {
continue;
}
innermostContainer = this.containers[ i ];
innermostIndex = i;
} else {
// container doesn't intersect. trigger "out" event if necessary
if ( this.containers[ i ].containerCache.over ) {
this.containers[ i ]._trigger( "out", event, this._uiHash( this ) );
this.containers[ i ].containerCache.over = 0;
}
}
}
// If no intersecting containers found, return
if ( !innermostContainer ) {
return;
}
// Move the item into the container if it's not there already
if ( this.containers.length === 1 ) {
if ( !this.containers[ innermostIndex ].containerCache.over ) {
this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash( this ) );
this.containers[ innermostIndex ].containerCache.over = 1;
}
} else {
// When entering a new container, we will find the item with the least distance and
// append our item near it
dist = 10000;
itemWithLeastDistance = null;
floating = innermostContainer.floating || this._isFloating( this.currentItem );
posProperty = floating ? "left" : "top";
sizeProperty = floating ? "width" : "height";
axis = floating ? "pageX" : "pageY";
for ( j = this.items.length - 1; j >= 0; j-- ) {
if ( !$.contains(
this.containers[ innermostIndex ].element[ 0 ], this.items[ j ].item[ 0 ] )
) {
continue;
}
if ( this.items[ j ].item[ 0 ] === this.currentItem[ 0 ] ) {
continue;
}
cur = this.items[ j ].item.offset()[ posProperty ];
nearBottom = false;
if ( event[ axis ] - cur > this.items[ j ][ sizeProperty ] / 2 ) {
nearBottom = true;
}
if ( Math.abs( event[ axis ] - cur ) < dist ) {
dist = Math.abs( event[ axis ] - cur );
itemWithLeastDistance = this.items[ j ];
this.direction = nearBottom ? "up" : "down";
}
}
//Check if dropOnEmpty is enabled
if ( !itemWithLeastDistance && !this.options.dropOnEmpty ) {
return;
}
if ( this.currentContainer === this.containers[ innermostIndex ] ) {
if ( !this.currentContainer.containerCache.over ) {
this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash() );
this.currentContainer.containerCache.over = 1;
}
return;
}
itemWithLeastDistance ?
this._rearrange( event, itemWithLeastDistance, null, true ) :
this._rearrange( event, null, this.containers[ innermostIndex ].element, true );
this._trigger( "change", event, this._uiHash() );
this.containers[ innermostIndex ]._trigger( "change", event, this._uiHash( this ) );
this.currentContainer = this.containers[ innermostIndex ];
//Update the placeholder
this.options.placeholder.update( this.currentContainer, this.placeholder );
this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash( this ) );
this.containers[ innermostIndex ].containerCache.over = 1;
}
},
_createHelper: function( event ) {
var o = this.options,
helper = $.isFunction( o.helper ) ?
$( o.helper.apply( this.element[ 0 ], [ event, this.currentItem ] ) ) :
( o.helper === "clone" ? this.currentItem.clone() : this.currentItem );
//Add the helper to the DOM if that didn't happen already
if ( !helper.parents( "body" ).length ) {
$( o.appendTo !== "parent" ?
o.appendTo :
this.currentItem[ 0 ].parentNode )[ 0 ].appendChild( helper[ 0 ] );
}
if ( helper[ 0 ] === this.currentItem[ 0 ] ) {
this._storedCSS = {
width: this.currentItem[ 0 ].style.width,
height: this.currentItem[ 0 ].style.height,
position: this.currentItem.css( "position" ),
top: this.currentItem.css( "top" ),
left: this.currentItem.css( "left" )
};
}
if ( !helper[ 0 ].style.width || o.forceHelperSize ) {
helper.width( this.currentItem.width() );
}
if ( !helper[ 0 ].style.height || o.forceHelperSize ) {
helper.height( this.currentItem.height() );
}
return helper;
},
_adjustOffsetFromHelper: function( obj ) {
if ( typeof obj === "string" ) {
obj = obj.split( " " );
}
if ( $.isArray( obj ) ) {
obj = { left: +obj[ 0 ], top: +obj[ 1 ] || 0 };
}
if ( "left" in obj ) {
this.offset.click.left = obj.left + this.margins.left;
}
if ( "right" in obj ) {
this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
}
if ( "top" in obj ) {
this.offset.click.top = obj.top + this.margins.top;
}
if ( "bottom" in obj ) {
this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
}
},
_getParentOffset: function() {
//Get the offsetParent and cache its position
this.offsetParent = this.helper.offsetParent();
var po = this.offsetParent.offset();
// This is a special case where we need to modify a offset calculated on start, since the
// following happened:
// 1. The position of the helper is absolute, so it's position is calculated based on the
// next positioned parent
// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
// the document, which means that the scroll is included in the initial calculation of the
// offset of the parent, and never recalculated upon drag
if ( this.cssPosition === "absolute" && this.scrollParent[ 0 ] !== this.document[ 0 ] &&
$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) {
po.left += this.scrollParent.scrollLeft();
po.top += this.scrollParent.scrollTop();
}
// This needs to be actually done for all browsers, since pageX/pageY includes this
// information with an ugly IE fix
if ( this.offsetParent[ 0 ] === this.document[ 0 ].body ||
( this.offsetParent[ 0 ].tagName &&
this.offsetParent[ 0 ].tagName.toLowerCase() === "html" && $.ui.ie ) ) {
po = { top: 0, left: 0 };
}
return {
top: po.top + ( parseInt( this.offsetParent.css( "borderTopWidth" ), 10 ) || 0 ),
left: po.left + ( parseInt( this.offsetParent.css( "borderLeftWidth" ), 10 ) || 0 )
};
},
_getRelativeOffset: function() {
if ( this.cssPosition === "relative" ) {
var p = this.currentItem.position();
return {
top: p.top - ( parseInt( this.helper.css( "top" ), 10 ) || 0 ) +
this.scrollParent.scrollTop(),
left: p.left - ( parseInt( this.helper.css( "left" ), 10 ) || 0 ) +
this.scrollParent.scrollLeft()
};
} else {
return { top: 0, left: 0 };
}
},
_cacheMargins: function() {
this.margins = {
left: ( parseInt( this.currentItem.css( "marginLeft" ), 10 ) || 0 ),
top: ( parseInt( this.currentItem.css( "marginTop" ), 10 ) || 0 )
};
},
_cacheHelperProportions: function() {
this.helperProportions = {
width: this.helper.outerWidth(),
height: this.helper.outerHeight()
};
},
_setContainment: function() {
var ce, co, over,
o = this.options;
if ( o.containment === "parent" ) {
o.containment = this.helper[ 0 ].parentNode;
}
if ( o.containment === "document" || o.containment === "window" ) {
this.containment = [
0 - this.offset.relative.left - this.offset.parent.left,
0 - this.offset.relative.top - this.offset.parent.top,
o.containment === "document" ?
this.document.width() :
this.window.width() - this.helperProportions.width - this.margins.left,
( o.containment === "document" ?
( this.document.height() || document.body.parentNode.scrollHeight ) :
this.window.height() || this.document[ 0 ].body.parentNode.scrollHeight
) - this.helperProportions.height - this.margins.top
];
}
if ( !( /^(document|window|parent)$/ ).test( o.containment ) ) {
ce = $( o.containment )[ 0 ];
co = $( o.containment ).offset();
over = ( $( ce ).css( "overflow" ) !== "hidden" );
this.containment = [
co.left + ( parseInt( $( ce ).css( "borderLeftWidth" ), 10 ) || 0 ) +
( parseInt( $( ce ).css( "paddingLeft" ), 10 ) || 0 ) - this.margins.left,
co.top + ( parseInt( $( ce ).css( "borderTopWidth" ), 10 ) || 0 ) +
( parseInt( $( ce ).css( "paddingTop" ), 10 ) || 0 ) - this.margins.top,
co.left + ( over ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
( parseInt( $( ce ).css( "borderLeftWidth" ), 10 ) || 0 ) -
( parseInt( $( ce ).css( "paddingRight" ), 10 ) || 0 ) -
this.helperProportions.width - this.margins.left,
co.top + ( over ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
( parseInt( $( ce ).css( "borderTopWidth" ), 10 ) || 0 ) -
( parseInt( $( ce ).css( "paddingBottom" ), 10 ) || 0 ) -
this.helperProportions.height - this.margins.top
];
}
},
_convertPositionTo: function( d, pos ) {
if ( !pos ) {
pos = this.position;
}
var mod = d === "absolute" ? 1 : -1,
scroll = this.cssPosition === "absolute" &&
!( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ?
this.offsetParent :
this.scrollParent,
scrollIsRootNode = ( /(html|body)/i ).test( scroll[ 0 ].tagName );
return {
top: (
// The absolute mouse position
pos.top +
// Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.relative.top * mod +
// The offsetParent's offset without borders (offset + border)
this.offset.parent.top * mod -
( ( this.cssPosition === "fixed" ?
-this.scrollParent.scrollTop() :
( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod )
),
left: (
// The absolute mouse position
pos.left +
// Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.relative.left * mod +
// The offsetParent's offset without borders (offset + border)
this.offset.parent.left * mod -
( ( this.cssPosition === "fixed" ?
-this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 :
scroll.scrollLeft() ) * mod )
)
};
},
_generatePosition: function( event ) {
var top, left,
o = this.options,
pageX = event.pageX,
pageY = event.pageY,
scroll = this.cssPosition === "absolute" &&
!( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ?
this.offsetParent :
this.scrollParent,
scrollIsRootNode = ( /(html|body)/i ).test( scroll[ 0 ].tagName );
// This is another very weird special case that only happens for relative elements:
// 1. If the css position is relative
// 2. and the scroll parent is the document or similar to the offset parent
// we have to refresh the relative offset during the scroll so there are no jumps
if ( this.cssPosition === "relative" && !( this.scrollParent[ 0 ] !== this.document[ 0 ] &&
this.scrollParent[ 0 ] !== this.offsetParent[ 0 ] ) ) {
this.offset.relative = this._getRelativeOffset();
}
/*
* - Position constraining -
* Constrain the position to a mix of grid, containment.
*/
if ( this.originalPosition ) { //If we are not dragging yet, we won't check for options
if ( this.containment ) {
if ( event.pageX - this.offset.click.left < this.containment[ 0 ] ) {
pageX = this.containment[ 0 ] + this.offset.click.left;
}
if ( event.pageY - this.offset.click.top < this.containment[ 1 ] ) {
pageY = this.containment[ 1 ] + this.offset.click.top;
}
if ( event.pageX - this.offset.click.left > this.containment[ 2 ] ) {
pageX = this.containment[ 2 ] + this.offset.click.left;
}
if ( event.pageY - this.offset.click.top > this.containment[ 3 ] ) {
pageY = this.containment[ 3 ] + this.offset.click.top;
}
}
if ( o.grid ) {
top = this.originalPageY + Math.round( ( pageY - this.originalPageY ) /
o.grid[ 1 ] ) * o.grid[ 1 ];
pageY = this.containment ?
( ( top - this.offset.click.top >= this.containment[ 1 ] &&
top - this.offset.click.top <= this.containment[ 3 ] ) ?
top :
( ( top - this.offset.click.top >= this.containment[ 1 ] ) ?
top - o.grid[ 1 ] : top + o.grid[ 1 ] ) ) :
top;
left = this.originalPageX + Math.round( ( pageX - this.originalPageX ) /
o.grid[ 0 ] ) * o.grid[ 0 ];
pageX = this.containment ?
( ( left - this.offset.click.left >= this.containment[ 0 ] &&
left - this.offset.click.left <= this.containment[ 2 ] ) ?
left :
( ( left - this.offset.click.left >= this.containment[ 0 ] ) ?
left - o.grid[ 0 ] : left + o.grid[ 0 ] ) ) :
left;
}
}
return {
top: (
// The absolute mouse position
pageY -
// Click offset (relative to the element)
this.offset.click.top -
// Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.relative.top -
// The offsetParent's offset without borders (offset + border)
this.offset.parent.top +
( ( this.cssPosition === "fixed" ?
-this.scrollParent.scrollTop() :
( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) )
),
left: (
// The absolute mouse position
pageX -
// Click offset (relative to the element)
this.offset.click.left -
// Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.relative.left -
// The offsetParent's offset without borders (offset + border)
this.offset.parent.left +
( ( this.cssPosition === "fixed" ?
-this.scrollParent.scrollLeft() :
scrollIsRootNode ? 0 : scroll.scrollLeft() ) )
)
};
},
_rearrange: function( event, i, a, hardRefresh ) {
a ? a[ 0 ].appendChild( this.placeholder[ 0 ] ) :
i.item[ 0 ].parentNode.insertBefore( this.placeholder[ 0 ],
( this.direction === "down" ? i.item[ 0 ] : i.item[ 0 ].nextSibling ) );
//Various things done here to improve the performance:
// 1. we create a setTimeout, that calls refreshPositions
// 2. on the instance, we have a counter variable, that get's higher after every append
// 3. on the local scope, we copy the counter variable, and check in the timeout,
// if it's still the same
// 4. this lets only the last addition to the timeout stack through
this.counter = this.counter ? ++this.counter : 1;
var counter = this.counter;
this._delay( function() {
if ( counter === this.counter ) {
//Precompute after each DOM insertion, NOT on mousemove
this.refreshPositions( !hardRefresh );
}
} );
},
_clear: function( event, noPropagation ) {
this.reverting = false;
// We delay all events that have to be triggered to after the point where the placeholder
// has been removed and everything else normalized again
var i,
delayedTriggers = [];
// We first have to update the dom position of the actual currentItem
// Note: don't do it if the current item is already removed (by a user), or it gets
// reappended (see #4088)
if ( !this._noFinalSort && this.currentItem.parent().length ) {
this.placeholder.before( this.currentItem );
}
this._noFinalSort = null;
if ( this.helper[ 0 ] === this.currentItem[ 0 ] ) {
for ( i in this._storedCSS ) {
if ( this._storedCSS[ i ] === "auto" || this._storedCSS[ i ] === "static" ) {
this._storedCSS[ i ] = "";
}
}
this.currentItem.css( this._storedCSS );
this._removeClass( this.currentItem, "ui-sortable-helper" );
} else {
this.currentItem.show();
}
if ( this.fromOutside && !noPropagation ) {
delayedTriggers.push( function( event ) {
this._trigger( "receive", event, this._uiHash( this.fromOutside ) );
} );
}
if ( ( this.fromOutside ||
this.domPosition.prev !==
this.currentItem.prev().not( ".ui-sortable-helper" )[ 0 ] ||
this.domPosition.parent !== this.currentItem.parent()[ 0 ] ) && !noPropagation ) {
// Trigger update callback if the DOM position has changed
delayedTriggers.push( function( event ) {
this._trigger( "update", event, this._uiHash() );
} );
}
// Check if the items Container has Changed and trigger appropriate
// events.
if ( this !== this.currentContainer ) {
if ( !noPropagation ) {
delayedTriggers.push( function( event ) {
this._trigger( "remove", event, this._uiHash() );
} );
delayedTriggers.push( ( function( c ) {
return function( event ) {
c._trigger( "receive", event, this._uiHash( this ) );
};
} ).call( this, this.currentContainer ) );
delayedTriggers.push( ( function( c ) {
return function( event ) {
c._trigger( "update", event, this._uiHash( this ) );
};
} ).call( this, this.currentContainer ) );
}
}
//Post events to containers
function delayEvent( type, instance, container ) {
return function( event ) {
container._trigger( type, event, instance._uiHash( instance ) );
};
}
for ( i = this.containers.length - 1; i >= 0; i-- ) {
if ( !noPropagation ) {
delayedTriggers.push( delayEvent( "deactivate", this, this.containers[ i ] ) );
}
if ( this.containers[ i ].containerCache.over ) {
delayedTriggers.push( delayEvent( "out", this, this.containers[ i ] ) );
this.containers[ i ].containerCache.over = 0;
}
}
//Do what was originally in plugins
if ( this.storedCursor ) {
this.document.find( "body" ).css( "cursor", this.storedCursor );
this.storedStylesheet.remove();
}
if ( this._storedOpacity ) {
this.helper.css( "opacity", this._storedOpacity );
}
if ( this._storedZIndex ) {
this.helper.css( "zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex );
}
this.dragging = false;
if ( !noPropagation ) {
this._trigger( "beforeStop", event, this._uiHash() );
}
//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately,
// it unbinds ALL events from the original node!
this.placeholder[ 0 ].parentNode.removeChild( this.placeholder[ 0 ] );
if ( !this.cancelHelperRemoval ) {
if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) {
this.helper.remove();
}
this.helper = null;
}
if ( !noPropagation ) {
for ( i = 0; i < delayedTriggers.length; i++ ) {
// Trigger all delayed events
delayedTriggers[ i ].call( this, event );
}
this._trigger( "stop", event, this._uiHash() );
}
this.fromOutside = false;
return !this.cancelHelperRemoval;
},
_trigger: function() {
if ( $.Widget.prototype._trigger.apply( this, arguments ) === false ) {
this.cancel();
}
},
_uiHash: function( _inst ) {
var inst = _inst || this;
return {
helper: inst.helper,
placeholder: inst.placeholder || $( [] ),
position: inst.position,
originalPosition: inst.originalPosition,
offset: inst.positionAbs,
item: inst.currentItem,
sender: _inst ? _inst.element : null
};
}
} );
/*!
* jQuery UI Effects 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Effects Core
//>>group: Effects
// jscs:disable maximumLineLength
//>>description: Extends the internal jQuery effects. Includes morphing and easing. Required by all other effects.
// jscs:enable maximumLineLength
//>>docs: http://api.jqueryui.com/category/effects-core/
//>>demos: http://jqueryui.com/effect/
var dataSpace = "ui-effects-",
dataSpaceStyle = "ui-effects-style",
dataSpaceAnimated = "ui-effects-animated",
// Create a local jQuery because jQuery Color relies on it and the
// global may not exist with AMD and a custom build (#10199)
jQuery = $;
$.effects = {
effect: {}
};
/*!
* jQuery Color Animations v2.1.2
* https://github.com/jquery/jquery-color
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* Date: Wed Jan 16 08:47:09 2013 -0600
*/
( function( jQuery, undefined ) {
var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor " +
"borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",
// Plusequals test for += 100 -= 100
rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,
// A set of RE's that can match strings and generate color tuples.
stringParsers = [ {
re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
parse: function( execResult ) {
return [
execResult[ 1 ],
execResult[ 2 ],
execResult[ 3 ],
execResult[ 4 ]
];
}
}, {
re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
parse: function( execResult ) {
return [
execResult[ 1 ] * 2.55,
execResult[ 2 ] * 2.55,
execResult[ 3 ] * 2.55,
execResult[ 4 ]
];
}
}, {
// This regex ignores A-F because it's compared against an already lowercased string
re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
parse: function( execResult ) {
return [
parseInt( execResult[ 1 ], 16 ),
parseInt( execResult[ 2 ], 16 ),
parseInt( execResult[ 3 ], 16 )
];
}
}, {
// This regex ignores A-F because it's compared against an already lowercased string
re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
parse: function( execResult ) {
return [
parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
parseInt( execResult[ 3 ] + execResult[ 3 ], 16 )
];
}
}, {
re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
space: "hsla",
parse: function( execResult ) {
return [
execResult[ 1 ],
execResult[ 2 ] / 100,
execResult[ 3 ] / 100,
execResult[ 4 ]
];
}
} ],
// JQuery.Color( )
color = jQuery.Color = function( color, green, blue, alpha ) {
return new jQuery.Color.fn.parse( color, green, blue, alpha );
},
spaces = {
rgba: {
props: {
red: {
idx: 0,
type: "byte"
},
green: {
idx: 1,
type: "byte"
},
blue: {
idx: 2,
type: "byte"
}
}
},
hsla: {
props: {
hue: {
idx: 0,
type: "degrees"
},
saturation: {
idx: 1,
type: "percent"
},
lightness: {
idx: 2,
type: "percent"
}
}
}
},
propTypes = {
"byte": {
floor: true,
max: 255
},
"percent": {
max: 1
},
"degrees": {
mod: 360,
floor: true
}
},
support = color.support = {},
// Element for support tests
supportElem = jQuery( "<p>" )[ 0 ],
// Colors = jQuery.Color.names
colors,
// Local aliases of functions called often
each = jQuery.each;
// Determine rgba support immediately
supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1;
// Define cache name and alpha properties
// for rgba and hsla spaces
each( spaces, function( spaceName, space ) {
space.cache = "_" + spaceName;
space.props.alpha = {
idx: 3,
type: "percent",
def: 1
};
} );
function clamp( value, prop, allowEmpty ) {
var type = propTypes[ prop.type ] || {};
if ( value == null ) {
return ( allowEmpty || !prop.def ) ? null : prop.def;
}
// ~~ is an short way of doing floor for positive numbers
value = type.floor ? ~~value : parseFloat( value );
// IE will pass in empty strings as value for alpha,
// which will hit this case
if ( isNaN( value ) ) {
return prop.def;
}
if ( type.mod ) {
// We add mod before modding to make sure that negatives values
// get converted properly: -10 -> 350
return ( value + type.mod ) % type.mod;
}
// For now all property types without mod have min and max
return 0 > value ? 0 : type.max < value ? type.max : value;
}
function stringParse( string ) {
var inst = color(),
rgba = inst._rgba = [];
string = string.toLowerCase();
each( stringParsers, function( i, parser ) {
var parsed,
match = parser.re.exec( string ),
values = match && parser.parse( match ),
spaceName = parser.space || "rgba";
if ( values ) {
parsed = inst[ spaceName ]( values );
// If this was an rgba parse the assignment might happen twice
// oh well....
inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
rgba = inst._rgba = parsed._rgba;
// Exit each( stringParsers ) here because we matched
return false;
}
} );
// Found a stringParser that handled it
if ( rgba.length ) {
// If this came from a parsed string, force "transparent" when alpha is 0
// chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
if ( rgba.join() === "0,0,0,0" ) {
jQuery.extend( rgba, colors.transparent );
}
return inst;
}
// Named colors
return colors[ string ];
}
color.fn = jQuery.extend( color.prototype, {
parse: function( red, green, blue, alpha ) {
if ( red === undefined ) {
this._rgba = [ null, null, null, null ];
return this;
}
if ( red.jquery || red.nodeType ) {
red = jQuery( red ).css( green );
green = undefined;
}
var inst = this,
type = jQuery.type( red ),
rgba = this._rgba = [];
// More than 1 argument specified - assume ( red, green, blue, alpha )
if ( green !== undefined ) {
red = [ red, green, blue, alpha ];
type = "array";
}
if ( type === "string" ) {
return this.parse( stringParse( red ) || colors._default );
}
if ( type === "array" ) {
each( spaces.rgba.props, function( key, prop ) {
rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
} );
return this;
}
if ( type === "object" ) {
if ( red instanceof color ) {
each( spaces, function( spaceName, space ) {
if ( red[ space.cache ] ) {
inst[ space.cache ] = red[ space.cache ].slice();
}
} );
} else {
each( spaces, function( spaceName, space ) {
var cache = space.cache;
each( space.props, function( key, prop ) {
// If the cache doesn't exist, and we know how to convert
if ( !inst[ cache ] && space.to ) {
// If the value was null, we don't need to copy it
// if the key was alpha, we don't need to copy it either
if ( key === "alpha" || red[ key ] == null ) {
return;
}
inst[ cache ] = space.to( inst._rgba );
}
// This is the only case where we allow nulls for ALL properties.
// call clamp with alwaysAllowEmpty
inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
} );
// Everything defined but alpha?
if ( inst[ cache ] &&
jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {
// Use the default of 1
inst[ cache ][ 3 ] = 1;
if ( space.from ) {
inst._rgba = space.from( inst[ cache ] );
}
}
} );
}
return this;
}
},
is: function( compare ) {
var is = color( compare ),
same = true,
inst = this;
each( spaces, function( _, space ) {
var localCache,
isCache = is[ space.cache ];
if ( isCache ) {
localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
each( space.props, function( _, prop ) {
if ( isCache[ prop.idx ] != null ) {
same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
return same;
}
} );
}
return same;
} );
return same;
},
_space: function() {
var used = [],
inst = this;
each( spaces, function( spaceName, space ) {
if ( inst[ space.cache ] ) {
used.push( spaceName );
}
} );
return used.pop();
},
transition: function( other, distance ) {
var end = color( other ),
spaceName = end._space(),
space = spaces[ spaceName ],
startColor = this.alpha() === 0 ? color( "transparent" ) : this,
start = startColor[ space.cache ] || space.to( startColor._rgba ),
result = start.slice();
end = end[ space.cache ];
each( space.props, function( key, prop ) {
var index = prop.idx,
startValue = start[ index ],
endValue = end[ index ],
type = propTypes[ prop.type ] || {};
// If null, don't override start value
if ( endValue === null ) {
return;
}
// If null - use end
if ( startValue === null ) {
result[ index ] = endValue;
} else {
if ( type.mod ) {
if ( endValue - startValue > type.mod / 2 ) {
startValue += type.mod;
} else if ( startValue - endValue > type.mod / 2 ) {
startValue -= type.mod;
}
}
result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
}
} );
return this[ spaceName ]( result );
},
blend: function( opaque ) {
// If we are already opaque - return ourself
if ( this._rgba[ 3 ] === 1 ) {
return this;
}
var rgb = this._rgba.slice(),
a = rgb.pop(),
blend = color( opaque )._rgba;
return color( jQuery.map( rgb, function( v, i ) {
return ( 1 - a ) * blend[ i ] + a * v;
} ) );
},
toRgbaString: function() {
var prefix = "rgba(",
rgba = jQuery.map( this._rgba, function( v, i ) {
return v == null ? ( i > 2 ? 1 : 0 ) : v;
} );
if ( rgba[ 3 ] === 1 ) {
rgba.pop();
prefix = "rgb(";
}
return prefix + rgba.join() + ")";
},
toHslaString: function() {
var prefix = "hsla(",
hsla = jQuery.map( this.hsla(), function( v, i ) {
if ( v == null ) {
v = i > 2 ? 1 : 0;
}
// Catch 1 and 2
if ( i && i < 3 ) {
v = Math.round( v * 100 ) + "%";
}
return v;
} );
if ( hsla[ 3 ] === 1 ) {
hsla.pop();
prefix = "hsl(";
}
return prefix + hsla.join() + ")";
},
toHexString: function( includeAlpha ) {
var rgba = this._rgba.slice(),
alpha = rgba.pop();
if ( includeAlpha ) {
rgba.push( ~~( alpha * 255 ) );
}
return "#" + jQuery.map( rgba, function( v ) {
// Default to 0 when nulls exist
v = ( v || 0 ).toString( 16 );
return v.length === 1 ? "0" + v : v;
} ).join( "" );
},
toString: function() {
return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
}
} );
color.fn.parse.prototype = color.fn;
// Hsla conversions adapted from:
// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021
function hue2rgb( p, q, h ) {
h = ( h + 1 ) % 1;
if ( h * 6 < 1 ) {
return p + ( q - p ) * h * 6;
}
if ( h * 2 < 1 ) {
return q;
}
if ( h * 3 < 2 ) {
return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6;
}
return p;
}
spaces.hsla.to = function( rgba ) {
if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
return [ null, null, null, rgba[ 3 ] ];
}
var r = rgba[ 0 ] / 255,
g = rgba[ 1 ] / 255,
b = rgba[ 2 ] / 255,
a = rgba[ 3 ],
max = Math.max( r, g, b ),
min = Math.min( r, g, b ),
diff = max - min,
add = max + min,
l = add * 0.5,
h, s;
if ( min === max ) {
h = 0;
} else if ( r === max ) {
h = ( 60 * ( g - b ) / diff ) + 360;
} else if ( g === max ) {
h = ( 60 * ( b - r ) / diff ) + 120;
} else {
h = ( 60 * ( r - g ) / diff ) + 240;
}
// Chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
// otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
if ( diff === 0 ) {
s = 0;
} else if ( l <= 0.5 ) {
s = diff / add;
} else {
s = diff / ( 2 - add );
}
return [ Math.round( h ) % 360, s, l, a == null ? 1 : a ];
};
spaces.hsla.from = function( hsla ) {
if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
return [ null, null, null, hsla[ 3 ] ];
}
var h = hsla[ 0 ] / 360,
s = hsla[ 1 ],
l = hsla[ 2 ],
a = hsla[ 3 ],
q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
p = 2 * l - q;
return [
Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
Math.round( hue2rgb( p, q, h ) * 255 ),
Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
a
];
};
each( spaces, function( spaceName, space ) {
var props = space.props,
cache = space.cache,
to = space.to,
from = space.from;
// Makes rgba() and hsla()
color.fn[ spaceName ] = function( value ) {
// Generate a cache for this space if it doesn't exist
if ( to && !this[ cache ] ) {
this[ cache ] = to( this._rgba );
}
if ( value === undefined ) {
return this[ cache ].slice();
}
var ret,
type = jQuery.type( value ),
arr = ( type === "array" || type === "object" ) ? value : arguments,
local = this[ cache ].slice();
each( props, function( key, prop ) {
var val = arr[ type === "object" ? key : prop.idx ];
if ( val == null ) {
val = local[ prop.idx ];
}
local[ prop.idx ] = clamp( val, prop );
} );
if ( from ) {
ret = color( from( local ) );
ret[ cache ] = local;
return ret;
} else {
return color( local );
}
};
// Makes red() green() blue() alpha() hue() saturation() lightness()
each( props, function( key, prop ) {
// Alpha is included in more than one space
if ( color.fn[ key ] ) {
return;
}
color.fn[ key ] = function( value ) {
var vtype = jQuery.type( value ),
fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ),
local = this[ fn ](),
cur = local[ prop.idx ],
match;
if ( vtype === "undefined" ) {
return cur;
}
if ( vtype === "function" ) {
value = value.call( this, cur );
vtype = jQuery.type( value );
}
if ( value == null && prop.empty ) {
return this;
}
if ( vtype === "string" ) {
match = rplusequals.exec( value );
if ( match ) {
value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
}
}
local[ prop.idx ] = value;
return this[ fn ]( local );
};
} );
} );
// Add cssHook and .fx.step function for each named hook.
// accept a space separated string of properties
color.hook = function( hook ) {
var hooks = hook.split( " " );
each( hooks, function( i, hook ) {
jQuery.cssHooks[ hook ] = {
set: function( elem, value ) {
var parsed, curElem,
backgroundColor = "";
if ( value !== "transparent" && ( jQuery.type( value ) !== "string" ||
( parsed = stringParse( value ) ) ) ) {
value = color( parsed || value );
if ( !support.rgba && value._rgba[ 3 ] !== 1 ) {
curElem = hook === "backgroundColor" ? elem.parentNode : elem;
while (
( backgroundColor === "" || backgroundColor === "transparent" ) &&
curElem && curElem.style
) {
try {
backgroundColor = jQuery.css( curElem, "backgroundColor" );
curElem = curElem.parentNode;
} catch ( e ) {
}
}
value = value.blend( backgroundColor && backgroundColor !== "transparent" ?
backgroundColor :
"_default" );
}
value = value.toRgbaString();
}
try {
elem.style[ hook ] = value;
} catch ( e ) {
// Wrapped to prevent IE from throwing errors on "invalid" values like
// 'auto' or 'inherit'
}
}
};
jQuery.fx.step[ hook ] = function( fx ) {
if ( !fx.colorInit ) {
fx.start = color( fx.elem, hook );
fx.end = color( fx.end );
fx.colorInit = true;
}
jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
};
} );
};
color.hook( stepHooks );
jQuery.cssHooks.borderColor = {
expand: function( value ) {
var expanded = {};
each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) {
expanded[ "border" + part + "Color" ] = value;
} );
return expanded;
}
};
// Basic color names only.
// Usage of any of the other color names requires adding yourself or including
// jquery.color.svg-names.js.
colors = jQuery.Color.names = {
// 4.1. Basic color keywords
aqua: "#00ffff",
black: "#000000",
blue: "#0000ff",
fuchsia: "#ff00ff",
gray: "#808080",
green: "#008000",
lime: "#00ff00",
maroon: "#800000",
navy: "#000080",
olive: "#808000",
purple: "#800080",
red: "#ff0000",
silver: "#c0c0c0",
teal: "#008080",
white: "#ffffff",
yellow: "#ffff00",
// 4.2.3. "transparent" color keyword
transparent: [ null, null, null, 0 ],
_default: "#ffffff"
};
} )( jQuery );
/******************************************************************************/
/****************************** CLASS ANIMATIONS ******************************/
/******************************************************************************/
( function() {
var classAnimationActions = [ "add", "remove", "toggle" ],
shorthandStyles = {
border: 1,
borderBottom: 1,
borderColor: 1,
borderLeft: 1,
borderRight: 1,
borderTop: 1,
borderWidth: 1,
margin: 1,
padding: 1
};
$.each(
[ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ],
function( _, prop ) {
$.fx.step[ prop ] = function( fx ) {
if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
jQuery.style( fx.elem, prop, fx.end );
fx.setAttr = true;
}
};
}
);
function getElementStyles( elem ) {
var key, len,
style = elem.ownerDocument.defaultView ?
elem.ownerDocument.defaultView.getComputedStyle( elem, null ) :
elem.currentStyle,
styles = {};
if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
len = style.length;
while ( len-- ) {
key = style[ len ];
if ( typeof style[ key ] === "string" ) {
styles[ $.camelCase( key ) ] = style[ key ];
}
}
// Support: Opera, IE <9
} else {
for ( key in style ) {
if ( typeof style[ key ] === "string" ) {
styles[ key ] = style[ key ];
}
}
}
return styles;
}
function styleDifference( oldStyle, newStyle ) {
var diff = {},
name, value;
for ( name in newStyle ) {
value = newStyle[ name ];
if ( oldStyle[ name ] !== value ) {
if ( !shorthandStyles[ name ] ) {
if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
diff[ name ] = value;
}
}
}
}
return diff;
}
// Support: jQuery <1.8
if ( !$.fn.addBack ) {
$.fn.addBack = function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
};
}
$.effects.animateClass = function( value, duration, easing, callback ) {
var o = $.speed( duration, easing, callback );
return this.queue( function() {
var animated = $( this ),
baseClass = animated.attr( "class" ) || "",
applyClassChange,
allAnimations = o.children ? animated.find( "*" ).addBack() : animated;
// Map the animated objects to store the original styles.
allAnimations = allAnimations.map( function() {
var el = $( this );
return {
el: el,
start: getElementStyles( this )
};
} );
// Apply class change
applyClassChange = function() {
$.each( classAnimationActions, function( i, action ) {
if ( value[ action ] ) {
animated[ action + "Class" ]( value[ action ] );
}
} );
};
applyClassChange();
// Map all animated objects again - calculate new styles and diff
allAnimations = allAnimations.map( function() {
this.end = getElementStyles( this.el[ 0 ] );
this.diff = styleDifference( this.start, this.end );
return this;
} );
// Apply original class
animated.attr( "class", baseClass );
// Map all animated objects again - this time collecting a promise
allAnimations = allAnimations.map( function() {
var styleInfo = this,
dfd = $.Deferred(),
opts = $.extend( {}, o, {
queue: false,
complete: function() {
dfd.resolve( styleInfo );
}
} );
this.el.animate( this.diff, opts );
return dfd.promise();
} );
// Once all animations have completed:
$.when.apply( $, allAnimations.get() ).done( function() {
// Set the final class
applyClassChange();
// For each animated element,
// clear all css properties that were animated
$.each( arguments, function() {
var el = this.el;
$.each( this.diff, function( key ) {
el.css( key, "" );
} );
} );
// This is guarnteed to be there if you use jQuery.speed()
// it also handles dequeuing the next anim...
o.complete.call( animated[ 0 ] );
} );
} );
};
$.fn.extend( {
addClass: ( function( orig ) {
return function( classNames, speed, easing, callback ) {
return speed ?
$.effects.animateClass.call( this,
{ add: classNames }, speed, easing, callback ) :
orig.apply( this, arguments );
};
} )( $.fn.addClass ),
removeClass: ( function( orig ) {
return function( classNames, speed, easing, callback ) {
return arguments.length > 1 ?
$.effects.animateClass.call( this,
{ remove: classNames }, speed, easing, callback ) :
orig.apply( this, arguments );
};
} )( $.fn.removeClass ),
toggleClass: ( function( orig ) {
return function( classNames, force, speed, easing, callback ) {
if ( typeof force === "boolean" || force === undefined ) {
if ( !speed ) {
// Without speed parameter
return orig.apply( this, arguments );
} else {
return $.effects.animateClass.call( this,
( force ? { add: classNames } : { remove: classNames } ),
speed, easing, callback );
}
} else {
// Without force parameter
return $.effects.animateClass.call( this,
{ toggle: classNames }, force, speed, easing );
}
};
} )( $.fn.toggleClass ),
switchClass: function( remove, add, speed, easing, callback ) {
return $.effects.animateClass.call( this, {
add: add,
remove: remove
}, speed, easing, callback );
}
} );
} )();
/******************************************************************************/
/*********************************** EFFECTS **********************************/
/******************************************************************************/
( function() {
if ( $.expr && $.expr.filters && $.expr.filters.animated ) {
$.expr.filters.animated = ( function( orig ) {
return function( elem ) {
return !!$( elem ).data( dataSpaceAnimated ) || orig( elem );
};
} )( $.expr.filters.animated );
}
if ( $.uiBackCompat !== false ) {
$.extend( $.effects, {
// Saves a set of properties in a data storage
save: function( element, set ) {
var i = 0, length = set.length;
for ( ; i < length; i++ ) {
if ( set[ i ] !== null ) {
element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
}
}
},
// Restores a set of previously saved properties from a data storage
restore: function( element, set ) {
var val, i = 0, length = set.length;
for ( ; i < length; i++ ) {
if ( set[ i ] !== null ) {
val = element.data( dataSpace + set[ i ] );
element.css( set[ i ], val );
}
}
},
setMode: function( el, mode ) {
if ( mode === "toggle" ) {
mode = el.is( ":hidden" ) ? "show" : "hide";
}
return mode;
},
// Wraps the element around a wrapper that copies position properties
createWrapper: function( element ) {
// If the element is already wrapped, return it
if ( element.parent().is( ".ui-effects-wrapper" ) ) {
return element.parent();
}
// Wrap the element
var props = {
width: element.outerWidth( true ),
height: element.outerHeight( true ),
"float": element.css( "float" )
},
wrapper = $( "<div></div>" )
.addClass( "ui-effects-wrapper" )
.css( {
fontSize: "100%",
background: "transparent",
border: "none",
margin: 0,
padding: 0
} ),
// Store the size in case width/height are defined in % - Fixes #5245
size = {
width: element.width(),
height: element.height()
},
active = document.activeElement;
// Support: Firefox
// Firefox incorrectly exposes anonymous content
// https://bugzilla.mozilla.org/show_bug.cgi?id=561664
try {
active.id;
} catch ( e ) {
active = document.body;
}
element.wrap( wrapper );
// Fixes #7595 - Elements lose focus when wrapped.
if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
$( active ).trigger( "focus" );
}
// Hotfix for jQuery 1.4 since some change in wrap() seems to actually
// lose the reference to the wrapped element
wrapper = element.parent();
// Transfer positioning properties to the wrapper
if ( element.css( "position" ) === "static" ) {
wrapper.css( { position: "relative" } );
element.css( { position: "relative" } );
} else {
$.extend( props, {
position: element.css( "position" ),
zIndex: element.css( "z-index" )
} );
$.each( [ "top", "left", "bottom", "right" ], function( i, pos ) {
props[ pos ] = element.css( pos );
if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
props[ pos ] = "auto";
}
} );
element.css( {
position: "relative",
top: 0,
left: 0,
right: "auto",
bottom: "auto"
} );
}
element.css( size );
return wrapper.css( props ).show();
},
removeWrapper: function( element ) {
var active = document.activeElement;
if ( element.parent().is( ".ui-effects-wrapper" ) ) {
element.parent().replaceWith( element );
// Fixes #7595 - Elements lose focus when wrapped.
if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
$( active ).trigger( "focus" );
}
}
return element;
}
} );
}
$.extend( $.effects, {
version: "1.12.1",
define: function( name, mode, effect ) {
if ( !effect ) {
effect = mode;
mode = "effect";
}
$.effects.effect[ name ] = effect;
$.effects.effect[ name ].mode = mode;
return effect;
},
scaledDimensions: function( element, percent, direction ) {
if ( percent === 0 ) {
return {
height: 0,
width: 0,
outerHeight: 0,
outerWidth: 0
};
}
var x = direction !== "horizontal" ? ( ( percent || 100 ) / 100 ) : 1,
y = direction !== "vertical" ? ( ( percent || 100 ) / 100 ) : 1;
return {
height: element.height() * y,
width: element.width() * x,
outerHeight: element.outerHeight() * y,
outerWidth: element.outerWidth() * x
};
},
clipToBox: function( animation ) {
return {
width: animation.clip.right - animation.clip.left,
height: animation.clip.bottom - animation.clip.top,
left: animation.clip.left,
top: animation.clip.top
};
},
// Injects recently queued functions to be first in line (after "inprogress")
unshift: function( element, queueLength, count ) {
var queue = element.queue();
if ( queueLength > 1 ) {
queue.splice.apply( queue,
[ 1, 0 ].concat( queue.splice( queueLength, count ) ) );
}
element.dequeue();
},
saveStyle: function( element ) {
element.data( dataSpaceStyle, element[ 0 ].style.cssText );
},
restoreStyle: function( element ) {
element[ 0 ].style.cssText = element.data( dataSpaceStyle ) || "";
element.removeData( dataSpaceStyle );
},
mode: function( element, mode ) {
var hidden = element.is( ":hidden" );
if ( mode === "toggle" ) {
mode = hidden ? "show" : "hide";
}
if ( hidden ? mode === "hide" : mode === "show" ) {
mode = "none";
}
return mode;
},
// Translates a [top,left] array into a baseline value
getBaseline: function( origin, original ) {
var y, x;
switch ( origin[ 0 ] ) {
case "top":
y = 0;
break;
case "middle":
y = 0.5;
break;
case "bottom":
y = 1;
break;
default:
y = origin[ 0 ] / original.height;
}
switch ( origin[ 1 ] ) {
case "left":
x = 0;
break;
case "center":
x = 0.5;
break;
case "right":
x = 1;
break;
default:
x = origin[ 1 ] / original.width;
}
return {
x: x,
y: y
};
},
// Creates a placeholder element so that the original element can be made absolute
createPlaceholder: function( element ) {
var placeholder,
cssPosition = element.css( "position" ),
position = element.position();
// Lock in margins first to account for form elements, which
// will change margin if you explicitly set height
// see: http://jsfiddle.net/JZSMt/3/ https://bugs.webkit.org/show_bug.cgi?id=107380
// Support: Safari
element.css( {
marginTop: element.css( "marginTop" ),
marginBottom: element.css( "marginBottom" ),
marginLeft: element.css( "marginLeft" ),
marginRight: element.css( "marginRight" )
} )
.outerWidth( element.outerWidth() )
.outerHeight( element.outerHeight() );
if ( /^(static|relative)/.test( cssPosition ) ) {
cssPosition = "absolute";
placeholder = $( "<" + element[ 0 ].nodeName + ">" ).insertAfter( element ).css( {
// Convert inline to inline block to account for inline elements
// that turn to inline block based on content (like img)
display: /^(inline|ruby)/.test( element.css( "display" ) ) ?
"inline-block" :
"block",
visibility: "hidden",
// Margins need to be set to account for margin collapse
marginTop: element.css( "marginTop" ),
marginBottom: element.css( "marginBottom" ),
marginLeft: element.css( "marginLeft" ),
marginRight: element.css( "marginRight" ),
"float": element.css( "float" )
} )
.outerWidth( element.outerWidth() )
.outerHeight( element.outerHeight() )
.addClass( "ui-effects-placeholder" );
element.data( dataSpace + "placeholder", placeholder );
}
element.css( {
position: cssPosition,
left: position.left,
top: position.top
} );
return placeholder;
},
removePlaceholder: function( element ) {
var dataKey = dataSpace + "placeholder",
placeholder = element.data( dataKey );
if ( placeholder ) {
placeholder.remove();
element.removeData( dataKey );
}
},
// Removes a placeholder if it exists and restores
// properties that were modified during placeholder creation
cleanUp: function( element ) {
$.effects.restoreStyle( element );
$.effects.removePlaceholder( element );
},
setTransition: function( element, list, factor, value ) {
value = value || {};
$.each( list, function( i, x ) {
var unit = element.cssUnit( x );
if ( unit[ 0 ] > 0 ) {
value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
}
} );
return value;
}
} );
// Return an effect options object for the given parameters:
function _normalizeArguments( effect, options, speed, callback ) {
// Allow passing all options as the first parameter
if ( $.isPlainObject( effect ) ) {
options = effect;
effect = effect.effect;
}
// Convert to an object
effect = { effect: effect };
// Catch (effect, null, ...)
if ( options == null ) {
options = {};
}
// Catch (effect, callback)
if ( $.isFunction( options ) ) {
callback = options;
speed = null;
options = {};
}
// Catch (effect, speed, ?)
if ( typeof options === "number" || $.fx.speeds[ options ] ) {
callback = speed;
speed = options;
options = {};
}
// Catch (effect, options, callback)
if ( $.isFunction( speed ) ) {
callback = speed;
speed = null;
}
// Add options to effect
if ( options ) {
$.extend( effect, options );
}
speed = speed || options.duration;
effect.duration = $.fx.off ? 0 :
typeof speed === "number" ? speed :
speed in $.fx.speeds ? $.fx.speeds[ speed ] :
$.fx.speeds._default;
effect.complete = callback || options.complete;
return effect;
}
function standardAnimationOption( option ) {
// Valid standard speeds (nothing, number, named speed)
if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
return true;
}
// Invalid strings - treat as "normal" speed
if ( typeof option === "string" && !$.effects.effect[ option ] ) {
return true;
}
// Complete callback
if ( $.isFunction( option ) ) {
return true;
}
// Options hash (but not naming an effect)
if ( typeof option === "object" && !option.effect ) {
return true;
}
// Didn't match any standard API
return false;
}
$.fn.extend( {
effect: function( /* effect, options, speed, callback */ ) {
var args = _normalizeArguments.apply( this, arguments ),
effectMethod = $.effects.effect[ args.effect ],
defaultMode = effectMethod.mode,
queue = args.queue,
queueName = queue || "fx",
complete = args.complete,
mode = args.mode,
modes = [],
prefilter = function( next ) {
var el = $( this ),
normalizedMode = $.effects.mode( el, mode ) || defaultMode;
// Sentinel for duck-punching the :animated psuedo-selector
el.data( dataSpaceAnimated, true );
// Save effect mode for later use,
// we can't just call $.effects.mode again later,
// as the .show() below destroys the initial state
modes.push( normalizedMode );
// See $.uiBackCompat inside of run() for removal of defaultMode in 1.13
if ( defaultMode && ( normalizedMode === "show" ||
( normalizedMode === defaultMode && normalizedMode === "hide" ) ) ) {
el.show();
}
if ( !defaultMode || normalizedMode !== "none" ) {
$.effects.saveStyle( el );
}
if ( $.isFunction( next ) ) {
next();
}
};
if ( $.fx.off || !effectMethod ) {
// Delegate to the original method (e.g., .show()) if possible
if ( mode ) {
return this[ mode ]( args.duration, complete );
} else {
return this.each( function() {
if ( complete ) {
complete.call( this );
}
} );
}
}
function run( next ) {
var elem = $( this );
function cleanup() {
elem.removeData( dataSpaceAnimated );
$.effects.cleanUp( elem );
if ( args.mode === "hide" ) {
elem.hide();
}
done();
}
function done() {
if ( $.isFunction( complete ) ) {
complete.call( elem[ 0 ] );
}
if ( $.isFunction( next ) ) {
next();
}
}
// Override mode option on a per element basis,
// as toggle can be either show or hide depending on element state
args.mode = modes.shift();
if ( $.uiBackCompat !== false && !defaultMode ) {
if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {
// Call the core method to track "olddisplay" properly
elem[ mode ]();
done();
} else {
effectMethod.call( elem[ 0 ], args, done );
}
} else {
if ( args.mode === "none" ) {
// Call the core method to track "olddisplay" properly
elem[ mode ]();
done();
} else {
effectMethod.call( elem[ 0 ], args, cleanup );
}
}
}
// Run prefilter on all elements first to ensure that
// any showing or hiding happens before placeholder creation,
// which ensures that any layout changes are correctly captured.
return queue === false ?
this.each( prefilter ).each( run ) :
this.queue( queueName, prefilter ).queue( queueName, run );
},
show: ( function( orig ) {
return function( option ) {
if ( standardAnimationOption( option ) ) {
return orig.apply( this, arguments );
} else {
var args = _normalizeArguments.apply( this, arguments );
args.mode = "show";
return this.effect.call( this, args );
}
};
} )( $.fn.show ),
hide: ( function( orig ) {
return function( option ) {
if ( standardAnimationOption( option ) ) {
return orig.apply( this, arguments );
} else {
var args = _normalizeArguments.apply( this, arguments );
args.mode = "hide";
return this.effect.call( this, args );
}
};
} )( $.fn.hide ),
toggle: ( function( orig ) {
return function( option ) {
if ( standardAnimationOption( option ) || typeof option === "boolean" ) {
return orig.apply( this, arguments );
} else {
var args = _normalizeArguments.apply( this, arguments );
args.mode = "toggle";
return this.effect.call( this, args );
}
};
} )( $.fn.toggle ),
cssUnit: function( key ) {
var style = this.css( key ),
val = [];
$.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
if ( style.indexOf( unit ) > 0 ) {
val = [ parseFloat( style ), unit ];
}
} );
return val;
},
cssClip: function( clipObj ) {
if ( clipObj ) {
return this.css( "clip", "rect(" + clipObj.top + "px " + clipObj.right + "px " +
clipObj.bottom + "px " + clipObj.left + "px)" );
}
return parseClip( this.css( "clip" ), this );
},
transfer: function( options, done ) {
var element = $( this ),
target = $( options.to ),
targetFixed = target.css( "position" ) === "fixed",
body = $( "body" ),
fixTop = targetFixed ? body.scrollTop() : 0,
fixLeft = targetFixed ? body.scrollLeft() : 0,
endPosition = target.offset(),
animation = {
top: endPosition.top - fixTop,
left: endPosition.left - fixLeft,
height: target.innerHeight(),
width: target.innerWidth()
},
startPosition = element.offset(),
transfer = $( "<div class='ui-effects-transfer'></div>" )
.appendTo( "body" )
.addClass( options.className )
.css( {
top: startPosition.top - fixTop,
left: startPosition.left - fixLeft,
height: element.innerHeight(),
width: element.innerWidth(),
position: targetFixed ? "fixed" : "absolute"
} )
.animate( animation, options.duration, options.easing, function() {
transfer.remove();
if ( $.isFunction( done ) ) {
done();
}
} );
}
} );
function parseClip( str, element ) {
var outerWidth = element.outerWidth(),
outerHeight = element.outerHeight(),
clipRegex = /^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/,
values = clipRegex.exec( str ) || [ "", 0, outerWidth, outerHeight, 0 ];
return {
top: parseFloat( values[ 1 ] ) || 0,
right: values[ 2 ] === "auto" ? outerWidth : parseFloat( values[ 2 ] ),
bottom: values[ 3 ] === "auto" ? outerHeight : parseFloat( values[ 3 ] ),
left: parseFloat( values[ 4 ] ) || 0
};
}
$.fx.step.clip = function( fx ) {
if ( !fx.clipInit ) {
fx.start = $( fx.elem ).cssClip();
if ( typeof fx.end === "string" ) {
fx.end = parseClip( fx.end, fx.elem );
}
fx.clipInit = true;
}
$( fx.elem ).cssClip( {
top: fx.pos * ( fx.end.top - fx.start.top ) + fx.start.top,
right: fx.pos * ( fx.end.right - fx.start.right ) + fx.start.right,
bottom: fx.pos * ( fx.end.bottom - fx.start.bottom ) + fx.start.bottom,
left: fx.pos * ( fx.end.left - fx.start.left ) + fx.start.left
} );
};
} )();
/******************************************************************************/
/*********************************** EASING ***********************************/
/******************************************************************************/
( function() {
// Based on easing equations from Robert Penner (http://www.robertpenner.com/easing)
var baseEasings = {};
$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
baseEasings[ name ] = function( p ) {
return Math.pow( p, i + 2 );
};
} );
$.extend( baseEasings, {
Sine: function( p ) {
return 1 - Math.cos( p * Math.PI / 2 );
},
Circ: function( p ) {
return 1 - Math.sqrt( 1 - p * p );
},
Elastic: function( p ) {
return p === 0 || p === 1 ? p :
-Math.pow( 2, 8 * ( p - 1 ) ) * Math.sin( ( ( p - 1 ) * 80 - 7.5 ) * Math.PI / 15 );
},
Back: function( p ) {
return p * p * ( 3 * p - 2 );
},
Bounce: function( p ) {
var pow2,
bounce = 4;
while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
}
} );
$.each( baseEasings, function( name, easeIn ) {
$.easing[ "easeIn" + name ] = easeIn;
$.easing[ "easeOut" + name ] = function( p ) {
return 1 - easeIn( 1 - p );
};
$.easing[ "easeInOut" + name ] = function( p ) {
return p < 0.5 ?
easeIn( p * 2 ) / 2 :
1 - easeIn( p * -2 + 2 ) / 2;
};
} );
} )();
var effect = $.effects;
/*!
* jQuery UI Effects Slide 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Slide Effect
//>>group: Effects
//>>description: Slides an element in and out of the viewport.
//>>docs: http://api.jqueryui.com/slide-effect/
//>>demos: http://jqueryui.com/effect/
var effectsEffectSlide = $.effects.define( "slide", "show", function( options, done ) {
var startClip, startRef,
element = $( this ),
map = {
up: [ "bottom", "top" ],
down: [ "top", "bottom" ],
left: [ "right", "left" ],
right: [ "left", "right" ]
},
mode = options.mode,
direction = options.direction || "left",
ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
positiveMotion = ( direction === "up" || direction === "left" ),
distance = options.distance ||
element[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ),
animation = {};
$.effects.createPlaceholder( element );
startClip = element.cssClip();
startRef = element.position()[ ref ];
// Define hide animation
animation[ ref ] = ( positiveMotion ? -1 : 1 ) * distance + startRef;
animation.clip = element.cssClip();
animation.clip[ map[ direction ][ 1 ] ] = animation.clip[ map[ direction ][ 0 ] ];
// Reverse the animation if we're showing
if ( mode === "show" ) {
element.cssClip( animation.clip );
element.css( ref, animation[ ref ] );
animation.clip = startClip;
animation[ ref ] = startRef;
}
// Actually animate
element.animate( animation, {
queue: false,
duration: options.duration,
easing: options.easing,
complete: done
} );
} );
}));
|
gpl-2.0
|
xponen/Zero-K
|
units/corclog.lua
|
4115
|
unitDef = {
unitname = [[corclog]],
name = [[Dirtbag]],
description = [[Box of Dirt]],
acceleration = 0.2,
brakeRate = 0.2,
buildCostEnergy = 30,
buildCostMetal = 30,
buildPic = [[corclog.png]],
buildTime = 30,
canAttack = false,
canFight = true,
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND STUPIDTARGET]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[34 45 27]],
collisionVolumeType = [[box]],
customParams = {
canjump = [[1]],
description_es = [[Caja de tierra]],
description_fr = [[]],
description_it = [[Scatola di terra]],
description_de = [[Behalter voller Dreck]],
description_pl = [[Pudlo z piachem]],
helptext = [[The Dirtbag exists to block enemy movement and generally get in the way. They are so dedicated to this task that they release their dirt payload upon death to form little annoying mounds. While waiting for their fate Dirtbags enjoy headbutting and scouting.]],
helptext_pl = [[Dirtbag istnieje po to, by blokowac ruch przeciwnika i sie mu naprzykrzac. Po zniszczeniu wysypuje sie z nich piach, tworzac utrudniajacy poruszanie sie pagorek. Dirtbag moze takze uzywac swojego pudelka, by uderzac przeciwnikow z dynki, sprawdza sie tez jako zwiadowca.]],
},
explodeAs = [[CLOGGER_EXPLODE]],
footprintX = 2,
footprintZ = 2,
iconType = [[clogger]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
maxDamage = 600,
maxSlope = 36,
maxVelocity = 2.5,
maxWaterDepth = 22,
minCloakDistance = 75,
movementClass = [[KBOT2]],
noChaseCategory = [[TERRAFORM FIXEDWING GUNSHIP]],
objectName = [[clogger.s3o]],
script = [[corclog.lua]],
seismicSignature = 4,
selfDestructAs = [[CLOGGER_EXPLODE]],
selfDestructCountdown = 0,
sightDistance = 300,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 22,
turnRate = 2000,
upright = true,
weapons = {
{
def = [[Headbutt]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP FIXEDWING]],
},
},
weaponDefs = {
Headbutt = {
name = [[Headbutt]],
beamTime = 0.03,
avoidFeature = false,
avoidFriendly = false,
avoidGround = false,
canattackground = true,
collideFeature = false,
collideFriendly = false,
collideGround = false,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
damage = {
default = 36,
planes = 36,
subs = 3.6,
},
explosionGenerator = [[custom:none]],
fireStarter = 90,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 0,
lodDistance = 10000,
noSelfDamage = true,
range = 50,
reloadtime = 2,
rgbColor = [[1 0.25 0]],
soundStart = [[explosion/ex_small4_2]],
soundStartVolume = 25,
targetborder = 1,
targetMoveError = 0,
thickness = 0,
tolerance = 1000000,
turret = true,
waterweapon = true,
weaponType = [[BeamLaser]],
},
},
}
return lowerkeys({ corclog = unitDef })
|
gpl-2.0
|
acbalingit/scilab-sivp
|
thirdparty/opencv/windows/include/opencv2/core/wimage.hpp
|
21372
|
///////////////////////////////////////////////////////////////////////////////
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to
// this license. If you do not agree to this license, do not download,
// install, copy or use the software.
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2008, Google, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation or contributors may not be used to endorse
// or promote products derived from this software without specific
// prior written permission.
//
// This software is provided by the copyright holders and contributors "as is"
// and any express or implied warranties, including, but not limited to, the
// implied warranties of merchantability and fitness for a particular purpose
// are disclaimed. In no event shall the Intel Corporation or contributors be
// liable for any direct, indirect, incidental, special, exemplary, or
// consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
/////////////////////////////////////////////////////////////////////////////////
//
// Image class which provides a thin layer around an IplImage. The goals
// of the class design are:
// 1. All the data has explicit ownership to avoid memory leaks
// 2. No hidden allocations or copies for performance.
// 3. Easy access to OpenCV methods (which will access IPP if available)
// 4. Can easily treat external data as an image
// 5. Easy to create images which are subsets of other images
// 6. Fast pixel access which can take advantage of number of channels
// if known at compile time.
//
// The WImage class is the image class which provides the data accessors.
// The 'W' comes from the fact that it is also a wrapper around the popular
// but inconvenient IplImage class. A WImage can be constructed either using a
// WImageBuffer class which allocates and frees the data,
// or using a WImageView class which constructs a subimage or a view into
// external data. The view class does no memory management. Each class
// actually has two versions, one when the number of channels is known at
// compile time and one when it isn't. Using the one with the number of
// channels specified can provide some compile time optimizations by using the
// fact that the number of channels is a constant.
//
// We use the convention (c,r) to refer to column c and row r with (0,0) being
// the upper left corner. This is similar to standard Euclidean coordinates
// with the first coordinate varying in the horizontal direction and the second
// coordinate varying in the vertical direction.
// Thus (c,r) is usually in the domain [0, width) X [0, height)
//
// Example usage:
// WImageBuffer3_b im(5,7); // Make a 5X7 3 channel image of type uchar
// WImageView3_b sub_im(im, 2,2, 3,3); // 3X3 submatrix
// vector<float> vec(10, 3.0f);
// WImageView1_f user_im(&vec[0], 2, 5); // 2X5 image w/ supplied data
//
// im.SetZero(); // same as cvSetZero(im.Ipl())
// *im(2, 3) = 15; // Modify the element at column 2, row 3
// MySetRand(&sub_im);
//
// // Copy the second row into the first. This can be done with no memory
// // allocation and will use SSE if IPP is available.
// int w = im.Width();
// im.View(0,0, w,1).CopyFrom(im.View(0,1, w,1));
//
// // Doesn't care about source of data since using WImage
// void MySetRand(WImage_b* im) { // Works with any number of channels
// for (int r = 0; r < im->Height(); ++r) {
// float* row = im->Row(r);
// for (int c = 0; c < im->Width(); ++c) {
// for (int ch = 0; ch < im->Channels(); ++ch, ++row) {
// *row = uchar(rand() & 255);
// }
// }
// }
// }
//
// Functions that are not part of the basic image allocation, viewing, and
// access should come from OpenCV, except some useful functions that are not
// part of OpenCV can be found in wimage_util.h
#ifndef __OPENCV_CORE_WIMAGE_HPP__
#define __OPENCV_CORE_WIMAGE_HPP__
#include "opencv2/core/core_c.h"
#ifdef __cplusplus
namespace cv {
template <typename T> class WImage;
template <typename T> class WImageBuffer;
template <typename T> class WImageView;
template<typename T, int C> class WImageC;
template<typename T, int C> class WImageBufferC;
template<typename T, int C> class WImageViewC;
// Commonly used typedefs.
typedef WImage<uchar> WImage_b;
typedef WImageView<uchar> WImageView_b;
typedef WImageBuffer<uchar> WImageBuffer_b;
typedef WImageC<uchar, 1> WImage1_b;
typedef WImageViewC<uchar, 1> WImageView1_b;
typedef WImageBufferC<uchar, 1> WImageBuffer1_b;
typedef WImageC<uchar, 3> WImage3_b;
typedef WImageViewC<uchar, 3> WImageView3_b;
typedef WImageBufferC<uchar, 3> WImageBuffer3_b;
typedef WImage<float> WImage_f;
typedef WImageView<float> WImageView_f;
typedef WImageBuffer<float> WImageBuffer_f;
typedef WImageC<float, 1> WImage1_f;
typedef WImageViewC<float, 1> WImageView1_f;
typedef WImageBufferC<float, 1> WImageBuffer1_f;
typedef WImageC<float, 3> WImage3_f;
typedef WImageViewC<float, 3> WImageView3_f;
typedef WImageBufferC<float, 3> WImageBuffer3_f;
// There isn't a standard for signed and unsigned short so be more
// explicit in the typename for these cases.
typedef WImage<short> WImage_16s;
typedef WImageView<short> WImageView_16s;
typedef WImageBuffer<short> WImageBuffer_16s;
typedef WImageC<short, 1> WImage1_16s;
typedef WImageViewC<short, 1> WImageView1_16s;
typedef WImageBufferC<short, 1> WImageBuffer1_16s;
typedef WImageC<short, 3> WImage3_16s;
typedef WImageViewC<short, 3> WImageView3_16s;
typedef WImageBufferC<short, 3> WImageBuffer3_16s;
typedef WImage<ushort> WImage_16u;
typedef WImageView<ushort> WImageView_16u;
typedef WImageBuffer<ushort> WImageBuffer_16u;
typedef WImageC<ushort, 1> WImage1_16u;
typedef WImageViewC<ushort, 1> WImageView1_16u;
typedef WImageBufferC<ushort, 1> WImageBuffer1_16u;
typedef WImageC<ushort, 3> WImage3_16u;
typedef WImageViewC<ushort, 3> WImageView3_16u;
typedef WImageBufferC<ushort, 3> WImageBuffer3_16u;
//
// WImage definitions
//
// This WImage class gives access to the data it refers to. It can be
// constructed either by allocating the data with a WImageBuffer class or
// using the WImageView class to refer to a subimage or outside data.
template<typename T>
class WImage
{
public:
typedef T BaseType;
// WImage is an abstract class with no other virtual methods so make the
// destructor virtual.
virtual ~WImage() = 0;
// Accessors
IplImage* Ipl() {return image_; }
const IplImage* Ipl() const {return image_; }
T* ImageData() { return reinterpret_cast<T*>(image_->imageData); }
const T* ImageData() const {
return reinterpret_cast<const T*>(image_->imageData);
}
int Width() const {return image_->width; }
int Height() const {return image_->height; }
// WidthStep is the number of bytes to go to the pixel with the next y coord
int WidthStep() const {return image_->widthStep; }
int Channels() const {return image_->nChannels; }
int ChannelSize() const {return sizeof(T); } // number of bytes per channel
// Number of bytes per pixel
int PixelSize() const {return Channels() * ChannelSize(); }
// Return depth type (e.g. IPL_DEPTH_8U, IPL_DEPTH_32F) which is the number
// of bits per channel and with the signed bit set.
// This is known at compile time using specializations.
int Depth() const;
inline const T* Row(int r) const {
return reinterpret_cast<T*>(image_->imageData + r*image_->widthStep);
}
inline T* Row(int r) {
return reinterpret_cast<T*>(image_->imageData + r*image_->widthStep);
}
// Pixel accessors which returns a pointer to the start of the channel
inline T* operator() (int c, int r) {
return reinterpret_cast<T*>(image_->imageData + r*image_->widthStep) +
c*Channels();
}
inline const T* operator() (int c, int r) const {
return reinterpret_cast<T*>(image_->imageData + r*image_->widthStep) +
c*Channels();
}
// Copy the contents from another image which is just a convenience to cvCopy
void CopyFrom(const WImage<T>& src) { cvCopy(src.Ipl(), image_); }
// Set contents to zero which is just a convenient to cvSetZero
void SetZero() { cvSetZero(image_); }
// Construct a view into a region of this image
WImageView<T> View(int c, int r, int width, int height);
protected:
// Disallow copy and assignment
WImage(const WImage&);
void operator=(const WImage&);
explicit WImage(IplImage* img) : image_(img) {
assert(!img || img->depth == Depth());
}
void SetIpl(IplImage* image) {
assert(!image || image->depth == Depth());
image_ = image;
}
IplImage* image_;
};
// Image class when both the pixel type and number of channels
// are known at compile time. This wrapper will speed up some of the operations
// like accessing individual pixels using the () operator.
template<typename T, int C>
class WImageC : public WImage<T>
{
public:
typedef typename WImage<T>::BaseType BaseType;
enum { kChannels = C };
explicit WImageC(IplImage* img) : WImage<T>(img) {
assert(!img || img->nChannels == Channels());
}
// Construct a view into a region of this image
WImageViewC<T, C> View(int c, int r, int width, int height);
// Copy the contents from another image which is just a convenience to cvCopy
void CopyFrom(const WImageC<T, C>& src) {
cvCopy(src.Ipl(), WImage<T>::image_);
}
// WImageC is an abstract class with no other virtual methods so make the
// destructor virtual.
virtual ~WImageC() = 0;
int Channels() const {return C; }
protected:
// Disallow copy and assignment
WImageC(const WImageC&);
void operator=(const WImageC&);
void SetIpl(IplImage* image) {
assert(!image || image->depth == WImage<T>::Depth());
WImage<T>::SetIpl(image);
}
};
//
// WImageBuffer definitions
//
// Image class which owns the data, so it can be allocated and is always
// freed. It cannot be copied but can be explicity cloned.
//
template<typename T>
class WImageBuffer : public WImage<T>
{
public:
typedef typename WImage<T>::BaseType BaseType;
// Default constructor which creates an object that can be
WImageBuffer() : WImage<T>(0) {}
WImageBuffer(int width, int height, int nchannels) : WImage<T>(0) {
Allocate(width, height, nchannels);
}
// Constructor which takes ownership of a given IplImage so releases
// the image on destruction.
explicit WImageBuffer(IplImage* img) : WImage<T>(img) {}
// Allocate an image. Does nothing if current size is the same as
// the new size.
void Allocate(int width, int height, int nchannels);
// Set the data to point to an image, releasing the old data
void SetIpl(IplImage* img) {
ReleaseImage();
WImage<T>::SetIpl(img);
}
// Clone an image which reallocates the image if of a different dimension.
void CloneFrom(const WImage<T>& src) {
Allocate(src.Width(), src.Height(), src.Channels());
CopyFrom(src);
}
~WImageBuffer() {
ReleaseImage();
}
// Release the image if it isn't null.
void ReleaseImage() {
if (WImage<T>::image_) {
IplImage* image = WImage<T>::image_;
cvReleaseImage(&image);
WImage<T>::SetIpl(0);
}
}
bool IsNull() const {return WImage<T>::image_ == NULL; }
private:
// Disallow copy and assignment
WImageBuffer(const WImageBuffer&);
void operator=(const WImageBuffer&);
};
// Like a WImageBuffer class but when the number of channels is known
// at compile time.
template<typename T, int C>
class WImageBufferC : public WImageC<T, C>
{
public:
typedef typename WImage<T>::BaseType BaseType;
enum { kChannels = C };
// Default constructor which creates an object that can be
WImageBufferC() : WImageC<T, C>(0) {}
WImageBufferC(int width, int height) : WImageC<T, C>(0) {
Allocate(width, height);
}
// Constructor which takes ownership of a given IplImage so releases
// the image on destruction.
explicit WImageBufferC(IplImage* img) : WImageC<T, C>(img) {}
// Allocate an image. Does nothing if current size is the same as
// the new size.
void Allocate(int width, int height);
// Set the data to point to an image, releasing the old data
void SetIpl(IplImage* img) {
ReleaseImage();
WImageC<T, C>::SetIpl(img);
}
// Clone an image which reallocates the image if of a different dimension.
void CloneFrom(const WImageC<T, C>& src) {
Allocate(src.Width(), src.Height());
CopyFrom(src);
}
~WImageBufferC() {
ReleaseImage();
}
// Release the image if it isn't null.
void ReleaseImage() {
if (WImage<T>::image_) {
IplImage* image = WImage<T>::image_;
cvReleaseImage(&image);
WImageC<T, C>::SetIpl(0);
}
}
bool IsNull() const {return WImage<T>::image_ == NULL; }
private:
// Disallow copy and assignment
WImageBufferC(const WImageBufferC&);
void operator=(const WImageBufferC&);
};
//
// WImageView definitions
//
// View into an image class which allows treating a subimage as an image
// or treating external data as an image
//
template<typename T>
class WImageView : public WImage<T>
{
public:
typedef typename WImage<T>::BaseType BaseType;
// Construct a subimage. No checks are done that the subimage lies
// completely inside the original image.
WImageView(WImage<T>* img, int c, int r, int width, int height);
// Refer to external data.
// If not given width_step assumed to be same as width.
WImageView(T* data, int width, int height, int channels, int width_step = -1);
// Refer to external data. This does NOT take ownership
// of the supplied IplImage.
WImageView(IplImage* img) : WImage<T>(img) {}
// Copy constructor
WImageView(const WImage<T>& img) : WImage<T>(0) {
header_ = *(img.Ipl());
WImage<T>::SetIpl(&header_);
}
WImageView& operator=(const WImage<T>& img) {
header_ = *(img.Ipl());
WImage<T>::SetIpl(&header_);
return *this;
}
protected:
IplImage header_;
};
template<typename T, int C>
class WImageViewC : public WImageC<T, C>
{
public:
typedef typename WImage<T>::BaseType BaseType;
enum { kChannels = C };
// Default constructor needed for vectors of views.
WImageViewC();
virtual ~WImageViewC() {}
// Construct a subimage. No checks are done that the subimage lies
// completely inside the original image.
WImageViewC(WImageC<T, C>* img,
int c, int r, int width, int height);
// Refer to external data
WImageViewC(T* data, int width, int height, int width_step = -1);
// Refer to external data. This does NOT take ownership
// of the supplied IplImage.
WImageViewC(IplImage* img) : WImageC<T, C>(img) {}
// Copy constructor which does a shallow copy to allow multiple views
// of same data. gcc-4.1.1 gets confused if both versions of
// the constructor and assignment operator are not provided.
WImageViewC(const WImageC<T, C>& img) : WImageC<T, C>(0) {
header_ = *(img.Ipl());
WImageC<T, C>::SetIpl(&header_);
}
WImageViewC(const WImageViewC<T, C>& img) : WImageC<T, C>(0) {
header_ = *(img.Ipl());
WImageC<T, C>::SetIpl(&header_);
}
WImageViewC& operator=(const WImageC<T, C>& img) {
header_ = *(img.Ipl());
WImageC<T, C>::SetIpl(&header_);
return *this;
}
WImageViewC& operator=(const WImageViewC<T, C>& img) {
header_ = *(img.Ipl());
WImageC<T, C>::SetIpl(&header_);
return *this;
}
protected:
IplImage header_;
};
// Specializations for depth
template<>
inline int WImage<uchar>::Depth() const {return IPL_DEPTH_8U; }
template<>
inline int WImage<signed char>::Depth() const {return IPL_DEPTH_8S; }
template<>
inline int WImage<short>::Depth() const {return IPL_DEPTH_16S; }
template<>
inline int WImage<ushort>::Depth() const {return IPL_DEPTH_16U; }
template<>
inline int WImage<int>::Depth() const {return IPL_DEPTH_32S; }
template<>
inline int WImage<float>::Depth() const {return IPL_DEPTH_32F; }
template<>
inline int WImage<double>::Depth() const {return IPL_DEPTH_64F; }
//
// Pure virtual destructors still need to be defined.
//
template<typename T> inline WImage<T>::~WImage() {}
template<typename T, int C> inline WImageC<T, C>::~WImageC() {}
//
// Allocate ImageData
//
template<typename T>
inline void WImageBuffer<T>::Allocate(int width, int height, int nchannels)
{
if (IsNull() || WImage<T>::Width() != width ||
WImage<T>::Height() != height || WImage<T>::Channels() != nchannels) {
ReleaseImage();
WImage<T>::image_ = cvCreateImage(cvSize(width, height),
WImage<T>::Depth(), nchannels);
}
}
template<typename T, int C>
inline void WImageBufferC<T, C>::Allocate(int width, int height)
{
if (IsNull() || WImage<T>::Width() != width || WImage<T>::Height() != height) {
ReleaseImage();
WImageC<T, C>::SetIpl(cvCreateImage(cvSize(width, height),WImage<T>::Depth(), C));
}
}
//
// ImageView methods
//
template<typename T>
WImageView<T>::WImageView(WImage<T>* img, int c, int r, int width, int height)
: WImage<T>(0)
{
header_ = *(img->Ipl());
header_.imageData = reinterpret_cast<char*>((*img)(c, r));
header_.width = width;
header_.height = height;
WImage<T>::SetIpl(&header_);
}
template<typename T>
WImageView<T>::WImageView(T* data, int width, int height, int nchannels, int width_step)
: WImage<T>(0)
{
cvInitImageHeader(&header_, cvSize(width, height), WImage<T>::Depth(), nchannels);
header_.imageData = reinterpret_cast<char*>(data);
if (width_step > 0) {
header_.widthStep = width_step;
}
WImage<T>::SetIpl(&header_);
}
template<typename T, int C>
WImageViewC<T, C>::WImageViewC(WImageC<T, C>* img, int c, int r, int width, int height)
: WImageC<T, C>(0)
{
header_ = *(img->Ipl());
header_.imageData = reinterpret_cast<char*>((*img)(c, r));
header_.width = width;
header_.height = height;
WImageC<T, C>::SetIpl(&header_);
}
template<typename T, int C>
WImageViewC<T, C>::WImageViewC() : WImageC<T, C>(0) {
cvInitImageHeader(&header_, cvSize(0, 0), WImage<T>::Depth(), C);
header_.imageData = reinterpret_cast<char*>(0);
WImageC<T, C>::SetIpl(&header_);
}
template<typename T, int C>
WImageViewC<T, C>::WImageViewC(T* data, int width, int height, int width_step)
: WImageC<T, C>(0)
{
cvInitImageHeader(&header_, cvSize(width, height), WImage<T>::Depth(), C);
header_.imageData = reinterpret_cast<char*>(data);
if (width_step > 0) {
header_.widthStep = width_step;
}
WImageC<T, C>::SetIpl(&header_);
}
// Construct a view into a region of an image
template<typename T>
WImageView<T> WImage<T>::View(int c, int r, int width, int height) {
return WImageView<T>(this, c, r, width, height);
}
template<typename T, int C>
WImageViewC<T, C> WImageC<T, C>::View(int c, int r, int width, int height) {
return WImageViewC<T, C>(this, c, r, width, height);
}
} // end of namespace
#endif // __cplusplus
#endif
|
gpl-2.0
|
Ghost-script/dyno-chat
|
kickchat/apps/pulsar/apps/data/server/pyparser.py
|
6529
|
'''A parser for redis messages
'''
import sys
from itertools import starmap
ispy3k = sys.version_info >= (3, 0)
if ispy3k:
long = int
string_type = str
else: # pragma nocover
string_type = unicode
nil = b'$-1\r\n'
null_array = b'*-1\r\n'
REPLAY_TYPE = frozenset((b'$', # REDIS_REPLY_STRING,
b'*', # REDIS_REPLY_ARRAY,
b':', # REDIS_REPLY_INTEGER,
b'+', # REDIS_REPLY_STATUS,
b'-')) # REDIS_REPLY_ERROR
class String(object):
__slots__ = ('_length', 'next')
def __init__(self, length, next):
self._length = length
self.next = next
def decode(self, parser, result):
parser._current = None
length = self._length
if length >= 0:
b = parser._inbuffer
if len(b) >= length+2:
parser._inbuffer, chunk = b[length+2:], bytes(b[:length])
if parser.encoding:
return chunk.decode(parser.encoding)
else:
return chunk
else:
parser._current = self
return False
class ArrayTask(object):
__slots__ = ('_length', '_response', 'next')
def __init__(self, length, next):
self._length = length
self._response = []
self.next = next
def decode(self, parser, result):
parser._current = None
length = self._length
if length >= 0:
response = self._response
if result is not False:
response.append(result)
while len(response) < length:
result = parser._get(self)
if result is False:
break
response.append(result)
if len(response) == length:
parser._current = None
return response
elif not parser._current:
parser._current = self
return False
class Parser(object):
'''A python parser for redis.'''
encoding = None
def __init__(self, protocolError, responseError):
self.protocolError = protocolError
self.responseError = responseError
self._current = None
self._inbuffer = bytearray()
def on_connect(self, connection):
if connection.decode_responses:
self.encoding = connection.encoding
def on_disconnect(self):
pass
def feed(self, buffer):
'''Feed new data into the buffer'''
self._inbuffer.extend(buffer)
def get(self):
'''Called by the protocol consumer'''
if self._current:
return self._resume(self._current, False)
else:
return self._get(None)
def bulk(self, value):
if value is None:
return nil
else:
return ('$%d\r\n' % len(value)).encode('utf-8') + value + b'\r\n'
def multi_bulk_len(self, len):
return ('*%s\r\n' % len).encode('utf-8')
def multi_bulk(self, args):
'''Multi bulk encoding for list/tuple ``args``
'''
return null_array if args is None else b''.join(self._pack(args))
def pack_command(self, args):
'''Encode a command to send to the server.
Used by redis clients
'''
return b''.join(self._pack_command(args))
def pack_pipeline(self, commands):
'''Packs pipeline commands into bytes.'''
pack = lambda *args: b''.join(self._pack_command(args))
return b''.join(starmap(pack, (args for args, _ in commands)))
# INTERNALS
def _pack_command(self, args):
crlf = b'\r\n'
yield ('*%d\r\n' % len(args)).encode('utf-8')
for value in args:
if isinstance(value, string_type):
value = value.encode('utf-8')
elif not isinstance(value, bytes):
value = str(value).encode('utf-8')
yield ('$%d\r\n' % len(value)).encode('utf-8')
yield value
yield crlf
def _pack(self, args):
crlf = b'\r\n'
yield ('*%d\r\n' % len(args)).encode('utf-8')
for value in args:
if value is None:
yield nil
elif isinstance(value, bytes):
yield ('$%d\r\n' % len(value)).encode('utf-8')
yield value
yield crlf
elif isinstance(value, string_type):
value = value.encode('utf-8')
yield ('$%d\r\n' % len(value)).encode('utf-8')
yield value
yield crlf
elif hasattr(value, 'items'):
for value in self._pack(tuple(self._lua_dict(value))):
yield value
elif hasattr(value, '__len__'):
for value in self._pack(value):
yield value
else:
value = str(value).encode('utf-8')
yield ('$%d\r\n' % len(value)).encode('utf-8')
yield value
yield crlf
def _lua_dict(self, d):
index = 0
while True:
index += 1
v = d.get(index)
if v is None:
break
yield v
def _get(self, next):
b = self._inbuffer
length = b.find(b'\r\n')
if length >= 0:
self._inbuffer, response = b[length+2:], bytes(b[:length])
rtype, response = response[:1], response[1:]
if rtype == b'-':
return self.responseError(response.decode('utf-8'))
elif rtype == b':':
return long(response)
elif rtype == b'+':
return response
elif rtype == b'$':
task = String(long(response), next)
return task.decode(self, False)
elif rtype == b'*':
task = ArrayTask(long(response), next)
return task.decode(self, False)
else:
# Clear the buffer and raise
self._inbuffer = bytearray()
raise self.protocolError('Protocol Error')
else:
return False
def buffer(self):
'''Current buffer'''
return bytes(self._inbuffer)
def _resume(self, task, result):
result = task.decode(self, result)
if result is not False and task.next:
return self._resume(task.next, result)
else:
return result
|
gpl-2.0
|
default1406/PhyLab
|
PythonExperimentDataHandle/1010212.py
|
2668
|
# -*- coding: utf-8 -*-
from math import sqrt
from math import pi
import phylab
from jinja2 import Environment
from handler import texdir
#texdir = "./tex/"
env = Environment()
def Inertia(m, d, T, l, T2):
# 所有测得的数据必须是5倍周期
I = []#实际值
J = [-1]#理论值
delta = []
for a in T:
a.append(sum(a)/len(a) / 5)
#计算扭转常数k
temp = m[0] * pow(d[0],2) * pow(10,-9) / 8
I.append(temp)
k = 4 * pow(pi,2) * temp / (pow(T[1][-1],2) - pow(T[0][-1],2))
for i in range(1,4):
#圆筒转动惯量
if i == 1:
temp1 = (pow(T[2][-1],2)-pow(T[0][-1],2)) * k / (4 * pow(pi,2))
temp2 = m[1] * (d[1]**2 + d[2]**2) * pow(10,-9) / 8
#球转动惯量
elif i == 2:
temp1 = pow(T[3][-1],2) * k / (4 * pow(pi,2))
temp2 = m[2] * pow(d[3],2) * pow(10,-9) / 10
#细杆转动惯量
else :
temp1 = pow(T[4][-1],2) * k / (4 * pow(pi,2))
temp2 = m[3] * pow(d[4],2) * pow(10,-9) / 12
I.append(temp1)
J.append(temp2)
delta.append(abs(J[i]-I[i]) * 100 / J[i]) #百分之多少
#验证平行轴定理
for a in T2:
a.append(sum(a)/len(a))
#线性回归计算
x, y, xy, x2, y2 = [], [], [], [], []
temp = 0
for i in range(5):
temp+=5
x.append(temp**2)
x2.append(x[i]**2)
y.append(pow(T2[i][-1]/5,2))
y2.append(y[i]**2)
xy.append(x[i] * y[i])
ave_x = sum(x) / len(x)
ave_y = sum(y) / len(y)
ave_x2 = sum(x2) / len(x2)
ave_y2 = sum(y2) / len(y2)
ave_xy = sum(xy) / len(xy)
b = (ave_x * ave_y - ave_xy) / (ave_x**2 - ave_x2) * pow(10,4)
a = ave_y - b*ave_x*pow(10,-4)
r = abs(ave_xy - ave_x*ave_y) / sqrt((ave_x2-ave_x**2) * (ave_y2-ave_y**2))
I1 = m[4] * (l[0]**2 + l[1]**2) * pow(10,-9) / 16 + m[4] * l[2]**2 * pow(10,-9)/12
I2 = m[5] * (l[0]**2 + l[1]**2) * pow(10,-9) / 16 + m[5] * l[2]**2 * pow(10,-9)/12
b1 = (m[4]+m[5]) * 4 * pi**2 / k / pow(10,3)
a1 = (J[3] + I1 + I2) * 4 * pi**2 / k
res = [r,b]
return env.from_string(source).render(
m=m,
d=d,
T=T,
K=k
)
def handler(XML):
file_object = open(texdir + "1010113.tex","r")
#将模板作为字符串存储在template文件中
source = file_object.read().decode('utf-8', 'ignore')
file_object.close()
m = [711.71, 697.76, 1242.40, 131.50, 239.84,239.57]
d = [99.95, 99.95, 93.85, 114.60, 610.00]
T = [[4.21, 4.21, 4.21],
[6.80, 6.80, 6.80],
[8.40, 8.39, 8.38],
[7.23, 7.23, 7.23],
[11.57, 11.60, 11.59]]
l = [34.92, 6.02, 33.05]
T2 = [[13.07,13.07,13.07,13.07,13.06],
[16.86,16.86,16.88,16.87,16.88],
[21.79,21.82,21.83,21.84,21.84],
[27.28,27.28,27.29,27.27,27.27],
[32.96,32.96,32.96,32.97,32.96]]
res = Inertia(m, d, T, l, T2)
return res
if __name__ == '__main__':
print handler('')
|
gpl-2.0
|
imshashank/The-Perfect-Self
|
wp-content/themes/Ines/groups/single/plugins.php
|
1217
|
<?php get_header( 'buddypress' ); ?>
<div id="content">
<div class="padder">
<?php if ( bp_has_groups() ) : while ( bp_groups() ) : bp_the_group(); ?>
<?php do_action( 'bp_before_group_plugin_template' ); ?>
<div id="item-header">
<?php locate_template( array( 'groups/single/group-header.php' ), true ); ?>
</div><!-- #item-header -->
<div id="item-nav">
<div class="item-list-tabs no-ajax" id="object-nav" role="navigation">
<ul>
<?php bp_get_options_nav(); ?>
<?php do_action( 'bp_group_plugin_options_nav' ); ?>
</ul>
</div>
</div><!-- #item-nav -->
<div id="item-body">
<?php do_action( 'bp_before_group_body' ); ?>
<?php do_action( 'bp_template_content' ); ?>
<?php do_action( 'bp_after_group_body' ); ?>
</div><!-- #item-body -->
<?php do_action( 'bp_after_group_plugin_template' ); ?>
<?php endwhile; endif; ?>
</div><!-- .padder -->
</div><!-- #content -->
<div id="navigation">
<?php _e('You are here', 'Detox') ?>: <?php if (function_exists('dimox_breadcrumbs')) dimox_breadcrumbs(); ?>
</div>
<?php get_sidebar( 'buddypress' ); ?>
<?php get_footer( 'buddypress' ); ?>
|
gpl-2.0
|
pisiganesh/my_pisi_files
|
Meld/actions.py
|
1046
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/copyleft/gpl.txt
from pisi.actionsapi import autotools
from pisi.actionsapi import get
#from pisi.actionsapi import pisitools
# if pisi can't find source directory, see /var/pisi/Meld/work/ and:
# WorkDir="Meld-"+ get.srcVERSION() +"/sub_project_dir/"
def build():
autotools.make()
def install():
autotools.rawInstall("DESTDIR=%s" % get.installDIR())
# Take a look at the source folder for these file as documentation.
# pisitools.dodoc("AUTHORS", "BUGS", "ChangeLog", "COPYING", "README")
# If there is no install rule for a runnable binary, you can
# install it to binary directory.
# pisitools.dobin("Meld")
# You can use these as variables, they will replace GUI values before build.
# Package Name : Meld
# Version : 1.8.2
# Summary : Meld is a visual diff and merge tool.
# For more information, you can look at the Actions API
# from the Help menu and toolbar.
# By PiSiDo 2.0.0
|
gpl-2.0
|
phpbbireland/portal
|
migrations/v10x/release_1_0_0.php
|
29812
|
<?php
/**
*
* Kiss Portal extension for the phpBB Forum Software package.
*
* @copyright (c) 2014 Michael OToole <http://www.phpbbireland.com>
* @license GNU General Public License, version 2 (GPL-2.0)
*
*/
namespace phpbbireland\portal\migrations\v10x;
class release_1_0_0 extends \phpbb\db\migration\migration
{
public function effectively_installed()
{
return isset($this->config['portal_mod_version']) && version_compare($this->config['portal_mod_version'], '1.0.0', '>=');
}
static public function depends_on()
{
return array('\phpbb\db\migration\data\v310\dev');
}
public function update_data()
{
return array(
array('config.add', array('portal_enabled', 1)),
array('config.add', array('blocks_enabled', 1)),
array('config.add', array('portal_version', '1.0.0')),
array('config.add', array('portal_build', '310-004')),
array('config.add', array('blocks_width', '190')),
array('permission.add', array('a_k_portal')),
array('permission.add', array('u_k_portal')),
// array('permission.role_add', array('Administer Portal', 'a_', 'portal')),
array('permission.permission_set', array('ROLE_ADMIN_FULL', 'a_k_portal')),
array('permission.permission_set', array('REGISTERED', 'u_k_portal', 'group')),
array('module.add', array(
'acp',
'',
'ACP_PORTAL_TITLE',
)),
array('module.add', array(
'acp',
'ACP_PORTAL_TITLE',
'ACP_CONFIG_TITLE',
)),
array('module.add', array(
'acp',
'ACP_PORTAL_TITLE',
'ACP_BLOCKS_TITLE',
)),
array('module.add', array(
'acp',
'ACP_PORTAL_TITLE',
'ACP_MENUS_TITLE',
)),
array('module.add', array(
'acp',
'ACP_PORTAL_TITLE',
'ACP_PAGES_TITLE',
)),
array('module.add', array(
'acp',
'ACP_PORTAL_TITLE',
'ACP_RESOURCES_TITLE',
)),
array('module.add', array(
'acp',
'ACP_PORTAL_TITLE',
'ACP_VARS_TITLE',
)),
array('module.add', array(
'acp',
'ACP_CONFIG_TITLE',
array(
'module_basename' => '\phpbbireland\portal\acp\config_module',
'modes' => array('config_portal'),
),
)),
array('module.add', array(
'acp',
'ACP_BLOCKS_TITLE',
array(
'module_basename' => '\phpbbireland\portal\acp\blocks_module',
'modes' => array('add', 'edit', 'delete', 'up', 'down', 'reindex', 'L', 'C', 'R', 'manage', 'reset'),
),
)),
array('module.add', array(
'acp',
'ACP_MENUS_TITLE',
array(
'module_basename' => '\phpbbireland\portal\acp\menus_module',
'modes' => array('add', 'nav', 'sub', 'link', 'edit', 'delete', 'up', 'down', 'all', 'unalloc'),
),
)),
array('module.add', array(
'acp',
'ACP_PAGES_TITLE',
array(
'module_basename' => '\phpbbireland\portal\acp\pages_module',
'modes' => array('add', 'delete', 'land', 'manage'),
),
)),
array('module.add', array(
'acp',
'ACP_RESOURCES_TITLE',
array(
'module_basename' => '\phpbbireland\portal\acp\resources_module',
'modes' => array('select'),
),
)),
array('module.add', array(
'acp',
'ACP_VARS_TITLE',
array(
'module_basename' => '\phpbbireland\portal\acp\vars_module',
'modes' => array('manage'),
),
)),
array('module.add', array(
'ucp',
'0',
'UCP_PORTAL_TITLE',
)),
array('module.add', array(
'ucp',
'UCP_PORTAL_TITLE',
array(
'module_basename' => '\phpbbireland\portal\ucp\portal_module',
'modes' => array('info', 'arrange', 'edit', 'delete', 'width'),
'module_auth' => 'acl_u_k_portal',
),
)),
array('config.add', array('portal_mod_version', '1.0.0')),
array('custom', array(array($this, 'seed_db'))),
);
}
public function update_schema()
{
return array(
'add_tables' => array(
$this->table_prefix . 'k_config' => array(
'COLUMNS' => array(
'config_name' => array('VCHAR', ''),
'config_value' => array('VCHAR', ''),
'is_dynamic' => array('BOOL', '0'),
),
'PRIMARY_KEY' => 'config_name',
'KEYS' => array('is_dynamic' => array('INDEX', 'is_dynamic'),
),
),
$this->table_prefix . 'k_vars' => array(
'COLUMNS' => array(
'config_name' => array('VCHAR', ''),
'config_value' => array('VCHAR', ''),
),
'PRIMARY_KEY' => 'config_name',
),
$this->table_prefix . 'k_blocks' => array(
'COLUMNS' => array(
'id' => array('UINT', null, 'auto_increment'),
'ndx' => array('UINT', '0'),
'title' => array('VCHAR:50', ''),
'position' => array('CHAR:1', 'L'),
'type' => array('CHAR:1', 'H'),
'active' => array('BOOL', '1'),
'html_file_name' => array('VCHAR', ''),
'var_file_name' => array('VCHAR', 'none.gif'),
'img_file_name' => array('VCHAR', 'none.gif'),
'view_all' => array('BOOL', '1'),
'view_groups' => array('VCHAR:100', ''),
'view_pages' => array('VCHAR:100', ''),
'groups' => array('UINT', '0'),
'scroll' => array('BOOL', '0'),
'block_height' => array('USINT', '0'),
'has_vars' => array('BOOL', '0'),
'is_static' => array('BOOL', '0'),
'minimod_based' => array('BOOL', '0'),
'mod_block_id' => array('UINT', '0'),
'block_cache_time' => array('UINT', '600'),
),
'PRIMARY_KEY' => 'id',
),
$this->table_prefix . 'k_menus' => array(
'COLUMNS' => array(
'm_id' => array('UINT', null, 'auto_increment'),
'ndx' => array('UINT', '0'),
'menu_type' => array('USINT', '0'),
'name' => array('VCHAR:50', ''),
'link_to' => array('VCHAR', ''),
'extern' => array('BOOL', '0'),
'menu_icon' => array('VCHAR:30', 'none.gif'),
'append_sid' => array('BOOL', '1'),
'append_uid' => array('BOOL', '0'),
'view_all' => array('BOOL', '1'),
'view_groups' => array('VCHAR:100', ''),
'soft_hr' => array('BOOL', '0'),
'sub_heading' => array('BOOL', '0'),
),
'PRIMARY_KEY' => 'm_id',
),
$this->table_prefix . 'k_pages' => array(
'COLUMNS' => array(
'page_id' => array('UINT', null, 'auto_increment'),
'page_name' => array('VCHAR_UNI:100', ''),
),
'PRIMARY_KEY' => 'page_id',
),
$this->table_prefix . 'k_resources' => array(
'COLUMNS' => array(
'id' => array('UINT', null, 'auto_increment'),
'word' => array('VCHAR:50', ''),
'type' => array('CHAR:1', 'V'),
),
'PRIMARY_KEY' => 'id',
),
),
'add_columns' => array(
$this->table_prefix . 'users' => array(
'user_left_blocks' => array('VCHAR:255', ''),
'user_center_blocks' => array('VCHAR:255', ''),
'user_right_blocks' => array('VCHAR:255', ''),
),
),
);
}
public function revert_schema()
{
return array(
'drop_tables' => array(
$this->table_prefix . 'k_config',
$this->table_prefix . 'k_blocks',
$this->table_prefix . 'k_menus',
$this->table_prefix . 'k_pages',
$this->table_prefix . 'k_resources',
$this->table_prefix . 'k_vars',
),
'drop_columns' => array(
$this->table_prefix . 'users' => array(
'user_left_blocks',
'user_center_blocks',
'user_right_blocks',
),
),
array('config.remove', array('portal_enabled')),
array('config.remove', array('blocks_enabled')),
array('config.remove', array('portal_version')),
array('config.remove', array('portal_build')),
array('config.remove', array('blocks_width')),
array('permission.remove', array('a_k_portal')),
array('permission.remove', array('u_k_portal')),
);
}
public function seed_db()
{
$blocks_sql = array(
array(
'ndx' => '1',
'title' => 'Site Navigator',
'position' => 'L',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_menus_nav.html',
'var_file_name' => '',
'img_file_name' => 'menu.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '1,2,3,4,5,6,7,8,9,11,12,13,14',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '0',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '600',
),
array(
'ndx' => '2',
'title' => 'Sub_Menu',
'position' => 'L',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_menus_sub.html',
'var_file_name' => '',
'img_file_name' => 'sub_menu.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '1,2,3,4,5,6,7,8,9,11,12,13,14',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '0',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '600',
),
array(
'ndx' => '3',
'title' => 'Links_Menu',
'position' => 'L',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_menus_links.html',
'var_file_name' => '',
'img_file_name' => 'sub_menu.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '1,2,3,4,5,6,7,8,9,11,12,13,14',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '0',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '600',
),
array(
'ndx' => '4',
'title' => 'Online Users',
'position' => 'L',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_online_users.html',
'var_file_name' => '',
'img_file_name' => 'online_users.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '1,2,3,4,5,6,7,8,9',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '0',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '600',
),
array(
'ndx' => '5',
'title' => 'Last Online',
'position' => 'L',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_last_online.html',
'var_file_name' => 'k_last_online_vars.html',
'img_file_name' => 'last_online.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '2,3,4,5,6,7,8,9',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '1',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '300',
),
array(
'ndx' => '6',
'title' => 'Search',
'position' => 'L',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_search.html',
'var_file_name' => '',
'img_file_name' => 'search.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '2,3,4,5,6,7,12',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '0',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '600',
),
array(
'ndx' => '7',
'title' => 'Categories',
'position' => 'L',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_forum_categories.html',
'var_file_name' => '',
'img_file_name' => 'categories.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '2',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '0',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '667',
),
array(
'ndx' => '2',
'title' => 'Welcome',
'position' => 'C',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_welcome.html',
'var_file_name' => 'k_welcome_vars.html',
'img_file_name' => 'welcome.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '2',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '1',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '999',
),
array(
'ndx' => '3',
'title' => 'Announcements',
'position' => 'C',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_announcements.html',
'var_file_name' => 'k_announce_vars.html',
'img_file_name' => 'announce.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '2',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '1',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '300',
),
array(
'ndx' => '4',
'title' => 'Recent Topics',
'position' => 'C',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_recent_topics_wide.html',
'var_file_name' => 'k_recent_topics_vars.html',
'img_file_name' => 'recent_topics.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '2',
'groups' => '0',
'scroll' => '0',
'block_height' => '200',
'has_vars' => '1',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '20',
),
array(
'ndx' => '5',
'title' => 'News Report',
'position' => 'C',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_news.html',
'var_file_name' => 'k_news_vars.html',
'img_file_name' => 'news.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '2',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '1',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '50',
),
array(
'ndx' => '1',
'title' => 'User Information',
'position' => 'R',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_user_information.html',
'var_file_name' => 'k_user_information_vars.html',
'img_file_name' => 'user.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '2,5,8,9',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '1',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '600',
),
array(
'ndx' => '2',
'title' => 'The Team',
'position' => 'R',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_the_teams.html',
'var_file_name' => 'k_the_teams_vars.html',
'img_file_name' => 'team.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '2,5,8,9',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '1',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '555',
),
array(
'ndx' => '3',
'title' => 'Top Posters',
'position' => 'R',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_top_posters.html',
'var_file_name' => 'k_top_posters_vars.html',
'img_file_name' => 'rating.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '2,5,8,9',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '1',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '200',
),
array(
'ndx' => '4',
'title' => 'Most Active Topics',
'position' => 'R',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_top_topics.html',
'var_file_name' => 'k_top_topics_vars.html',
'img_file_name' => 'most_active_topics.png',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '2',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '1',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '100',
),
array(
'ndx' => '5',
'title' => 'Clock',
'position' => 'R',
'type' => 'H',
'active' => '1',
'html_file_name'=> 'block_clock.html',
'var_file_name' => '',
'img_file_name' => 'clock.gif',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '2,12,13,14',
'groups' => '0',
'scroll' => '0',
'block_height' => '0',
'has_vars' => '0',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '6009',
),
array(
'ndx' => '6',
'title' => 'Links',
'position' => 'R',
'type' => 'H',
'active' => '0',
'html_file_name'=> 'block_links.html',
'var_file_name' => 'k_links_vars.html',
'img_file_name' => 'www.gif',
'view_all' => '1',
'view_groups' => '0',
'view_pages' => '2,5,8,9,12',
'groups' => '0',
'scroll' => '1',
'block_height' => '0',
'has_vars' => '1',
'minimod_based' => '0',
'mod_block_id' => '0',
'is_static' => '0',
'block_cache_time' => '668',
),
);
$this->db->sql_multi_insert($this->table_prefix . 'k_blocks', $blocks_sql);
$menus_sql = array(
array(
'ndx' => '1',
'menu_type' => '1',
'name' => 'Main Menu',
'link_to' => '',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'default.png',
'view_all' => '1',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '1',
),
array(
'ndx' => '2',
'menu_type' => '1',
'name' => 'Portal',
'link_to' => 'portal',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'portal.png',
'view_all' => '1',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '3',
'menu_type' => '1',
'name' => 'Forum',
'link_to' => 'index.php',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'home2.png',
'view_all' => '1',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '4',
'menu_type' => '1',
'name' => 'Navigator',
'link_to' => '',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'default.png',
'view_all' => '1',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '1',
),
array(
'ndx' => '5',
'menu_type' => '99',
'name' => 'Album',
'link_to' => 'inprogress.php',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'gallery.png',
'view_all' => '0',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '6',
'menu_type' => '1',
'name' => 'Bookmarks',
'link_to' => 'ucp.php?i=main&mode=bookmarks',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'bookmark.png',
'view_all' => '0',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '7',
'menu_type' => '99',
'name' => 'Downloads',
'link_to' => 'inprogress.php',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'ff.png',
'view_all' => '0',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '8',
'menu_type' => '99',
'name' => 'Links',
'link_to' => 'inprogress.php',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'link.gif',
'view_all' => '0',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '9',
'menu_type' => '1',
'name' => 'Members',
'link_to' => 'memberlist.php',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'chat.png',
'view_all' => '0',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '10',
'menu_type' => '99',
'name' => 'Ratings',
'link_to' => 'index.php',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'rating.png',
'view_all' => '0',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '11',
'menu_type' => '1',
'name' => 'Rules',
'link_to' => 'rules',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'rules.png',
'view_all' => '1',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '12',
'menu_type' => '1',
'name' => 'Staff',
'link_to' => 'memberlist.php?mode=leaders',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'staff.png',
'view_all' => '0',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '13',
'menu_type' => '99',
'name' => 'Statistics',
'link_to' => 'inprogress.php',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'pie.png',
'view_all' => '0',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '14',
'menu_type' => '1',
'name' => 'UCP',
'link_to' => 'ucp.php',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'links.gif',
'view_all' => '0',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '15',
'menu_type' => '99',
'name' => 'Chat',
'link_to' => 'chat/index.php',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'chat.png',
'view_all' => '0',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '16',
'menu_type' => '1',
'name' => 'Admin Menu',
'link_to' => '',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'default.png',
'view_all' => '0',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '1',
),
array(
'ndx' => '17',
'menu_type' => '1',
'name' => 'Admin CP',
'link_to' => 'adm/index.php',
'extern' => '0',
'append_sid' => '1',
'append_uid' => '0',
'menu_icon' => 'acp.png',
'view_all' => '0',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '1',
'menu_type' => '2',
'name' => 'Mini Menu',
'link_to' => '',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'default.png',
'view_all' => '1',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '1',
),
array(
'ndx' => '2',
'menu_type' => '2',
'name' => 'Active Posts',
'link_to' => 'search.php?search_id=active_topics',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'links.png',
'view_all' => '1',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '1',
'menu_type' => '5',
'name' => 'Lnks Menu',
'link_to' => '',
'extern' => '0',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'default.png',
'view_all' => '1',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '1',
),
array(
'ndx' => '2',
'menu_type' => '5',
'name' => 'Kiss Portal dev. site',
'link_to' => 'http://www.phpbbireland.com',
'extern' => '1',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'phpireland_globe.gif',
'view_all' => '1',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '3',
'menu_type' => '5',
'name' => 'Stargate Portal',
'link_to' => 'http://www.stargate-portal.com',
'extern' => '1',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'phpireland_globe.gif',
'view_all' => '1',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
array(
'ndx' => '4',
'menu_type' => '5',
'name' => 'phpBB3',
'link_to' => 'http://www.phpbb.com',
'extern' => '1',
'append_sid' => '0',
'append_uid' => '0',
'menu_icon' => 'phpireland_globe.gif',
'view_all' => '1',
'view_groups' => '',
'soft_hr' => '0',
'sub_heading' => '0',
),
);
$this->db->sql_multi_insert($this->table_prefix . 'k_menus', $menus_sql);
$resources_sql = array(
array(
'word' => 'phpBB',
'type' => 'R',
),
array(
'word' => '{PORTAL_VERSION}',
'type' => 'V',
),
array(
'word' => '{PORTAL_BUILD}',
'type' => 'V',
),
array(
'word' => '{VERSION}',
'type' => 'V',
),
array(
'word' => '{SITENAME}',
'type' => 'V',
),
);
$this->db->sql_multi_insert($this->table_prefix . 'k_resources', $resources_sql);
$pages_sql = array(
array(
'page_name' => 'index',
),
array(
'page_name' => 'portal',
),
array(
'page_name' => 'viewforum',
),
array(
'page_name' => 'viewtopic',
),
array(
'page_name' => 'memberlist',
),
array(
'page_name' => 'mcp',
),
array(
'page_name' => 'ucp',
),
array(
'page_name' => 'search',
),
array(
'page_name' => 'faq',
),
array(
'page_name' => 'posting',
),
);
$this->db->sql_multi_insert($this->table_prefix . 'k_pages', $pages_sql);
$vars_sql = array(
array(
'config_name' => 'k_announce_allow',
'config_value' => '1',
),
array(
'config_name' => 'k_allow_acronyms',
'config_value' => '1',
),
array(
'config_name' => 'k_bot_display_allow',
'config_value' => '1',
),
array(
'config_name' => 'k_footer_images_allow',
'config_value' => '1',
),
array(
'config_name' => 'k_news_allow',
'config_value' => '1',
),
array(
'config_name' => 'k_announce_type',
'config_value' => '0',
),
array(
'config_name' => 'k_blocks_display_globally',
'config_value' => '1',
),
array(
'config_name' => 'k_smilies_show',
'config_value' => '1',
),
array(
'config_name' => 'k_links_scroll_amount',
'config_value' => '0',
),
array(
'config_name' => 'k_links_scroll_direction',
'config_value' => '0',
),
array(
'config_name' => 'k_announce_item_max_length',
'config_value' => '400',
),
array(
'config_name' => 'k_news_item_max_length',
'config_value' => '350',
),
array(
'config_name' => 'k_last_online_max',
'config_value' => '10',
),
array(
'config_name' => 'k_news_type',
'config_value' => '0',
),
array(
'config_name' => 'k_announce_to_display',
'config_value' => '5',
),
array(
'config_name' => 'k_links_to_display',
'config_value' => '5',
),
array(
'config_name' => 'k_links_forum_id',
'config_value' => '',
),
array(
'config_name' => 'k_news_items_to_display',
'config_value' => '5',
),
array(
'config_name' => 'k_recent_topics_to_display',
'config_value' => '25',
),
array(
'config_name' => 'k_recent_topics_per_forum',
'config_value' => '5',
),
array(
'config_name' => 'k_top_posters_to_display',
'config_value' => '10',
),
array(
'config_name' => 'k_top_posters_show',
'config_value' => '1',
),
array(
'config_name' => 'k_recent_search_days',
'config_value' => '7',
),
array(
'config_name' => 'k_allow_rotating_logos',
'config_value' => '1',
),
array(
'config_name' => 'k_post_types',
'config_value' => '1',
),
array(
'config_name' => 'k_top_topics_max',
'config_value' => '5',
),
array(
'config_name' => 'k_adm_block',
'config_value' => '',
),
array(
'config_name' => 'k_quick_reply',
'config_value' => '1',
),
array(
'config_name' => 'k_recent_topics_search_exclude',
'config_value' => '',
),
array(
'config_name' => 'k_top_topics_days',
'config_value' => '7',
),
array(
'config_name' => 'k_block_cache_time_default',
'config_value' => '600',
),
array(
'config_name' => 'k_block_cache_time_short',
'config_value' => '10',
),
array(
'config_name' => 'k_teams',
'config_value' => '',
),
array(
'config_name' => 'k_teams_display_this_many',
'config_value' => '2',
),
array(
'config_name' => 'k_max_block_avatar_width',
'config_value' => '80',
),
array(
'config_name' => 'k_max_block_avatar_height',
'config_value' => '80',
),
array(
'config_name' => 'k_teampage_memberships',
'config_value' => '0',
),
array(
'config_name' => 'k_tooltips_active',
'config_value' => '1',
),
array(
'config_name' => 'k_tooltips_which',
'config_value' => '1',
),
array(
'config_name' => 'k_landing_page',
'config_value' => 'portal',
),
array(
'config_name' => 'k_mod_folders',
'config_value' => '',
),
array(
'config_name' => 'k_teams_sort',
'config_value' => 'default',
),
);
$this->db->sql_multi_insert($this->table_prefix . 'k_vars', $vars_sql);
}
}
|
gpl-2.0
|
gbentley/ezpublish-kernel
|
eZ/Publish/Core/REST/Server/Input/Parser/Criterion/ContentId.php
|
1367
|
<?php
/**
* File containing the ContentIdCriterion parser class
*
* @copyright Copyright (C) 1999-2013 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\REST\Server\Input\Parser\Criterion;
use eZ\Publish\Core\REST\Server\Input\Parser\Base;
use eZ\Publish\Core\REST\Common\Input\ParsingDispatcher;
use eZ\Publish\Core\REST\Common\RequestParser;
use eZ\Publish\Core\REST\Common\Exceptions;
use eZ\Publish\API\Repository\Values\Content\Query\Criterion\ContentId as ContentIdCriterion;
/**
* Parser for ViewInput
*/
class ContentId extends Base
{
/**
* Parses input structure to a Criterion object
*
* @param array $data
* @param \eZ\Publish\Core\REST\Common\Input\ParsingDispatcher $parsingDispatcher
*
* @throws \eZ\Publish\Core\REST\Common\Exceptions\Parser
*
* @return \eZ\Publish\API\Repository\Values\Content\Query\Criterion\ContentId
*/
public function parse( array $data, ParsingDispatcher $parsingDispatcher )
{
if ( !array_key_exists( "ContentIdCriterion", $data ) )
{
throw new Exceptions\Parser( "Invalid <ContentIdCriterion> format" );
}
return new ContentIdCriterion( explode( ',', $data["ContentIdCriterion"] ) );
}
}
|
gpl-2.0
|
kutschkem/QGen
|
src/test/java/com/github/kutschkem/Qgen/test/QuestionExtractorTest.java
|
502
|
package com.github.kutschkem.Qgen.test;
import java.io.IOException;
import org.apache.uima.UIMAException;
import org.junit.Test;
import com.github.kutschkem.Qgen.QuestionExtractor;
public class QuestionExtractorTest {
@Test
public void testSingularForm() throws UIMAException, IOException{
// tests a bug that occurred in the sentence "You went to school."
String text = "You went to school.";
QuestionExtractor ex = new QuestionExtractor();
ex.extract(text);
}
}
|
gpl-2.0
|
paco30amigos/sieni
|
SIENI/SIENI-model/src/main/java/sv/com/mined/sieni/model/SieniDocentRol.java
|
5620
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sv.com.mined.sieni.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.PrePersist;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Laptop
*/
@Entity
@Table(name = "sieni_docent_rol")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "SieniDocentRol.findAllNoInactivos", query = "SELECT s FROM SieniDocentRol s where s.sdrEstado not in (:estado) order by s.idDocenteRol"),
@NamedQuery(name = "SieniDocentRol.findAdmins", query = "SELECT s FROM SieniDocentRol s where s.fRolDoc=:rol and s.sdrEstado=:estado"),
@NamedQuery(name = "SieniDocentRol.findAll", query = "SELECT s FROM SieniDocentRol s"),
@NamedQuery(name = "SieniDocentRol.findRoles", query = "SELECT s FROM SieniDocentRol s where s.idDocente=:idDocente and s.sdrEstado not in (:estado)"),
@NamedQuery(name = "SieniDocentRol.findByIdDocenteRol", query = "SELECT s FROM SieniDocentRol s WHERE s.idDocenteRol = :idDocenteRol"),
@NamedQuery(name = "SieniDocentRol.findByFRolDoc", query = "SELECT s FROM SieniDocentRol s WHERE s.fRolDoc = :fRolDoc"),
@NamedQuery(name = "SieniDocentRol.findByEstado", query = "SELECT s FROM SieniDocentRol s WHERE s.sdrEstado = :sdrEstado"),
@NamedQuery(name = "SieniDocentRol.findByFIngreso", query = "SELECT s FROM SieniDocentRol s, SieniDocente d WHERE s.idDocente = :idDocente AND d.idDocente=s.idDocente")})
public class SieniDocentRol implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@GeneratedValue(strategy = GenerationType.AUTO, generator = "sec_sieni_docent_rol")
@SequenceGenerator(name = "sec_sieni_docent_rol", initialValue = 1, allocationSize = 1, sequenceName = "sec_sieni_docent_rol")
@Column(name = "id_docente_rol")
private Long idDocenteRol;
@Basic(optional = false)
@Column(name = "f_rol_doc")
private long fRolDoc;
@Column(name = "sdr_estado")
private Character sdrEstado;
@Column(name = "sdr_fecha_ingreso", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date sdrFechaIngreso;
// @PrePersist
// protected void onCreate() {
// sdrFechaIngreso = new Date();
// }
// @JoinColumn(name = "id_docente", referencedColumnName = "id_docente")
// @ManyToOne
// private SieniDocente idDocente;
@Column(name = "id_docente")
private Long idDocente;
@Transient
private SieniDocente docente;
public SieniDocentRol() {
}
public SieniDocentRol(Long idDocenteRol) {
this.idDocenteRol = idDocenteRol;
}
public SieniDocentRol(Long idDocenteRol, long fRolDoc) {
this.idDocenteRol = idDocenteRol;
this.fRolDoc = fRolDoc;
}
public Long getIdDocenteRol() {
return idDocenteRol;
}
public void setIdDocenteRol(Long idDocenteRol) {
this.idDocenteRol = idDocenteRol;
}
public long getFRolDoc() {
return fRolDoc;
}
public void setFRolDoc(long fRolDoc) {
this.fRolDoc = fRolDoc;
}
// public SieniDocente getIdDocente() {
// return idDocente;
// }
//
// public void setIdDocente(SieniDocente idDocente) {
// this.idDocente = idDocente;
// }
@Override
public int hashCode() {
int hash = 0;
hash += (idDocenteRol != null ? idDocenteRol.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof SieniDocentRol)) {
return false;
}
SieniDocentRol other = (SieniDocentRol) object;
if ((this.idDocenteRol == null && other.idDocenteRol != null) || (this.idDocenteRol != null && !this.idDocenteRol.equals(other.idDocenteRol))) {
return false;
}
return true;
}
@Override
public String toString() {
return "sv.com.mined.sieni.model.SieniDocentRol[ idDocenteRol=" + idDocenteRol + " ]";
}
public Character getSdrEstado() {
return sdrEstado;
}
public void setSdrEstado(Character sdrEstado) {
this.sdrEstado = sdrEstado;
}
public Long getIdDocente() {
return idDocente;
}
public void setIdDocente(Long idDocente) {
this.idDocente = idDocente;
}
public SieniDocente getDocente() {
return docente;
}
public void setDocente(SieniDocente docente) {
this.docente = docente;
}
public Date getSdrFechaIngreso() {
return sdrFechaIngreso;
}
public void setSdrFechaIngreso(Date sdrFechaIngreso) {
this.sdrFechaIngreso = sdrFechaIngreso;
}
}
|
gpl-2.0
|
foxbei/joomla16
|
templates/yoo_pure/html/com_users/login/default_login.php
|
492
|
<?php
/**
* @package yoo_pure Template
* @file default_login.php
* @version 5.5.0 January 2011
* @author YOOtheme http://www.yootheme.com
* @copyright Copyright (C) 2007 - 2011 YOOtheme GmbH
* @license YOOtheme Proprietary Use License (http://www.yootheme.com/license)
*/
// include config and layout
$base = dirname(dirname(dirname(__FILE__)));
include($base.'/config.php');
include($warp->path->path('layouts:'.preg_replace('/'.preg_quote($base, '/').'/', '', __FILE__, 1)));
|
gpl-2.0
|
mitrobkat/wordpress
|
themes/heifer/footer.php
|
2848
|
<?php
/**
* The template for displaying the footer.
*
* Contains the closing of the id=main div and all content after
*
* @package WordPress
* @subpackage Heifer
* @since Heifer 1.0
*/
?>
</div>
</div>
<!-- #main -->
<footer id="footer" role="contentinfo">
<?php
/* A sidebar in the footer? Yep. You can can customize
* your footer with three columns of widgets.
*/
if ( ! is_404() )
get_sidebar( 'footer' );
?>
<div id="site-generator" style="display:none;">
<?php do_action( 'heifer_credits' ); ?>
<a href="<?php echo esc_url( __( 'http://wordpress.org/', 'heifer' ) ); ?>" title="<?php esc_attr_e( 'Semantic Personal Publishing Platform', 'heifer' ); ?>" rel="generator"><?php printf( __( 'Proudly powered by %s', 'heifer' ), 'WordPress' ); ?></a>
</div>
<?php
/*********************************************************
* Retrieve the "Drupal" / "www.heifer.org" FOOTER
*********************************************************/
//$db ='heifer_dev';
$db = 'heifer';
$user = 'heifer_admin';
$pass = 'uQu6Eexo';
//$host = '192.168.110.133'; // LIVE
$host = 'db1';
//$host = 'localhost'; // local
$nav_query = 'SELECT `body` FROM block_custom WHERE `bid` = 3';
$drupal_wpdb = new wpdb($user, $pass, $db, $host);
$results = $drupal_wpdb->get_row($nav_query, OBJECT);
$contents = $results->body;
$string = str_replace(array("\r\n","\t","\r","\n"),array("","","",""),$contents);
//remove the form tags from the markup.
$string = preg_replace('/{{(.*?)}}/', '', $string);
//preg_match_all('/<div id="footerContainer"><div id="footer">(.*?)<\/div><\/div>/',$contents,$matches);
//preg_match_all('/<div class="logos">(.*?)<\/div>/',$contents,$m2);
//$SITE_URL = get_site_url();
$SITE_URL = 'http://www.heifer.org';
$nMarkup = preg_replace('/href="(?!(http|https))(.*?)"/','href="'.$SITE_URL.'$2"',$string);
$nMarkup = preg_replace('/src=("|\')(?!(http|https))(.*?)?(.*?)("|\')/','src=$1$4$5',$nMarkup);
$nMarkup2 = preg_replace('/src="(?!(http|https))(.*?)"/','src="$2"',$m2[0][0]);
//echo $nMarkup.'</div></div>'.$nMarkup2.'</div>';
echo $nMarkup;
?>
</footer><!-- #colophon -->
</div><!-- #page -->
<?php wp_footer(); ?>
<!-- TRACKING PIXELS {section added 5/4/2012 MRK } -->
<iframe src='http://pixel.fetchback.com/serve/fb/pdj?cat=&name=landing&sid=1540' scrolling='no' width='1' height='1' marginheight='0' marginwidth='0' frameborder='0'></iframe>
<!-- added 5/4/2012 mrk - Audience Science pixel -->
<script type="text/javascript" src="http://js.revsci.net/gateway/gw.js?csid=G11201&auto=t"></script>
<!-- EDN TRACKING PIXELS -->
</body>
</html>
|
gpl-2.0
|
iNecas/katello
|
cli/src/katello/client/api/user.py
|
3625
|
# -*- coding: utf-8 -*-
#
# Copyright © 2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
from katello.client.api.base import KatelloAPI
from katello.client.utils.encoding import u_str
from katello.client.core.utils import update_dict_unless_none
class UserAPI(KatelloAPI):
"""
Connection class to access User Data
"""
def create(self, name, pw, email, disabled, default_environment, default_locale=None):
userdata = {"username": name,
"password": pw,
"email": email,
"disabled": disabled}
if default_locale is not None:
userdata["default_locale"] = default_locale
if default_environment is not None:
userdata.update(default_environment_id=default_environment['id'])
path = "/api/users/"
return self.server.POST(path, userdata)[1]
def delete(self, user_id):
path = "/api/users/%s" % u_str(user_id)
return self.server.DELETE(path)[1]
def update(self, user_id, pw, email, disabled, default_environment, default_locale=None):
userdata = {}
userdata = update_dict_unless_none(userdata, "password", pw)
userdata = update_dict_unless_none(userdata, "email", email)
userdata = update_dict_unless_none(userdata, "disabled", disabled)
if default_environment is None:
userdata.update(default_environment_id=None) # pylint: disable=E1101
elif default_environment is not False:
userdata.update(default_environment_id=default_environment['id']) # pylint: disable=E1101
if default_locale is not None:
userdata = update_dict_unless_none(userdata, "default_locale", default_locale)
path = "/api/users/%s" % u_str(user_id)
return self.server.PUT(path, {"user": userdata})[1]
def users(self, query=None):
path = "/api/users/"
users = self.server.GET(path, query)[1]
return users
def user(self, user_id):
path = "/api/users/%s" % u_str(user_id)
user = self.server.GET(path)[1]
return user
def user_by_name(self, user_name):
users = self.users({"username": user_name})
if len(users) >= 1:
return users[0]
else:
return None
def sync_ldap_roles(self):
path = "/api/users/sync_ldap_roles/"
return self.server.GET(path)[1]
def assign_role(self, user_id, role_id):
path = "/api/users/%s/roles" % u_str(user_id)
data = {"role_id": role_id}
return self.server.POST(path, data)[1]
def unassign_role(self, user_id, role_id):
path = "/api/users/%s/roles/%s" % (u_str(user_id), u_str(role_id))
return self.server.DELETE(path)[1]
def roles(self, user_id):
path = "/api/users/%s/roles/" % u_str(user_id)
return self.server.GET(path)[1]
def report(self, format_in):
to_return = self.server.GET("/api/users/report", custom_headers={"Accept": format_in})
return (to_return[1], to_return[2])
|
gpl-2.0
|
cfloersch/keytool
|
src/main/java/xpertss/crypto/x509/SubjectInfoAccessExtension.java
|
7067
|
package xpertss.crypto.x509;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import xpertss.crypto.util.DerOutputStream;
import xpertss.crypto.util.DerValue;
/**
* The Subject Information Access Extension (OID = 1.3.6.1.5.5.7.1.11).
* <p/>
* The subject information access extension indicates how to access
* information and services for the subject of the certificate in which
* the extension appears. When the subject is a CA, information and
* services may include certificate validation services and CA policy
* data. When the subject is an end entity, the information describes
* the type of services offered and how to access them. In this case,
* the contents of this extension are defined in the protocol
* specifications for the supported services. This extension may be
* included in end entity or CA certificates. Conforming CAs MUST mark
* this extension as non-critical.
* <p/>
* This extension is defined in <a href="http://www.ietf.org/rfc/rfc3280.txt">
* Internet X.509 PKI Certificate and Certificate Revocation List
* (CRL) Profile</a>. The profile permits
* the extension to be included in end-entity or CA certificates,
* and it must be marked as non-critical. Its ASN.1 definition is as follows:
* <pre>
* id-pe-subjectInfoAccess OBJECT IDENTIFIER ::= { id-pe 11 }
*
* SubjectInfoAccessSyntax ::=
* SEQUENCE SIZE (1..MAX) OF AccessDescription
*
* AccessDescription ::= SEQUENCE {
* accessMethod OBJECT IDENTIFIER,
* accessLocation GeneralName }
* </pre>
* <p/>
*
* @see Extension
* @see CertAttrSet
*/
public class SubjectInfoAccessExtension extends Extension implements CertAttrSet<String> {
/**
* Identifier for this attribute, to be used with the
* get, set, delete methods of Certificate, x509 type.
*/
public static final String IDENT = "x509.info.extensions.SubjectInfoAccess";
/**
* Attribute name.
*/
public static final String NAME = "SubjectInfoAccess";
public static final String DESCRIPTIONS = "descriptions";
/**
* The List of AccessDescription objects.
*/
private List<AccessDescription> accessDescriptions;
/**
* Create an SubjectInfoAccessExtension from a List of
* AccessDescription; the criticality is set to false.
*
* @param accessDescriptions the List of AccessDescription
* @throws IOException on error
*/
public SubjectInfoAccessExtension(
List<AccessDescription> accessDescriptions) throws IOException
{
this.extensionId = PKIXExtensions.SubjectInfoAccess_Id;
this.critical = false;
this.accessDescriptions = accessDescriptions;
encodeThis();
}
/**
* Create the extension from the passed DER encoded value of the same.
*
* @param critical true if the extension is to be treated as critical.
* @param value Array of DER encoded bytes of the actual value.
* @throws IOException on error.
*/
public SubjectInfoAccessExtension(Boolean critical, Object value)
throws IOException
{
this.extensionId = PKIXExtensions.SubjectInfoAccess_Id;
this.critical = critical.booleanValue();
if (!(value instanceof byte[])) {
throw new IOException("Illegal argument type");
}
extensionValue = (byte[]) value;
DerValue val = new DerValue(extensionValue);
if (val.tag != DerValue.tag_Sequence) {
throw new IOException("Invalid encoding for " +
"SubjectInfoAccessExtension.");
}
accessDescriptions = new ArrayList<AccessDescription>();
while (val.data.available() != 0) {
DerValue seq = val.data.getDerValue();
AccessDescription accessDescription = new AccessDescription(seq);
accessDescriptions.add(accessDescription);
}
}
/**
* Return the list of AccessDescription objects.
*/
public List<AccessDescription> getAccessDescriptions()
{
return accessDescriptions;
}
/**
* Return the name of this attribute.
*/
public String getName()
{
return NAME;
}
/**
* Write the extension to the DerOutputStream.
*
* @param out the DerOutputStream to write the extension to.
* @throws IOException on encoding errors.
*/
public void encode(OutputStream out) throws IOException
{
DerOutputStream tmp = new DerOutputStream();
if (this.extensionValue == null) {
this.extensionId = PKIXExtensions.SubjectInfoAccess_Id;
this.critical = false;
encodeThis();
}
super.encode(tmp);
out.write(tmp.toByteArray());
}
/**
* Set the attribute value.
*/
public void set(String name, Object obj) throws IOException
{
if (name.equalsIgnoreCase(DESCRIPTIONS)) {
if (!(obj instanceof List)) {
throw new IOException("Attribute value should be of type List.");
}
accessDescriptions = (List<AccessDescription>) obj;
} else {
throw new IOException("Attribute name [" + name +
"] not recognized by " +
"CertAttrSet:SubjectInfoAccessExtension.");
}
encodeThis();
}
/**
* Get the attribute value.
*/
public Object get(String name) throws IOException
{
if (name.equalsIgnoreCase(DESCRIPTIONS)) {
return accessDescriptions;
} else {
throw new IOException("Attribute name [" + name +
"] not recognized by " +
"CertAttrSet:SubjectInfoAccessExtension.");
}
}
/**
* Delete the attribute value.
*/
public void delete(String name) throws IOException
{
if (name.equalsIgnoreCase(DESCRIPTIONS)) {
accessDescriptions = new ArrayList<AccessDescription>();
} else {
throw new IOException("Attribute name [" + name +
"] not recognized by " +
"CertAttrSet:SubjectInfoAccessExtension.");
}
encodeThis();
}
/**
* Return an enumeration of names of attributes existing within this
* attribute.
*/
public Enumeration<String> getElements()
{
AttributeNameEnumeration elements = new AttributeNameEnumeration();
elements.add(DESCRIPTIONS);
return Collections.enumeration(elements);
}
// Encode this extension value
private void encodeThis() throws IOException
{
if (accessDescriptions.isEmpty()) {
this.extensionValue = null;
} else {
DerOutputStream ads = new DerOutputStream();
for (AccessDescription accessDescription : accessDescriptions) {
accessDescription.encode(ads);
}
DerOutputStream seq = new DerOutputStream();
seq.write(DerValue.tag_Sequence, ads);
this.extensionValue = seq.toByteArray();
}
}
/**
* Return the extension as user readable string.
*/
public String toString()
{
return super.toString() + "SubjectInfoAccess [\n "
+ accessDescriptions + "\n]\n";
}
}
|
gpl-2.0
|
sugang/coolmap
|
src/coolmap/canvas/sidemaps/impl/ColumnLabels.java
|
30556
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package coolmap.canvas.sidemaps.impl;
import com.google.common.collect.Range;
import coolmap.application.CoolMapMaster;
import coolmap.application.state.StateStorageMaster;
import coolmap.canvas.CoolMapView;
import coolmap.canvas.misc.MatrixCell;
import coolmap.canvas.misc.ZoomControl;
import coolmap.canvas.sidemaps.ColumnMap;
import coolmap.data.CoolMapObject;
import coolmap.data.cmatrixview.model.VNode;
import coolmap.data.contology.model.COntology;
import coolmap.data.state.CoolMapState;
import coolmap.utils.graphics.CAnimator;
import coolmap.utils.graphics.UI;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import org.jdesktop.core.animation.timing.Animator;
import org.jdesktop.core.animation.timing.TimingTarget;
/**
*
* @author gangsu
*/
public class ColumnLabels extends ColumnMap<Object, Object> implements MouseListener, MouseMotionListener {
private ZoomControl _zoomControlX;
private int _fontSize = 0;
private int _maxDescent = 0;
private int _liftSize = 16;
private Rectangle _activeRectangle = new Rectangle();
private final JPopupMenu _menu = new JPopupMenu();
private final JMenuItem _sortAscending;
private final JMenuItem _sortDescending, _removeSelected;
@Override
public String getName() {
return "Column Labels";
}
public ColumnLabels(CoolMapObject object) {
super(object);
getViewPanel().setName(getName());
getViewPanel().addMouseListener(this);
getViewPanel().addMouseMotionListener(this);
_sortAscending = new JMenuItem("Sort ascending", UI.getImageIcon("upThin"));
_sortDescending = new JMenuItem("Sort dscending", UI.getImageIcon("downThin"));
_zoomControlX = getCoolMapView().getZoomControlX();
_sortAscending.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (isDataViewValid()) {
getCoolMapObject().sortColumn(getCoolMapView().getActiveCell().getCol(), false);
}
}
});
_sortDescending.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (isDataViewValid()) {
getCoolMapObject().sortColumn(getCoolMapView().getActiveCell().getCol(), true);
}
}
});
_menu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent pme) {
boolean matrixValid = _validateActions();
if (matrixValid && Comparable.class.isAssignableFrom(getCoolMapView().getCoolMapObject().getViewClass())) {
_sortAscending.setEnabled(true);
_sortDescending.setEnabled(true);
} else {
_sortAscending.setEnabled(false);
_sortDescending.setEnabled(false);
}
if (isDataViewValid()) {
ArrayList<Range<Integer>> selColumns = getCoolMapView().getSelectedColumns();
if (selColumns == null || selColumns.isEmpty()) {
_removeSelected.setEnabled(false);
} else {
_removeSelected.setEnabled(true);
}
}
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent pme) {
}
@Override
public void popupMenuCanceled(PopupMenuEvent pme) {
}
});
getViewPanel().setComponentPopupMenu(_menu);
_menu.add(_sortAscending);
_menu.add(_sortDescending);
_menu.addSeparator();
_removeSelected = new JMenuItem("Remove selected columns (w/o expanded nodes)", UI.getImageIcon("trashBin"));
_removeSelected.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
if (isDataViewValid()) {
CoolMapObject obj = getCoolMapObject();
ArrayList<Range<Integer>> selColumns = getCoolMapView().getSelectedColumns();
ArrayList<VNode> nodesToBeRemoved = new ArrayList<VNode>();
for (Range<Integer> selections : selColumns) {
for (int i = selections.lowerEndpoint(); i < selections.upperEndpoint(); i++) {
VNode node = obj.getViewNodeColumn(i);
nodesToBeRemoved.add(node);
}
}//end iteration
try {
CoolMapState state = CoolMapState.createStateColumns("Remove columns", obj, null);
obj.removeViewNodesColumn(nodesToBeRemoved);
StateStorageMaster.addState(state);
} catch (Exception e) {
System.err.println("Error removing columns");
}
}
}
});
_menu.add(_removeSelected);
}
private boolean _validateActions() {
CoolMapView view = getCoolMapView();
if (view == null) {
return false;
}
CoolMapObject object = view.getCoolMapObject();
if (object == null) {
return false;
}
if (object.getViewClass() == null || !Comparable.class.isAssignableFrom(object.getViewClass())) {
return false;
}
return view.getActiveCell().isColValidCell(object);
}
@Override
protected void renderColumn(Graphics2D g2D, CoolMapObject<Object, Object> object, VNode node, int anchorX, int anchorY, int cellWidth, int cellHeight) {
if (node == null || getCoolMapView() == null) {
return;
}
String label = node.getViewLabel();
if (label != null) {
//System.out.println("Rendered label" + label);
//Sometimes the label is drawn, but not shown.
//System.out.println(label + " " + anchorX + " " + anchorY);
g2D.setColor(UI.colorBlack3);
g2D.drawString(label, anchorX + cellWidth - _maxDescent - (cellWidth - _fontSize) / 2 - 1, anchorY + cellHeight - _liftSize);
}
if (node.isGroupNode()) {
Color color;
if (node.getViewColor() == null) {
COntology onto = CoolMapMaster.getCOntologyByID(node.getCOntologyID());
if (onto != null) {
color = onto.getViewColor();
} else {
color = null;
}
} else {
color = node.getViewColor();
}
if (cellWidth > 6) {
g2D.setColor(color);
g2D.fillRoundRect(anchorX + 1, anchorY + cellHeight - 5, cellWidth - 2, 10, 4, 4);
} else {
g2D.setColor(color);
g2D.fillRect(anchorX, anchorY + cellHeight - 5, cellWidth, 10);
}
}
}
@Override
public void prePaint(Graphics2D g2D, CoolMapObject<Object, Object> object, int width, int height) {
//paint selected columns
CoolMapObject obj = getCoolMapObject();
CoolMapView canvas = getCoolMapView();
if (canvas != null && obj != null) {
ArrayList<Range<Integer>> selectedColumns = canvas.getSelectedColumns();
if (selectedColumns != null && !selectedColumns.isEmpty()) {
for (Range<Integer> range : selectedColumns) {
int start = range.lowerEndpoint();
int end = range.upperEndpoint() - 1;
VNode startNode = obj.getViewNodeColumn(start);
VNode endNode = obj.getViewNodeColumn(end);
if (startNode != null && endNode != null && startNode.getViewOffset() != null && endNode.getViewOffset() != null) {
int x = (int) (canvas.getMapAnchor().x + startNode.getViewOffset());
int y = 0;
int selectionWidth = (int) (endNode.getViewOffset(canvas.getZoomX()) - startNode.getViewOffset());
int selectionHeight = height;
g2D.setColor(UI.colorLightBlue0);
g2D.fillRect(x, y, selectionWidth, selectionHeight);
}
}
}
}
if (isEnabled() && canvas != null) {
if (canvas.getActiveCell().isColValidCell(canvas.getCoolMapObject())) {
_activeRectangle.height = height;
g2D.setColor(UI.colorLightGreen5);
g2D.fillRect(_activeRectangle.x, _activeRectangle.y, _activeRectangle.width, _activeRectangle.height);
}
}
}
private final HoverTarget _hoverTarget = new HoverTarget();
private final Animator _hoverAnimator = CAnimator.createInstance(_hoverTarget, 150);
@Override
public void aggregatorUpdated(CoolMapObject object) {
}
@Override
public void rowsChanged(CoolMapObject object) {
}
@Override
public void columnsChanged(CoolMapObject object) {
}
@Override
public void coolMapObjectBaseMatrixChanged(CoolMapObject object) {
}
@Override
public void mapAnchorMoved(CoolMapObject object) {
//System.out.println("anchor changed");
}
@Override
public void mapZoomChanged(CoolMapObject object) {
}
// @Override
// public void stateStorageUpdated(CoolMapObject object) {
// }
// @Override
// public void subSelectionRowChanged(CoolMapObject object) {
// }
// @Override
// public void subSelectionColumnChanged(CoolMapObject object) {
// System.out.println(object.getCoolMapView().getSubSelectedColumns());
// }
@Override
public void viewRendererChanged(CoolMapObject object) {
}
@Override
public void viewFilterChanged(CoolMapObject object) {
}
@Override
public void gridChanged(CoolMapObject object) {
}
@Override
public void nameChanged(CoolMapObject object) {
}
private class HoverTarget implements TimingTarget {
private final Rectangle _beginRect = new Rectangle();
private final Rectangle _endRect = new Rectangle();
public void setBeginEnd(MatrixCell oldCell, MatrixCell newCell) {
//System.out.println(oldCell + " " + newCell);
CoolMapView view = getCoolMapView();
if (view == null) { // || oldCell == null || oldCell.getCol() == null || newCell == null || newCell.getCol() == null) {
return;
}
if (oldCell == null || newCell == null) {
return;
}
if (newCell.col == null) {
return;
}
if (oldCell.col == null && newCell.col != null) {
oldCell.col = newCell.col;
}
VNode oldNode = getCoolMapView().getCoolMapObject().getViewNodeColumn(oldCell.getCol());
VNode newNode = getCoolMapView().getCoolMapObject().getViewNodeColumn(newCell.getCol());
if (oldNode == null || oldNode.getViewOffset() == null || newNode == null || newNode.getViewOffset() == null) {
return;
}
_beginRect.x = (int) (getCoolMapView().getMapAnchor().x + oldNode.getViewOffset());
_beginRect.y = 0;
_beginRect.width = (int) oldNode.getViewSizeInMap(view.getZoomX());
_endRect.x = (int) (getCoolMapView().getMapAnchor().x + newNode.getViewOffset());
_endRect.y = 0;
_endRect.width = (int) newNode.getViewSizeInMap(view.getZoomX());
getViewPanel().repaint();
}
@Override
public void begin(Animator source) {
}
@Override
public void end(Animator source) {
}
@Override
public void repeat(Animator source) {
}
@Override
public void reverse(Animator source) {
}
@Override
public void timingEvent(Animator source, double fraction) {
_activeRectangle.x = (int) (_beginRect.x + (_endRect.x - _beginRect.x) * fraction);
_activeRectangle.y = 0;
_activeRectangle.width = (int) (_beginRect.width + (_endRect.width - _beginRect.width) * fraction);
getViewPanel().repaint();
}
}
@Override
public void postPaint(Graphics2D g2D, CoolMapObject<Object, Object> obj, int width, int height) {
if (_dragStart) {
g2D.setColor(UI.colorGrey6);
g2D.setStroke(UI.strokeDash2);
g2D.fillOval(_dragStartPoint.x - 3, _dragStartPoint.y - 3, 6, 6);
CoolMapView view = getCoolMapView();
int targetX;
if (isDataViewValid() && _targetCol != null) {
if (_targetCol < 0) {
_targetCol = 0;
}
VNode node = view.getCoolMapObject().getViewNodeColumn(_targetCol);
if (node != null && node.getViewOffset() != null) {
targetX = (int) (view.getMapAnchor().x + node.getViewOffset());
g2D.drawLine(targetX, 0, targetX, height);
g2D.drawLine(_dragStartPoint.x, _dragStartPoint.y, targetX, _dragEndPoint.y);
g2D.drawImage(UI.getImageIcon("insertColumn").getImage(), _dragEndPoint.x - 18, _dragEndPoint.y - 18, null);
} else if (_targetCol == view.getCoolMapObject().getViewNumColumns()) {
node = view.getCoolMapObject().getViewNodeColumn(_targetCol - 1);
if (node != null) {
targetX = (int) (view.getMapAnchor().x + node.getViewOffset(view.getZoomX()));
g2D.drawLine(targetX, 0, targetX, height);
g2D.drawLine(_dragStartPoint.x, _dragStartPoint.y, targetX, _dragEndPoint.y);
g2D.drawImage(UI.getImageIcon("insertColumn").getImage(), _dragStartPoint.x - 8, _dragStartPoint.y - 8, null);
}
}
//draw a marker for ontology
//draw a marker for sorter
}
}
if (isDataViewValid()) {
obj = getCoolMapObject();
VNode lastSortedColumn = obj.getSortTracker().lastSortedColumn;
boolean lastSortedColumnDescending = obj.getSortTracker().lastSortedColumnDescending;
if (lastSortedColumn == null || lastSortedColumn.getViewOffset() == null) {
return;
}
Point anchor = getCoolMapView().getMapAnchor();
int x = (int) (anchor.x + lastSortedColumn.getViewOffset());
int cellWidth = (int) lastSortedColumn.getViewSizeInMap(getCoolMapView().getZoomX());
g2D.setStroke(UI.stroke4);
//Don't dispose
g2D = (Graphics2D) g2D.create(x, 0, cellWidth, height);
//g2D.setClip(x, 0, cellWidth, height);
if (!lastSortedColumnDescending) {
// g2D.drawLine(x, height-8, x + cellWidth / 2, height-12);
// g2D.drawLine(x + cellWidth / 2, height-12, x + cellWidth, height-8);
g2D.setColor(UI.colorDarkGreen1);
g2D.drawLine(0, height - 8, cellWidth / 2, height - 12);
g2D.drawLine(0 + cellWidth / 2, height - 12, cellWidth, height - 8);
} else {
g2D.setColor(UI.colorOrange2);
g2D.drawLine(0, height - 12, cellWidth / 2, height - 8);
g2D.drawLine(cellWidth / 2, height - 8, cellWidth, height - 12);
}
g2D.setClip(null);
}
}
@Override
public boolean canRender(CoolMapObject coolMapObject) {
return true;
}
@Override
public JComponent getConfigUI() {
return null;
}
@Override
public void justifyView() {
_updateRectangle(getCoolMapView().getActiveCell());
getViewPanel().repaint();
}
@Override
public void activeCellChanged(CoolMapObject obj, MatrixCell oldCell, MatrixCell newCell) {
// System.out.println(oldCell + " " + newCell);
// _updateRectangle(newCell);
if (_hoverAnimator.isRunning()) {
_hoverAnimator.cancel();
}
_hoverTarget.setBeginEnd(oldCell, newCell);
_hoverAnimator.start();
}
private void _updateRectangle(MatrixCell activeCell) {
CoolMapView view = getCoolMapView();
if (view == null || activeCell == null || activeCell.getCol() == null) {
return;
}
VNode node = getCoolMapView().getCoolMapObject().getViewNodeColumn(activeCell.getCol());
if (node == null || node.getViewOffset() == null) {
return;
}
_activeRectangle.x = (int) (getCoolMapView().getMapAnchor().x + node.getViewOffset());
_activeRectangle.y = 0;
_activeRectangle.width = (int) node.getViewSizeInMap(view.getZoomX());
}
@Override
public void selectionChanged(CoolMapObject obj) {
Set<Rectangle> selections = obj.getCoolMapView().getSelections();
//need to find out which columns are selected
//need a way to merge rectangles.
}
@Override
protected void prepareRender(Graphics2D g2D) {
AffineTransform at = new AffineTransform();
at.rotate(-Math.PI / 2);
g2D.setFont(_zoomControlX.getBoldFont().deriveFont(at));
_maxDescent = g2D.getFontMetrics().getMaxDescent();
_fontSize = _zoomControlX.getBoldFont().getSize();
}
@Override
public void mouseClicked(MouseEvent me) {
if (SwingUtilities.isLeftMouseButton(me)) {
_colSelectionChange(me);
}
}
private Integer _anchorCol = null;
private void _colSelectionChange(MouseEvent me) {
/////////////////////////////////////////////////////////////////////////////////////
//Robust Judgement
if (getCoolMapView() == null && getCoolMapView().getCoolMapObject() == null) {
return;
}
CoolMapView view = getCoolMapView();
CoolMapObject obj = view.getCoolMapObject();
if (obj.getViewNumRows() <= 0) {
return;
}
Integer targetCol = view.getCurrentCol(me.getX());
if (targetCol == null || targetCol < 0 || targetCol >= obj.getViewNumColumns()) {
return;
}
/////////////////////////////////////////////////////////////////////////////////////
ArrayList<Range<Integer>> selectedColumns = view.getSelectedColumns();
//create new selections
if (me.isControlDown() || me.isMetaDown()) {
if (selectedColumns.isEmpty()) {
//same as single selection
_newSingleSelection(obj, targetCol);
} else {
boolean containRange = false;
for (Range<Integer> range : selectedColumns) {
if (range.contains(targetCol)) {
_removeSingleSelection(obj, targetCol);
containRange = true;
break;
}
}
if (containRange == false) {
_addSingleSelection(obj, targetCol);
}
}
} else if (me.isShiftDown()) {
//select a range.
_newSpanSelection(obj, targetCol);
} //create a new single selection
else {
_newSingleSelection(obj, targetCol);
}
// if (me.getClickCount() > 1) {
// CoolMapState state = CoolMapState.createStateSelections("Clear selection", obj, null);
// view.clearSelection();
// StateStorageMaster.addState(state);
// }
}
private void _newSpanSelection(CoolMapObject obj, int targetCol) {
//does not change anchor
//
if (_anchorCol == null) {
_newSingleSelection(obj, targetCol);
} else {
CoolMapView view = obj.getCoolMapView();
ArrayList<Range<Integer>> selectedColumns = view.getSelectedColumns();
Range<Integer> containingOne = null;
for (Range<Integer> range : selectedColumns) {
if (range.contains(_anchorCol)) {
containingOne = range;
break;
}
}
if (containingOne != null) {
selectedColumns.remove(containingOne);
}
Range<Integer> newRange;
if (targetCol > _anchorCol) {
//first remove every selection that contains targetCol
//only one will contain colselection
//remove anchorcol
newRange = Range.closedOpen(_anchorCol, targetCol + 1);
} else {
newRange = Range.closedOpen(targetCol, _anchorCol + 1);
}
selectedColumns.add(newRange);
//build a new selection like this
ArrayList<Rectangle> newSelections = new ArrayList<Rectangle>();
ArrayList<Range<Integer>> selectedRows = view.getSelectedRows();
for (Range<Integer> colRange : selectedColumns) {
for (Range<Integer> rowRange : selectedRows) {
newSelections.add(new Rectangle(colRange.lowerEndpoint(), rowRange.lowerEndpoint(), colRange.upperEndpoint() - colRange.lowerEndpoint(), rowRange.upperEndpoint() - rowRange.lowerEndpoint()));
}
}
CoolMapState state = CoolMapState.createStateSelections("Select columns", obj, null);
view.setSelections(newSelections);
StateStorageMaster.addState(state);
}
}
private void _newSingleSelection(CoolMapObject obj, int targetCol) {
CoolMapView view = obj.getCoolMapView();
ArrayList<Range<Integer>> selectedRows = view.getSelectedRows();
if (selectedRows.isEmpty()) {
selectedRows.add(Range.closedOpen(0, obj.getViewNumRows()));
}
ArrayList<Rectangle> newSelections = new ArrayList<Rectangle>();
for (Range<Integer> range : selectedRows) {
newSelections.add(new Rectangle(targetCol, range.lowerEndpoint(), 1, range.upperEndpoint() - range.lowerEndpoint()));
}
CoolMapState state = CoolMapState.createStateSelections("Select column", obj, null);
view.setSelections(newSelections);
StateStorageMaster.addState(state);
_anchorCol = targetCol;
}
private void _addSingleSelection(CoolMapObject obj, int targetCol) {
CoolMapView view = obj.getCoolMapView();
ArrayList<Range<Integer>> selectedRows = view.getSelectedRows();
if (selectedRows.isEmpty()) {
selectedRows.add(Range.closedOpen(0, obj.getViewNumRows()));
}
//the only difference is that the view was not cleared
ArrayList<Rectangle> newSelections = new ArrayList<Rectangle>();
for (Range<Integer> range : selectedRows) {
newSelections.add(new Rectangle(targetCol, range.lowerEndpoint(), 1, range.upperEndpoint() - range.lowerEndpoint()));
}
CoolMapState state = CoolMapState.createStateSelections("Add selected column", obj, null);
view.addSelection(newSelections);
StateStorageMaster.addState(state);
_anchorCol = targetCol;
}
private void _removeSingleSelection(CoolMapObject obj, int targetCol) {
CoolMapView view = obj.getCoolMapView();
ArrayList<Range<Integer>> selectedRows = view.getSelectedRows();
if (selectedRows.isEmpty()) {
selectedRows.add(Range.closedOpen(0, obj.getViewNumRows()));
}
////////////////////////////////////////////////////////////////
ArrayList<Range<Integer>> selectedColumns = view.getSelectedColumns();
if (selectedColumns.isEmpty()) {
return;
} else {
Range<Integer> tempRange = null;
for (Range<Integer> range : selectedColumns) {
if (range.contains(targetCol)) {
tempRange = range;
break;
}
}
//System.out.println("temp range:" + tempRange);
if (tempRange == null) {
return; //no range contain this range
} else {
if (tempRange.lowerEndpoint().intValue() == targetCol && tempRange.upperEndpoint().intValue() == targetCol + 1) {
selectedColumns.remove(tempRange);
} else {
//split the rectangles, and remove that columns
selectedColumns.remove(tempRange);
//move lower end up by 1
if (tempRange.lowerEndpoint().intValue() == targetCol) {
tempRange = Range.closedOpen(targetCol + 1, tempRange.upperEndpoint());
selectedColumns.add(tempRange);
} else if (tempRange.upperEndpoint().intValue() == targetCol + 1) {
tempRange = Range.closedOpen(tempRange.lowerEndpoint(), targetCol);
selectedColumns.add(tempRange);
} else {
selectedColumns.add(Range.closedOpen(tempRange.lowerEndpoint(), targetCol));
selectedColumns.add(Range.closedOpen(targetCol + 1, tempRange.upperEndpoint()));
}
}
//use selected rows and selected columns to rebuild
ArrayList<Rectangle> newSelections = new ArrayList<Rectangle>();
for (Range<Integer> colRange : selectedColumns) {
for (Range<Integer> rowRange : selectedRows) {
newSelections.add(new Rectangle(colRange.lowerEndpoint(), rowRange.lowerEndpoint(), colRange.upperEndpoint() - colRange.lowerEndpoint(), rowRange.upperEndpoint() - rowRange.lowerEndpoint()));
}
}
CoolMapState state = CoolMapState.createStateSelections("Remove selected column", obj, null);
view.setSelections(newSelections);
StateStorageMaster.addState(state);
//does not change anchor col
}
}
}
//allowing multiple selection makes it super complex...
private boolean _dragStart = false;
private final Point _dragStartPoint = new Point();
private final Point _dragEndPoint = new Point();
private Integer _targetCol = null;
private Integer _startCol = null;
@Override
public void mousePressed(MouseEvent me) {
if (SwingUtilities.isLeftMouseButton(me) && isDataViewValid()) {
_startCol = getCoolMapView().getCurrentCol(me.getX());
ArrayList<Range<Integer>> selectedCols = getCoolMapView().getSelectedColumns();
for (Range<Integer> range : selectedCols) {
if (range.contains(_startCol)) {
_dragStart = true;
//no need to know the start col
_dragStartPoint.x = me.getX();
_dragStartPoint.y = me.getY();
}
}
}
}
@Override
public void mouseReleased(MouseEvent me) {
if (SwingUtilities.isLeftMouseButton(me) && isDataViewValid() && _dragStart) {
Integer endCol = getCoolMapView().getCurrentCol(me.getX());
if (endCol != null) {
//System.out.println("Drag column to:" + endCol);
if (_startCol != null && _startCol.intValue() != endCol.intValue()) {
ArrayList<Range<Integer>> columns = getCoolMapView().getSelectedColumns();
if (columns == null || columns.isEmpty()) {
return;
}
CoolMapState state = CoolMapState.createStateColumns("Shift columns", getCoolMapObject(), null);
getCoolMapView().getCoolMapObject().multiShiftColumns(getCoolMapView().getSelectedColumns(), endCol.intValue());
StateStorageMaster.addState(state);
} else {
_targetCol = null;
}
}
_dragStart = false;
getViewPanel().repaint();
mouseMoved(me);
}
}
@Override
public void mouseEntered(MouseEvent me) {
}
@Override
public void mouseExited(MouseEvent me) {
}
@Override
public void mouseDragged(MouseEvent me) {
if (_dragStart && SwingUtilities.isLeftMouseButton(me)) {
_dragEndPoint.x = me.getX();
_dragEndPoint.y = me.getY();
CoolMapView view = getCoolMapView();
if (view != null) {
_targetCol = view.getCurrentCol(me.getX());
}
//view panel is not null.
getViewPanel().repaint();
}
}
@Override
public void mouseMoved(MouseEvent me) {
//System.out.println("mouse moved");
CoolMapView view = getCoolMapView();
if (view != null) {
Integer col = view.getCurrentCol(me.getX());
MatrixCell oldCell = view.getActiveCell();
MatrixCell newCell = new MatrixCell(oldCell.getRow(), col);
if (!newCell.valueEquals(oldCell)) {
//System.out.println("Col changed:" + view.getActiveCell() + " " + newCell);
view.setActiveCell(view.getActiveCell(), newCell);
//
}
}
}
}
|
gpl-2.0
|
XoopsModules25x/xhelp
|
include/jpgraph/Examples/gantthourminex1.php
|
3119
|
<?php // content="text/plain; charset=utf-8"
// Gantt hour + minute example
require_once ('jpgraph/jpgraph.php');
require_once ('jpgraph/jpgraph_gantt.php');
// Some sample Gantt data
$data = array(
array(0,array("Group 1","345 days","2004-03-01","2004-05-05"), "2001-11-27 10:00","2001-11-27 14:00",FF_FONT2,FS_NORMAL,0),
array(1,array(" Label one",' 122,5 days',' 2004-03-01',' 2003-05-05','MJ'), "2001-11-27 16:00","2001-11-27 18:00"),
array(2," Label two", "2001-11-27","2001-11-27 10:00"),
array(3," Label three", "2001-11-27","2001-11-27 08:00")
);
// Basic graph parameters
$graph = new GanttGraph();
$graph->SetMarginColor('darkgreen@0.8');
$graph->SetColor('white');
// We want to display day, hour and minute scales
$graph->ShowHeaders(GANTT_HDAY | GANTT_HHOUR | GANTT_HMIN);
// We want to have the following titles in our columns
// describing each activity
$graph->scale->actinfo->SetColTitles(
array('Act','Duration','Start','Finish','Resp'));//,array(100,70,70,70));
// Uncomment the following line if you don't want the 3D look
// in the columns headers
//$graph->scale->actinfo->SetStyle(ACTINFO_2D);
$graph->scale->actinfo->SetFont(FF_ARIAL,FS_NORMAL,10);
//These are the default values for use in the columns
//$graph->scale->actinfo->SetFontColor('black');
//$graph->scale->actinfo->SetBackgroundColor('lightgray');
//$graph->scale->actinfo->vgrid->SetStyle('solid');
$graph->scale->actinfo->vgrid->SetColor('gray');
$graph->scale->actinfo->SetColor('darkgray');
// Setup day format
$graph->scale->day->SetBackgroundColor('lightyellow:1.5');
$graph->scale->day->SetFont(FF_ARIAL);
$graph->scale->day->SetStyle(DAYSTYLE_SHORTDAYDATE1);
// Setup hour format
$graph->scale->hour->SetIntervall(1);
$graph->scale->hour->SetBackgroundColor('lightyellow:1.5');
$graph->scale->hour->SetFont(FF_FONT0);
$graph->scale->hour->SetStyle(HOURSTYLE_H24);
$graph->scale->hour->grid->SetColor('gray:0.8');
// Setup minute format
$graph->scale->minute->SetIntervall(30);
$graph->scale->minute->SetBackgroundColor('lightyellow:1.5');
$graph->scale->minute->SetFont(FF_FONT0);
$graph->scale->minute->SetStyle(MINUTESTYLE_MM);
$graph->scale->minute->grid->SetColor('lightgray');
$graph->scale->tableTitle->Set('Phase 1');
$graph->scale->tableTitle->SetFont(FF_ARIAL,FS_NORMAL,12);
$graph->scale->SetTableTitleBackground('darkgreen@0.6');
$graph->scale->tableTitle->Show(true);
$graph->title->Set("Example of hours & mins scale");
$graph->title->SetColor('darkgray');
$graph->title->SetFont(FF_VERDANA,FS_BOLD,14);
for($i=0; $i<count($data); ++$i) {
$bar = new GanttBar($data[$i][0],$data[$i][1],$data[$i][2],$data[$i][3]);
if( count($data[$i])>4 )
$bar->title->SetFont($data[$i][4],$data[$i][5],$data[$i][6]);
$bar->SetPattern(BAND_RDIAG,"yellow");
$bar->SetFillColor("gray");
$graph->Add($bar);
}
//$vline = new GanttVLine("2001-11-27");//d=1006858800,
$vline = new GanttVLine("2001-11-27 9:00");//d=1006858800,
$vline->SetWeight(5);
$vline->SetDayOffset(0);
$vline->title->Set("27/11 9:00");
$vline->title->SetFont(FF_FONT1,FS_BOLD,10);
$graph->Add($vline);
$graph->Stroke();
|
gpl-2.0
|
edwardthomas/phase-equilibria-software
|
PVT_calc/Source/VDW_EquationOfState.cpp
|
2978
|
#include "VDW_EquationOfState.h"
VDW_EquationOfState::VDW_EquationOfState(void)
{
eosName = new string("VDW Equation of State");
}
void VDW_EquationOfState::computeMixParameters(vector<double> zc, ComponentLib *pComp, double Pres, double Temp)
{
/*
The van der Waals equation of state is implemented with the energy parameter and molecular covolume as
as constants using original combining rules.
*/
int nc = GLOBAL::NC;
const double R = GLOBAL::R;
double tc, pc, ac;
// compute A and B for mixture
// first get a, and b for pure components
vector <double> a(nc), b(nc);
double am=0, bm=0, Am=0, Bm=0;
for ( int i = 0; i < nc; i++ )
{
// temp variables to make calculation simpler to read
tc = pComp->tc[i]; // crit temp
pc = pComp->pc[i]; // crit pres
ac = pComp->ac[i]; // acentric factor
// pure component b
b[i] = R*tc/(8*pc);
//linear mixing rule for bm
bm += zc[i]*b[i];
// pure component a
a[i] = 27*R*R*tc*tc/(64*pc);
//mixing rule for am -- calculation finished outside of loop
am += zc[i]*sqrt( a[i] );
// pure a
pComp->aPure[i] = a[i];
// pure b
pComp->bPure[i] = b[i];
}
//am*am to fnish calculation
am = am*am;
// Reduced Am and Bm
Am = am*Pres / ( R*R*Temp*Temp);
Bm = bm*Pres / (R*Temp);
EOS_A_mix = Am;
EOS_B_mix = Bm;
// Compute EOS coefficients for cubic eos
c0 = 1.0;
c1 = -Bm-1.0;
c2 = Am;
c3 = -Am*Bm;
}
void VDW_EquationOfState::computeDensity(vector<double> zc, ComponentLib *pComp, double Pres, double Temp, int phase_id, vector<double> &den)
{
const double R = GLOBAL::R;
double Zreturn = 0.0;
// update mix parameters
computeMixParameters(zc, pComp, Pres, Temp);
// compute average mw
double AMW = computeAverageMW(zc, pComp);
// solve cubic
solveCubicEOS(c0,c1,c2,c3, phase_id, &Zreturn);
double density = Pres/(Zreturn*R*Temp);
den[phase_id] = density*AMW;
}
void VDW_EquationOfState::computeFugacity(vector<double> zc, ComponentLib *pComp, double Pres, double Temp, int phase_id, vector<double> &fug)
{
const double R = GLOBAL::R;
int NC = GLOBAL::NC;
double Zreturn = 0.0;
// update mix parameters
computeMixParameters(zc, pComp, Pres, Temp);
// compute average mw
double AMW = computeAverageMW(zc, pComp);
// solve cubic
solveCubicEOS(c0,c1,c2,c3, phase_id, &Zreturn);
// get dimensioned mix parameters
double bm = EOS_B_mix*R*Temp/Pres;
double am = EOS_A_mix*R*R*Temp*Temp/Pres;
// temporary storage
double term1=0; double term2=0;
vector<double> lnphi(NC), A(NC), B(NC);
// compute mixture fugacity coefficients
for ( int i = 0; i <NC; i++)
{
//compute dimensions Ai and Bi
A[i] = pComp->aPure[i]*Pres / (R*R*Temp*Temp);
B[i] = pComp->bPure[i]*Pres / (R*Temp);
lnphi[i] = B[i]/(Zreturn-EOS_B_mix)-log(Zreturn*(1-EOS_B_mix/Zreturn))-2*sqrt(EOS_A_mix*A[i])/Zreturn;
// compute fugacity
fug[i] = exp(lnphi[i])*zc[i]*Pres;
}
};
VDW_EquationOfState::~VDW_EquationOfState(void)
{
}
|
gpl-2.0
|
dvklopfenstein/PrincetonAlgorithms
|
tests/test_GREP.py
|
1169
|
#!/usr/bin/env python
# TBD Finish Python port
import sys
#from AlgsSedgewickWayne.GREP import GREP
#****************************************************************************
# Compilation: javac GREP.java
# Execution: java GREP regexp < input.txt
# Dependencies: NFA.java StdOut.java
# Data files: http:#algs4.cs.princeton.edu/54regexp/tinyL.txt
#
# This program takes an RE as a command-line argument and prints
# the lines from standard input having some substring that
# is in the language described by the RE.
#
# % more tinyL.txt
# AC
# AD
# AAA
# ABD
# ADD
# BCD
# ABCCBD
# BABAAA
# BABBAAA
#
# % java GREP "(A*B|AC)D" < tinyL.txt
# ABD
# ABCCBD
#
def test_0(prt=sys.stdout):
pass
# TBD
#String regexp = "(.*" + args[0] + ".*)"
#NFA nfa = new NFA(regexp)
#while (StdIn.hasNextLine()):
# String line = StdIn.readLine()
# if nfa.recognizes(line)):
# prt.write(line)
#****************************************************************************
if __name__ == "__main__":
test_0()
# Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
# Copyright 2015-2019, DV Klopfenstein, Python implementation.
|
gpl-2.0
|
edii/drupal8
|
sites/default/files/php/twig/1#49#e6#99df03583aabddb41b13403a04ada7c10e9591f45bc93f4dfdb83e3f2731/df96c0bdadd9e655fbd2b4cc54ecde4129e0bd6eb402c5778cb0935e2cf2216c.php
|
4081
|
<?php
/* field.html.twig */
class __TwigTemplate_49e699df03583aabddb41b13403a04ada7c10e9591f45bc93f4dfdb83e3f2731 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 41
$context["field_name_class"] = \Drupal\Component\Utility\Html::getClass((isset($context["field_name"]) ? $context["field_name"] : null));
// line 43
$context["classes"] = array(0 => "field", 1 => ((("field-" . \Drupal\Component\Utility\Html::getClass((isset($context["entity_type"]) ? $context["entity_type"] : null))) . "--") . (isset($context["field_name_class"]) ? $context["field_name_class"] : null)), 2 => ("field-name-" . (isset($context["field_name_class"]) ? $context["field_name_class"] : null)), 3 => ("field-type-" . \Drupal\Component\Utility\Html::getClass((isset($context["field_type"]) ? $context["field_type"] : null))), 4 => ("field-label-" . (isset($context["label_display"]) ? $context["label_display"] : null)), 5 => ((((isset($context["label_display"]) ? $context["label_display"] : null) == "inline")) ? ("clearfix") : ("")));
// line 53
$context["title_classes"] = array(0 => "field-label", 1 => ((((isset($context["label_display"]) ? $context["label_display"] : null) == "visually_hidden")) ? ("visually-hidden") : ("")));
// line 58
echo "<div";
echo twig_drupal_escape_filter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => (isset($context["classes"]) ? $context["classes"] : null)), "method"), "html", null, true);
echo ">
";
// line 59
if ( !(isset($context["label_hidden"]) ? $context["label_hidden"] : null)) {
// line 60
echo " <div";
echo twig_drupal_escape_filter($this->env, $this->getAttribute((isset($context["title_attributes"]) ? $context["title_attributes"] : null), "addClass", array(0 => (isset($context["title_classes"]) ? $context["title_classes"] : null)), "method"), "html", null, true);
echo ">";
echo twig_drupal_escape_filter($this->env, (isset($context["label"]) ? $context["label"] : null), "html", null, true);
echo "</div>
";
}
// line 62
echo " <div";
echo twig_drupal_escape_filter($this->env, $this->getAttribute((isset($context["content_attributes"]) ? $context["content_attributes"] : null), "addClass", array(0 => "field-items"), "method"), "html", null, true);
echo ">
";
// line 63
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable((isset($context["items"]) ? $context["items"] : null));
foreach ($context['_seq'] as $context["_key"] => $context["item"]) {
// line 64
echo " <div";
echo twig_drupal_escape_filter($this->env, $this->getAttribute($this->getAttribute($context["item"], "attributes", array()), "addClass", array(0 => "field-item"), "method"), "html", null, true);
echo ">";
echo twig_drupal_escape_filter($this->env, $this->getAttribute($context["item"], "content", array()), "html", null, true);
echo "</div>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['item'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 66
echo " </div>
</div>
";
}
public function getTemplateName()
{
return "field.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 60 => 66, 49 => 64, 45 => 63, 40 => 62, 32 => 60, 30 => 59, 25 => 58, 23 => 53, 21 => 43, 19 => 41,);
}
}
|
gpl-2.0
|
britco/kirki
|
includes/class-kirki.php
|
15571
|
<?php
/**
* The Kirki API class.
* Takes care of adding panels, sections & fields to the customizer.
* For documentation please see https://github.com/reduxframework/kirki/wiki
*
* @package Kirki
* @category Core
* @author Aristeides Stathopoulos
* @copyright Copyright (c) 2015, Aristeides Stathopoulos
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
* @since 1.0
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Early exit if the class already exists
if ( class_exists( 'Kirki' ) ) {
return;
}
class Kirki {
public static $config = array();
public static $fields = array();
public static $panels = array();
public static $sections = array();
/**
* the class constructor
*/
public function __construct() {
add_action( 'wp_loaded', array( $this, 'add_to_customizer' ), 1 );
}
/**
* Helper function that adds the fields, sections and panels to the customizer.
* @return void
*/
public function add_to_customizer() {
$this->fields_from_filters();
add_action( 'customize_register', array( $this, 'add_panels' ), 97 );
add_action( 'customize_register', array( $this, 'add_sections' ), 98 );
add_action( 'customize_register', array( $this, 'add_fields' ), 99 );
}
/**
* Process fields added using the 'kirki/fields' and 'kirki/controls' filter.
* These filters are no longer used, this is simply for backwards-compatibility
*/
public function fields_from_filters() {
$fields = apply_filters( 'kirki/controls', array() );
$fields = apply_filters( 'kirki/fields', $fields );
if ( ! empty( $fields ) ) {
foreach ( $fields as $field ) {
self::add_field( 'global', $field );
}
}
}
/**
* Get the value of an option from the db.
*
* @var string the ID of the configuration corresponding to this field
* @var string the field_id (defined as 'settings' in the field arguments)
*
* @return mixed the saved value of the field.
*
*/
public static function get_option( $config_id = '', $field_id = '' ) {
/**
* Make sure value is defined
*/
$value = '';
/**
* This allows us to skip the $config_id argument.
* If we skip adding a $config_id, use the 'global' configuration.
*/
if ( ( '' == $field_id ) && '' != $config_id ) {
$field_id = $config_id;
$config_id = 'global';
}
/**
* If $config_id is empty, set it to 'global'.
*/
$config_id = ( '' == $config_id ) ? 'global' : $config_id;
if ( 'theme_mod' == self::$config[ $config_id ]['option_type'] ) {
/**
* We're using theme_mods.
* so just get the value using get_theme_mod
*/
$value = get_theme_mod( $field_id, self::$fields[ $field_id ]['default'] );
/**
* If the field is a background field, then get the sub-fields
* and return an array of the values.
*/
if ( 'background' == self::$fields[ $field_id ]['type'] ) {
$value = array();
foreach ( self::$fields[ $field_id ]['default'] as $property_key => $property_default ) {
$value[ $property_key ] = get_theme_mod( $field_id.'_'.$property_key, $property_default );
}
}
} elseif ( 'option' == self::$config[ $config_id ]['option_type'] ) {
/**
* We're using options.
*/
if ( '' != self::$config[ $config_id ]['option_name'] ) {
/**
* Options are serialized as a single option in the db.
* We'll have to get the option and then get the item from the array.
*/
$options = get_option( self::$config[ $config_id ]['option_name'] );
if ( ! isset( self::$fields[ $field_id ] ) && isset( self::$fields[ self::$config[ $config_id ]['option_name'].'['.$field_id.']' ] ) ) {
$field_id = self::$config[ $config_id ]['option_name'].'['.$field_id.']';
}
$setting_modified = str_replace( ']', '', str_replace( self::$config[ $config_id ]['option_name'].'[', '', $field_id ) );
/**
* If this is a background field, get the individual sub-fields and return an array.
*/
if ( 'background' == self::$fields[ $field_id ]['type'] ) {
$value = array();
foreach ( self::$fields[ $field_id ]['default'] as $property => $property_default ) {
if ( isset( $options[ $setting_modified.'_'.$property ] ) ) {
$value[ $property ] = $options[ $setting_modified.'_'.$property ];
} else {
$value[ $property ] = $property_default;
}
}
} else {
/**
* This is not a background field so continue and get the value.
*/
$value = ( isset( $options[ $setting_modified ] ) ) ? $options[ $setting_modified ] : self::$fields[ $field_id ]['default'];
$value = maybe_unserialize( $value );
}
} else {
/**
* Each option separately saved in the db
*/
$value = get_option( $field_id, self::$fields[ $field_id ]['default'] );
/**
* If the field is a background field, then get the sub-fields
* and return an array of the values.
*/
if ( 'background' == self::$fields[ $field_id ]['type'] ) {
$value = array();
foreach ( self::$fields[ $field_id ]['default'] as $property_key => $property_default ) {
$value[ $property_key ] = get_option( $field_id.'_'.$property_key, $property_default );
}
}
}
}
/**
* reduxframework compatibility tweaks.
* If KIRKI_REDUX_COMPATIBILITY is defined as true then modify the output of the values
* and make them compatible with Redux.
*/
if ( defined( 'KIRKI_REDUX_COMPATIBILITY' ) && KIRKI_REDUX_COMPATIBILITY ) {
switch ( self::$fields[ $field_id ]['type'] ) {
case 'image':
$value = Kirki_Helper::get_image_from_url( $value );
break;
}
}
return $value;
}
/**
* Sets the configuration options.
*
* @var string the configuration ID.
* @var array the configuration options.
*/
public static function add_config( $config_id, $args = array() ) {
$default_args = array(
'capability' => 'edit_theme_options',
'option_type' => 'theme_mod',
'option_name' => '',
'compiler' => array(),
);
$args = array_merge( $default_args, $args );
/**
* Allow empty value as the config ID by setting the id to global.
*/
$config_id = ( '' == $config_id ) ? 'global' : $config_id;
/**
* Set the config
*/
self::$config[ $config_id ] = $args;
}
/**
* register our panels to the WordPress Customizer
* @var object The WordPress Customizer object
*/
public function add_panels( $wp_customize ) {
if ( ! empty( self::$panels ) ) {
foreach ( self::$panels as $panel ) {
$wp_customize->add_panel( sanitize_key( $panel['id'] ), array(
'title' => esc_textarea( $panel['title'] ),
'priority' => esc_attr( $panel['priority'] ),
'description' => esc_textarea( $panel['description'] ),
'active_callback' => $panel['active_callback'],
) );
}
}
}
/**
* register our sections to the WordPress Customizer
* @var object The WordPress Customizer object
*/
public function add_sections( $wp_customize ) {
if ( ! empty( self::$sections ) ) {
foreach ( self::$sections as $section ) {
$wp_customize->add_section( sanitize_key( $section['id'] ), array(
'title' => esc_textarea( $section['title'] ),
'priority' => esc_attr( $section['priority'] ),
'panel' => esc_attr( $section['panel'] ),
'description' => esc_textarea( $section['description'] ),
'active_callback' => $section['active_callback'],
) );
}
}
}
/**
* Create the settings and controls from the $fields array and register them.
* @var object The WordPress Customizer object
*/
public function add_fields( $wp_customize ) {
$control_types = apply_filters( 'kirki/control_types', array(
'code' => 'Kirki_Controls_Code_Control',
'color' => 'WP_Customize_Color_Control',
'color-alpha' => 'Kirki_Controls_Color_Alpha_Control',
'image' => 'WP_Customize_Image_Control',
'upload' => 'WP_Customize_Upload_Control',
'switch' => 'Kirki_Controls_Switch_Control',
'toggle' => 'Kirki_Controls_Toggle_Control',
'radio-buttonset' => 'Kirki_Controls_Radio_ButtonSet_Control',
'radio-image' => 'Kirki_Controls_Radio_Image_Control',
'sortable' => 'Kirki_Controls_Sortable_Control',
'slider' => 'Kirki_Controls_Slider_Control',
'number' => 'Kirki_Controls_Number_Control',
'multicheck' => 'Kirki_Controls_MultiCheck_Control',
'palette' => 'Kirki_Controls_Palette_Control',
'custom' => 'Kirki_Controls_Custom_Control',
'editor' => 'Kirki_Controls_Editor_Control',
'select2' => 'Kirki_Controls_Select2_Control',
'select2-multiple' => 'Kirki_Controls_Select2_Multiple_Control',
'dimension' => 'Kirki_Controls_Dimension_Control',
) );
foreach ( self::$fields as $field ) {
if ( 'background' == $field['type'] ) {
continue;
}
$wp_customize->add_setting( Kirki_Field::sanitize_settings( $field ), array(
'default' => Kirki_Field::sanitize_default( $field ),
'type' => Kirki_Field::sanitize_type( $field ),
'capability' => Kirki_Field::sanitize_capability( $field ),
'transport' => Kirki_Field::sanitize_transport( $field ),
'sanitize_callback' => Kirki_Field::sanitize_callback( $field ),
) );
$class_name = 'WP_Customize_Control';
if ( array_key_exists( $field['type'], $control_types ) )
$class_name = $control_types[ $field['type'] ];
$wp_customize->add_control( new $class_name(
$wp_customize,
Kirki_Field::sanitize_id( $field ),
Kirki_Field::sanitize_field( $field )
) );
}
}
/**
* Create a new panel
*
* @var string the ID for this panel
* @var array the panel arguments
*/
public static function add_panel( $id = '', $args = array() ) {
$args['id'] = esc_attr( $id );
$args['description'] = ( isset( $args['description'] ) ) ? esc_textarea( $args['description'] ) : '';
$args['priority'] = ( isset( $args['priority'] ) ) ? esc_attr( $args['priority'] ) : 10;
if ( ! isset( $args['active_callback'] ) ) {
$args['active_callback'] = ( isset( $args['required'] ) ) ? 'kirki_active_callback' : '__return_true';
}
self::$panels[ $args['id'] ] = $args;
}
/**
* Create a new section
*
* @var string the ID for this section
* @var array the section arguments
*/
public static function add_section( $id, $args ) {
$args['id'] = esc_attr( $id );
$args['panel'] = ( isset( $args['panel'] ) ) ? esc_attr( $args['panel'] ) : '';
$args['description'] = ( isset( $args['description'] ) ) ? esc_textarea( $args['description'] ) : '';
$args['priority'] = ( isset( $args['priority'] ) ) ? esc_attr( $args['priority'] ) : 10;
if ( ! isset( $args['active_callback'] ) ) {
$args['active_callback'] = ( isset( $args['required'] ) ) ? 'kirki_active_callback' : '__return_true';
}
self::$sections[ $args['id'] ] = $args;
}
/**
* Create a new field
*
* @var string the configuration ID for this field
* @var array the field arguments
*/
public static function add_field( $config_id, $args ) {
if ( is_array( $config_id ) && empty( $args ) ) {
$args = $config_id;
$config_id = 'global';
}
$config_id = ( '' == $config_id ) ? 'global' : $config_id;
/**
* Get the configuration options
*/
$config = self::$config[ $config_id ];
/**
* If we've set an option in the configuration
* then make sure we're using options and not theme_mods
*/
if ( '' != $config['option_name'] ) {
$config['option_type'] = 'option';
}
/**
* If no option name has been set for the field,
* use the one from the configuration
*/
if ( ! isset( $args['option_name'] ) ) {
$args['option_name'] = $config['option_name'];
}
/**
* If no capability has been set for the field,
* use the one from the configuration
*/
if ( ! isset( $args['capability'] ) ) {
$args['capability'] = $config['capability'];
}
/**
* Check if [settings] is set.
* If not set, check for [setting]
*/
if ( ! isset( $args['settings'] ) && isset( $args['setting'] ) ) {
$args['settings'] = $args['setting'];
}
/**
* If no option-type has been set for the field,
* use the one from the configuration
*/
if ( ! isset( $args['option_type'] ) ) {
$args['option_type'] = $config['option_type'];
}
/**
* Add the field to the static $fields variable properly indexed
*/
self::$fields[ Kirki_Field::sanitize_settings( $args ) ] = $args;
if ( 'background' == $args['type'] ) {
/**
* Build the background fields
*/
self::$fields = Kirki_Explode_Background_Field::process_fields( self::$fields );
}
}
/**
* Find the config ID based on the field options
*/
public static function get_config_id( $field ) {
/**
* Get the array of configs from the Kirki class
*/
$configs = Kirki::$config;
/**
* Loop through all configs and search for a match
*/
foreach ( $configs as $config_id => $config_args ) {
$option_type = ( isset( $config_args['option_type'] ) ) ? $config_args['option_type'] : 'theme_mod';
$option_name = ( isset( $config_args['option_name'] ) ) ? $config_args['option_name'] : '';
$types_match = false;
$names_match = false;
if ( isset( $field['option_type'] ) ) {
$types_match = ( $option_type == $field['option_type'] ) ? true : false;
}
if ( isset( $field['option_name'] ) ) {
$names_match = ( $option_name == $field['option_name'] ) ? true : false;
}
if ( $types_match && $names_match ) {
$active_config = $config_id;
}
}
return $config_id;
}
/**
* Build the variables.
*
* @return array ('variable-name' => value)
*/
public function get_variables() {
$variables = array();
/**
* Loop through all fields
*/
foreach ( self::$fields as $field ) {
/**
* Check if we have variables for this field
*/
if ( isset( $field['variables'] ) && false != $field['variables'] && ! empty( $field['variables'] ) ) {
/**
* Loop through the array of variables
*/
foreach ( $field['variables'] as $field_variable ) {
/**
* Is the variable ['name'] defined?
* If yes, then we can proceed.
*/
if ( isset( $field_variable['name'] ) ) {
/**
* Sanitize the variable name
*/
$variable_name = esc_attr( $field_variable['name'] );
/**
* Do we have a callback function defined?
* If not then set $variable_callback to false.
*/
$variable_callback = ( isset( $field_variable['callback'] ) && is_callable( $field_variable['callback'] ) ) ? $field_variable['callback'] : false;
/**
* If we have a variable_callback defined then get the value of the option
* and run it through the callback function.
* If no callback is defined (false) then just get the value.
*/
if ( $variable_callback ) {
$variables[ $variable_name ] = call_user_func( $field_variable['callback'], self::get_option( Kirki_Field::sanitize_settings( $field ) ) );
} else {
$variables[ $variable_name ] = self::get_option( $field['settings'] );
}
}
}
}
}
/**
* Pass the variables through a filter ('kirki/variable')
* and return the array of variables
*/
return apply_filters( 'kirki/variable', $variables );
}
}
|
gpl-2.0
|
Khanos/HardCode
|
OpenEMR/src/interface/forms/fee_sheet/review/fee_sheet_justify.php
|
3040
|
<?php
/**
* Controller for fee sheet justification AJAX requests
*
* Copyright (C) 2013 Kevin Yeh <kevin.y@integralemr.com> and OEMR <www.oemr.org>
*
* LICENSE: This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>;.
*
* @package OpenEMR
* @author Kevin Yeh <kevin.y@integralemr.com>
* @link http://www.open-emr.org
*/
$fake_register_globals=false;
$sanitize_all_escapes=true;
require_once("../../../globals.php");
require_once("fee_sheet_queries.php");
include_once("$srcdir/jsonwrapper/jsonwrapper.php");
if(!acl_check('acct', 'bill'))
{
header("HTTP/1.0 403 Forbidden");
echo "Not authorized for billing";
return false;
}
if(isset($_REQUEST['pid']))
{
$req_pid=$_REQUEST['pid'];
}
if(isset($_REQUEST['encounter']))
{
$req_encounter=$_REQUEST['encounter'];
}
if(isset($_REQUEST['task']))
{
$task=$_REQUEST['task'];
}
if(isset($_REQUEST['billing_id']))
{
$billing_id=$_REQUEST['billing_id'];
}
if($task=='retrieve')
{
$retval=array();
$patient=issue_diagnoses($req_pid,$req_encounter);
$common=common_diagnoses();
$retval['patient']=$patient;
$retval['common']=$common;
$fee_sheet_diags=array();
$fee_sheet_procs=array();
fee_sheet_items($req_pid,$req_encounter,$fee_sheet_diags,$fee_sheet_procs);
$retval['current']=$fee_sheet_diags;
echo json_encode($retval);
return;
}
if($task=='update')
{
$skip_issues=false;
if(isset($_REQUEST['skip_issues']))
{
$skip_issues=$_REQUEST['skip_issues']=='true';
}
$diags=array();
if(isset($_REQUEST['diags']))
{
$json_diags=json_decode($_REQUEST['diags']);
}
foreach($json_diags as $diag)
{
$new_diag=new code_info($diag->{'code'},$diag->{'code_type'},$diag->{'description'});
if(isset($diag->{'prob_id'}))
{
$new_diag->db_id=$diag->{'prob_id'};
}
else
{
$new_diag->db_id=null;
$new_diag->create_problem=$diag->{'create_problem'};
}
$diags[]=$new_diag;
}
$database->StartTrans();
create_diags($req_pid,$req_encounter,$diags);
if(!$skip_issues)
{
update_issues($req_pid,$req_encounter,$diags);
}
update_justify($req_pid,$req_encounter,$diags,$billing_id);
$database->CompleteTrans();
}
?>
|
gpl-2.0
|
taranion/RPGFramework
|
Babylon_API/src/org/prelle/rpgframework/ConfigOptionImpl.java
|
3662
|
/**
*
*/
package org.prelle.rpgframework;
import java.util.prefs.Preferences;
import de.rpgframework.ConfigOption;
/**
* @author prelle
*
*/
public class ConfigOptionImpl extends ConfigNodeImpl implements ConfigOption {
private Type type;
private Object[] choiceOptions;
private Object defaultValue;
private int lowerLimit;
private int upperLimit;
//--------------------------------------------------------------------
public ConfigOptionImpl(String id, Type type, Object defVal) {
super(id);
this.type = type;
defaultValue = defVal;
}
//--------------------------------------------------------------------
/**
* @see de.rpgframework.ConfigOption#getChoiceOptions()
*/
@Override
public Object[] getChoiceOptions() {
return choiceOptions;
}
//-------------------------------------------------------------------
/**
* @see de.rpgframework.ConfigOption#getOptionName(java.lang.Object)
*/
public String getOptionName(Object obj) {
return RES.getString("config."+getLocalId()+"."+String.valueOf(obj).toLowerCase());
}
//--------------------------------------------------------------------
/**
* @see de.rpgframework.ConfigOption#getDefaultValue()
*/
@Override
public Object getDefaultValue() {
return defaultValue;
}
//--------------------------------------------------------------------
/**
* @see de.rpgframework.ConfigOption#getLowerLimit()
*/
@Override
public int getLowerLimit() {
return lowerLimit;
}
//--------------------------------------------------------------------
/**
* @see de.rpgframework.ConfigOption#getType()
*/
@Override
public Type getType() {
return type;
}
//--------------------------------------------------------------------
/**
* @see de.rpgframework.ConfigOption#getUpperLimit()
*/
@Override
public int getUpperLimit() {
return upperLimit;
}
//-------------------------------------------------------------------
/**
* @see de.rpgframework.ConfigOption#getValue()
*/
@Override
public Object getValue() {
Preferences PREF = parent.getPreferences();
switch (type) {
case BOOLEAN:
return PREF.getBoolean(getLocalId(), (boolean)defaultValue);
case TEXT:
case PASSWORD:
case CHOICE:
return PREF.get(getLocalId(), (String) defaultValue);
case NUMBER:
return PREF.getInt(getLocalId(), (int) defaultValue);
default:
return PREF.get(getLocalId(), null);
}
}
//-------------------------------------------------------------------
/**
* @see de.rpgframework.ConfigOption#getStringValue()
*/
@Override
public String getStringValue() {
Preferences PREF = parent.getPreferences();
System.out.println("getValue("+PREF+" id="+getLocalId()+")");
switch (type) {
case BOOLEAN:
return String.valueOf(PREF.getBoolean(getLocalId(), (boolean)defaultValue));
case TEXT:
case PASSWORD:
case CHOICE:
return PREF.get(getLocalId(), (String) defaultValue);
case NUMBER:
return String.valueOf(PREF.getInt(getLocalId(), (int) defaultValue));
default:
return String.valueOf(PREF.get(getLocalId(), null));
}
}
//-------------------------------------------------------------------
/**
* @see de.rpgframework.ConfigOption#set(java.lang.Object)
*/
@Override
public void set(Object newVal) {
Preferences PREF = parent.getPreferences();
String oldVal = PREF.get(getLocalId(), null);
if ((oldVal==null && newVal==null) || (oldVal!=null && newVal!=null && oldVal.equals(newVal)))
return;
PREF.put(getLocalId(), String.valueOf(newVal));
logger.debug("Option "+getID()+" changed "+((type==Type.PASSWORD)?"":"to "+getValue()));
super.parent.markRecentlyChanged(this);
}
}
|
gpl-2.0
|
danfmsouza/yipservicedesk
|
includes/phpmailer/language/phpmailer.lang-pl.php
|
1374
|
<?php
/**
* PHPMailer language file.
* Polish Version, encoding: windows-1250
* translated from english lang file ver. 1.72
*/
$PHPMAILER_LANG = array();
$PHPMAILER_LANG["provide_address"] = 'Nale¿y podaæ prawid³owy adres email Odbiorcy.';
$PHPMAILER_LANG["mailer_not_supported"] = 'Wybrana metoda wysy³ki wiadomoœci nie jest obs³ugiwana.';
$PHPMAILER_LANG["execute"] = 'Nie mo¿na uruchomiæ: ';
$PHPMAILER_LANG["instantiate"] = 'Nie mo¿na wywo³aæ funkcji mail(). SprawdŸ konfiguracjê serwera.';
$PHPMAILER_LANG["authenticate"] = 'B³¹d SMTP: Nie mo¿na przeprowadziæ autentykacji.';
$PHPMAILER_LANG["from_failed"] = 'Nastêpuj¹cy adres Nadawcy jest jest nieprawid³owy: ';
$PHPMAILER_LANG["recipients_failed"] = 'B³¹d SMTP: Nastêpuj¹cy ' .
'odbiorcy s¹ nieprawid³owi: ';
$PHPMAILER_LANG["data_not_accepted"] = 'B³¹d SMTP: Dane nie zosta³y przyjête.';
$PHPMAILER_LANG["connect_host"] = 'B³¹d SMTP: Nie mo¿na po³¹czyæ siê z wybranym hostem.';
$PHPMAILER_LANG["file_access"] = 'Brak dostêpu do pliku: ';
$PHPMAILER_LANG["file_open"] = 'Nie mo¿na otworzyæ pliku: ';
$PHPMAILER_LANG["encoding"] = 'Nieznany sposób kodowania znaków: ';
$PHPMAILER_LANG["signing"] = 'Signing Error: ';
?>
|
gpl-2.0
|
liao1995/Jasmin
|
RandomGen/RandomGen.java
|
169
|
public class RandomGen{
public static int generate(int seed){
return 69069*seed;
}
public static void main(String[] args){
System.out.println(generate(20));
}
}
|
gpl-2.0
|
dibben/NoteTaker
|
src/SpellChecker.cpp
|
3224
|
/*
Copyright 2015 David Dibben <dibben@ieee.org>
NoteTaker 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.
NoteTaker 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 NoteTaker. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SpellChecker.h"
#include "SpellingDictionary.h"
#include <hunspell/hunspell.hxx>
#include <QTextCodec>
#include <QStringList>
#include <QDir>
#include <QStandardPaths>
#include <QTextStream>
/*!
\brief
*/
SpellChecker::SpellChecker()
{
fTextCodec = 0;
}
SpellChecker::~SpellChecker()
{
}
bool SpellChecker::IsCorrect(const QString &word) const
{
if (fChecker.isNull()) return true;
return fChecker->spell( FromUnicode(word) ) != 0;
}
QStringList SpellChecker::Suggestions(const QString& word) const
{
if (fChecker.isNull()) return QStringList();
QStringList result;
char** suggestedWords;
int count = fChecker->suggest(&suggestedWords, FromUnicode(word));
for (int i = 0; i < count; ++i) {
result << ToUnicode(suggestedWords[i]);
}
fChecker->free_list(&suggestedWords, count);
return result;
}
void SpellChecker::AddToUserDictionary(const QString& text)
{
QString word = text.trimmed();
if (word.isEmpty()) return;
fChecker->add(FromUnicode(word).constData());
QFile file(UserDictionary());
if (!file.open(QIODevice::Append)) return;
QTextStream str(&file);
str << word << "\n";
file.close();
}
QByteArray SpellChecker::FromUnicode(const QString& str) const
{
if (fTextCodec == 0) return str.toUtf8();
return fTextCodec->fromUnicode(str);
}
QString SpellChecker::ToUnicode(const char* str) const
{
if (fTextCodec == 0) return QString::fromUtf8(str);
return fTextCodec->toUnicode(str);
}
void SpellChecker::LoadDictionary(const QString& language)
{
LoadDictionary(SpellingDictionary::DictionaryForLanguage(language));
}
void SpellChecker::LoadDictionary(const SpellingDictionary& dictionary)
{
QString dicFilePath = dictionary.FilePath();
QString affixFilePath(dicFilePath);
affixFilePath.replace(".dic", ".aff");
fChecker.reset(new Hunspell(affixFilePath.toLocal8Bit(), dicFilePath.toLocal8Bit()));
fTextCodec = QTextCodec::codecForName(fChecker->get_dic_encoding());
if (!fTextCodec) {
fTextCodec = QTextCodec::codecForName("UTF-8");
}
LoadUserDictionary();
}
void SpellChecker::LoadUserDictionary()
{
QFile file(UserDictionary());
if (!file.open(QIODevice::ReadOnly)) return;
QTextStream str(&file);
while (!str.atEnd()) {
QString word = str.readLine();
if (!word.isEmpty()) {
fChecker->add(FromUnicode(word).constData());
}
}
}
QString SpellChecker::UserDictionary() const
{
QDir path(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
if (!path.exists()) {
path.mkpath(path.absolutePath());
}
return (path.absoluteFilePath("user.dic"));
}
|
gpl-2.0
|
peterbartha/j2eecm
|
edu.bme.vik.iit.j2eecm.diagram/src/components/diagram/edit/policies/BrowserItemSemanticEditPolicy.java
|
3729
|
package components.diagram.edit.policies;
import java.util.Iterator;
import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.gef.commands.Command;
import org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand;
import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand;
import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyElementCommand;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateRelationshipRequest;
import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest;
import org.eclipse.gmf.runtime.emf.type.core.requests.ReorientRelationshipRequest;
import org.eclipse.gmf.runtime.notation.Edge;
import org.eclipse.gmf.runtime.notation.View;
import components.diagram.edit.commands.WebReleationshipCreateCommand;
import components.diagram.edit.commands.WebReleationshipReorientCommand;
import components.diagram.edit.parts.WebReleationshipEditPart;
import components.diagram.part.ModelVisualIDRegistry;
import components.diagram.providers.ModelElementTypes;
/**
* @generated
*/
public class BrowserItemSemanticEditPolicy extends
ModelBaseItemSemanticEditPolicy {
/**
* @generated
*/
public BrowserItemSemanticEditPolicy() {
super(ModelElementTypes.Browser_3001);
}
/**
* @generated
*/
protected Command getDestroyElementCommand(DestroyElementRequest req) {
View view = (View) getHost().getModel();
CompositeTransactionalCommand cmd = new CompositeTransactionalCommand(
getEditingDomain(), null);
cmd.setTransactionNestingEnabled(false);
for (Iterator<?> it = view.getSourceEdges().iterator(); it.hasNext();) {
Edge outgoingLink = (Edge) it.next();
if (ModelVisualIDRegistry.getVisualID(outgoingLink) == WebReleationshipEditPart.VISUAL_ID) {
DestroyElementRequest r = new DestroyElementRequest(
outgoingLink.getElement(), false);
cmd.add(new DestroyElementCommand(r));
cmd.add(new DeleteCommand(getEditingDomain(), outgoingLink));
continue;
}
}
EAnnotation annotation = view.getEAnnotation("Shortcut"); //$NON-NLS-1$
if (annotation == null) {
// there are indirectly referenced children, need extra commands: false
addDestroyShortcutsCommand(cmd, view);
// delete host element
cmd.add(new DestroyElementCommand(req));
} else {
cmd.add(new DeleteCommand(getEditingDomain(), view));
}
return getGEFWrapper(cmd.reduce());
}
/**
* @generated
*/
protected Command getCreateRelationshipCommand(CreateRelationshipRequest req) {
Command command = req.getTarget() == null ? getStartCreateRelationshipCommand(req)
: getCompleteCreateRelationshipCommand(req);
return command != null ? command : super
.getCreateRelationshipCommand(req);
}
/**
* @generated
*/
protected Command getStartCreateRelationshipCommand(
CreateRelationshipRequest req) {
if (ModelElementTypes.WebReleationship_4001 == req.getElementType()) {
return getGEFWrapper(new WebReleationshipCreateCommand(req,
req.getSource(), req.getTarget()));
}
return null;
}
/**
* @generated
*/
protected Command getCompleteCreateRelationshipCommand(
CreateRelationshipRequest req) {
if (ModelElementTypes.WebReleationship_4001 == req.getElementType()) {
return null;
}
return null;
}
/**
* Returns command to reorient EClass based link. New link target or source
* should be the domain model element associated with this node.
*
* @generated
*/
protected Command getReorientRelationshipCommand(
ReorientRelationshipRequest req) {
switch (getVisualID(req)) {
case WebReleationshipEditPart.VISUAL_ID:
return getGEFWrapper(new WebReleationshipReorientCommand(req));
}
return super.getReorientRelationshipCommand(req);
}
}
|
gpl-2.0
|
frannuca/mapreduce
|
src/test/scala/org/fjn/mapreduce/interface/MapReduceFunctionBaseTest.scala
|
644
|
package org.fjn.mapreduce.interface
import org.scalatest.junit.AssertionsForJUnit
import org.junit.Test
class MapReduceFunctionBaseTest extends AssertionsForJUnit {
val testClass = new MapReduceFunctionBase[Int,Double,String] {
override def getDefaultAccumulator:String={
"0"
}
override def getID:String={
"Test"
}
override def reduceExecutor(acc:String,x:Double):String={
acc + "+" + x.toString
}
override def mapExecutor(x:Int):Double={
x.toDouble
}
}
@Test def TestSimpleMapReduce{
val ok = testClass.mapReduce(Seq(1,2))
assert( ok === "0+1.0+2.0")
}
}
|
gpl-2.0
|
alshubei/ps-app
|
src/scripts/stores/datepicker-store.js
|
795
|
var Reflux = require('reflux');
var _ = require('underscore');
var Utils = require('../../scripts/components/common/utils.js');
var DatePickerActions = require('../actions/datepicker-actions.js');
var DatePickerStore = Reflux.createStore({
listenables: [DatePickerActions],
getState: function () {
return _state;
},
getDate: function () {
return _state.date;
},
getDateFormatted: function () {
return Utils.formatDate(this.getDate());
},
getMonth: function () {
return (new Date(_state.date)).getMonth() + 1;
},
changeDate: function (date) {
//here validate!!!!
_state.date = date;
this.trigger(date);
}
});
var _state = { date: Utils.formatDate(Date.now())};
module.exports = DatePickerStore;
|
gpl-2.0
|
imfaber/imfaber_v2
|
vendor/mockery/mockery/tests/Mockery/ContainerTest.php
|
45578
|
<?php
/**
* Mockery
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://github.com/padraic/mockery/master/LICENSE
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to padraic@php.net so we can send you a copy immediately.
*
* @category Mockery
* @package Mockery
* @subpackage UnitTests
* @copyright Copyright (c) 2010-2014 Pádraic Brady (http://blog.astrumfutura.com)
* @license http://github.com/padraic/mockery/blob/master/LICENSE New BSD License
*/
use Mockery\Generator\MockConfigurationBuilder;
class ContainerTest extends PHPUnit_Framework_TestCase
{
/** @var Mockery\Container */
private $container;
public function setup ()
{
$this->container = new \Mockery\Container(\Mockery::getDefaultGenerator(), new \Mockery\Loader\EvalLoader());
}
public function teardown()
{
$this->container->mockery_close();
}
public function testSimplestMockCreation()
{
$m = $this->container->mock();
$m->shouldReceive('foo')->andReturn('bar');
$this->assertEquals('bar', $m->foo());
}
public function testGetKeyOfDemeterMockShouldReturnKeyWhenMatchingMock()
{
$m = $this->container->mock();
$m->shouldReceive('foo->bar');
$this->assertRegExp(
'/Mockery_(\d+)__demeter_foo/',
$this->container->getKeyOfDemeterMockFor('foo')
);
}
public function testGetKeyOfDemeterMockShouldReturnNullWhenNoMatchingMock()
{
$method = 'unknownMethod';
$this->assertNull($this->container->getKeyOfDemeterMockFor($method));
$m = $this->container->mock();
$m->shouldReceive('method');
$this->assertNull($this->container->getKeyOfDemeterMockFor($method));
$m->shouldReceive('foo->bar');
$this->assertNull($this->container->getKeyOfDemeterMockFor($method));
}
public function testNamedMocksAddNameToExceptions()
{
$m = $this->container->mock('Foo');
$m->shouldReceive('foo')->with(1)->andReturn('bar');
try {
$m->foo();
} catch (\Mockery\Exception $e) {
$this->assertTrue((bool) preg_match("/Foo/", $e->getMessage()));
}
}
public function testSimpleMockWithArrayDefs()
{
$m = $this->container->mock(array('foo'=>1,'bar'=>2));
$this->assertEquals(1, $m->foo());
$this->assertEquals(2, $m->bar());
}
public function testSimpleMockWithArrayDefsCanBeOverridden()
{
// eg. In shared test setup
$m = $this->container->mock(array('foo' => 1, 'bar' => 2));
// and then overridden in one test
$m->shouldReceive('foo')->with('baz')->once()->andReturn(2);
$m->shouldReceive('bar')->with('baz')->once()->andReturn(42);
$this->assertEquals(2, $m->foo('baz'));
$this->assertEquals(42, $m->bar('baz'));
}
public function testNamedMockWithArrayDefs()
{
$m = $this->container->mock('Foo', array('foo'=>1,'bar'=>2));
$this->assertEquals(1, $m->foo());
$this->assertEquals(2, $m->bar());
try {
$m->f();
} catch (BadMethodCallException $e) {
$this->assertTrue((bool) preg_match("/Foo/", $e->getMessage()));
}
}
public function testNamedMockWithArrayDefsCanBeOverridden()
{
// eg. In shared test setup
$m = $this->container->mock('Foo', array('foo' => 1));
// and then overridden in one test
$m->shouldReceive('foo')->with('bar')->once()->andReturn(2);
$this->assertEquals(2, $m->foo('bar'));
try {
$m->f();
} catch (BadMethodCallException $e) {
$this->assertTrue((bool) preg_match("/Foo/", $e->getMessage()));
}
}
public function testNamedMockMultipleInterfaces()
{
$m = $this->container->mock('stdClass, ArrayAccess, Countable', array('foo'=>1,'bar'=>2));
$this->assertEquals(1, $m->foo());
$this->assertEquals(2, $m->bar());
try {
$m->f();
} catch (BadMethodCallException $e) {
$this->assertTrue((bool) preg_match("/stdClass/", $e->getMessage()));
$this->assertTrue((bool) preg_match("/ArrayAccess/", $e->getMessage()));
$this->assertTrue((bool) preg_match("/Countable/", $e->getMessage()));
}
}
public function testNamedMockWithConstructorArgs()
{
$m = $this->container->mock("MockeryTest_ClassConstructor2[foo]", array($param1 = new stdClass()));
$m->shouldReceive("foo")->andReturn(123);
$this->assertEquals(123, $m->foo());
$this->assertEquals($param1, $m->getParam1());
}
public function testNamedMockWithConstructorArgsAndArrayDefs()
{
$m = $this->container->mock(
"MockeryTest_ClassConstructor2[foo]",
array($param1 = new stdClass()),
array("foo" => 123)
);
$this->assertEquals(123, $m->foo());
$this->assertEquals($param1, $m->getParam1());
}
public function testNamedMockWithConstructorArgsWithInternalCallToMockedMethod()
{
$m = $this->container->mock("MockeryTest_ClassConstructor2[foo]", array($param1 = new stdClass()));
$m->shouldReceive("foo")->andReturn(123);
$this->assertEquals(123, $m->bar());
}
public function testNamedMockWithConstructorArgsButNoQuickDefsShouldLeaveConstructorIntact()
{
$m = $this->container->mock("MockeryTest_ClassConstructor2", array($param1 = new stdClass()));
$m->shouldDeferMissing();
$this->assertEquals($param1, $m->getParam1());
}
public function testNamedMockWithShouldDeferMissing()
{
$m = $this->container->mock("MockeryTest_ClassConstructor2", array($param1 = new stdClass()));
$m->shouldDeferMissing();
$this->assertEquals('foo', $m->bar());
$m->shouldReceive("bar")->andReturn(123);
$this->assertEquals(123, $m->bar());
}
/**
* @expectedException BadMethodCallException
*/
public function testNamedMockWithShouldDeferMissingThrowsIfNotAvailable()
{
$m = $this->container->mock("MockeryTest_ClassConstructor2", array($param1 = new stdClass()));
$m->shouldDeferMissing();
$m->foorbar123();
}
public function testMockingAKnownConcreteClassSoMockInheritsClassType()
{
$m = $this->container->mock('stdClass');
$m->shouldReceive('foo')->andReturn('bar');
$this->assertEquals('bar', $m->foo());
$this->assertTrue($m instanceof stdClass);
}
public function testMockingAKnownUserClassSoMockInheritsClassType()
{
$m = $this->container->mock('MockeryTest_TestInheritedType');
$this->assertTrue($m instanceof MockeryTest_TestInheritedType);
}
public function testMockingAConcreteObjectCreatesAPartialWithoutError()
{
$m = $this->container->mock(new stdClass);
$m->shouldReceive('foo')->andReturn('bar');
$this->assertEquals('bar', $m->foo());
$this->assertTrue($m instanceof stdClass);
}
public function testCreatingAPartialAllowsDynamicExpectationsAndPassesThroughUnexpectedMethods()
{
$m = $this->container->mock(new MockeryTestFoo);
$m->shouldReceive('bar')->andReturn('bar');
$this->assertEquals('bar', $m->bar());
$this->assertEquals('foo', $m->foo());
$this->assertTrue($m instanceof MockeryTestFoo);
}
public function testCreatingAPartialAllowsExpectationsToInterceptCallsToImplementedMethods()
{
$m = $this->container->mock(new MockeryTestFoo2);
$m->shouldReceive('bar')->andReturn('baz');
$this->assertEquals('baz', $m->bar());
$this->assertEquals('foo', $m->foo());
$this->assertTrue($m instanceof MockeryTestFoo2);
}
public function testBlockForwardingToPartialObject()
{
$m = $this->container->mock(new MockeryTestBar1, array('foo'=>1, \Mockery\Container::BLOCKS => array('method1')));
$this->assertSame($m, $m->method1());
}
public function testPartialWithArrayDefs()
{
$m = $this->container->mock(new MockeryTestBar1, array('foo'=>1, \Mockery\Container::BLOCKS => array('method1')));
$this->assertEquals(1, $m->foo());
}
public function testPassingClosureAsFinalParameterUsedToDefineExpectations()
{
$m = $this->container->mock('foo', function($m) {
$m->shouldReceive('foo')->once()->andReturn('bar');
});
$this->assertEquals('bar', $m->foo());
}
/**
* @expectedException \Mockery\Exception
*/
public function testMockingAKnownConcreteFinalClassThrowsErrors_OnlyPartialMocksCanMockFinalElements()
{
$m = $this->container->mock('MockeryFoo3');
}
public function testMockingAKnownConcreteClassWithFinalMethodsThrowsNoException()
{
$m = $this->container->mock('MockeryFoo4');
}
/**
* @group finalclass
*/
public function testFinalClassesCanBePartialMocks()
{
$m = $this->container->mock(new MockeryFoo3);
$m->shouldReceive('foo')->andReturn('baz');
$this->assertEquals('baz', $m->foo());
$this->assertFalse($m instanceof MockeryFoo3);
}
public function testSplClassWithFinalMethodsCanBeMocked()
{
$m = $this->container->mock('SplFileInfo');
$m->shouldReceive('foo')->andReturn('baz');
$this->assertEquals('baz', $m->foo());
$this->assertTrue($m instanceof SplFileInfo);
}
public function testClassesWithFinalMethodsCanBeProxyPartialMocks()
{
$m = $this->container->mock(new MockeryFoo4);
$m->shouldReceive('foo')->andReturn('baz');
$this->assertEquals('baz', $m->foo());
$this->assertEquals('bar', $m->bar());
$this->assertTrue($m instanceof MockeryFoo4);
}
public function testClassesWithFinalMethodsCanBeProperPartialMocks()
{
$m = $this->container->mock('MockeryFoo4[bar]');
$m->shouldReceive('bar')->andReturn('baz');
$this->assertEquals('baz', $m->foo());
$this->assertEquals('baz', $m->bar());
$this->assertTrue($m instanceof MockeryFoo4);
}
public function testClassesWithFinalMethodsCanBeProperPartialMocksButFinalMethodsNotPartialed()
{
$m = $this->container->mock('MockeryFoo4[foo]');
$m->shouldReceive('foo')->andReturn('foo');
$this->assertEquals('baz', $m->foo()); // partial expectation ignored - will fail callcount assertion
$this->assertTrue($m instanceof MockeryFoo4);
}
public function testSplfileinfoClassMockPassesUserExpectations()
{
$file = $this->container->mock('SplFileInfo[getFilename,getPathname,getExtension,getMTime]', array(__FILE__));
$file->shouldReceive('getFilename')->once()->andReturn('foo');
$file->shouldReceive('getPathname')->once()->andReturn('path/to/foo');
$file->shouldReceive('getExtension')->once()->andReturn('css');
$file->shouldReceive('getMTime')->once()->andReturn(time());
}
public function testCanMockInterface()
{
$m = $this->container->mock('MockeryTest_Interface');
$this->assertTrue($m instanceof MockeryTest_Interface);
}
public function testCanMockSpl()
{
$m = $this->container->mock('\\SplFixedArray');
$this->assertTrue($m instanceof \SplFixedArray);
}
public function testCanMockInterfaceWithAbstractMethod()
{
$m = $this->container->mock('MockeryTest_InterfaceWithAbstractMethod');
$this->assertTrue($m instanceof MockeryTest_InterfaceWithAbstractMethod);
$m->shouldReceive('foo')->andReturn(1);
$this->assertEquals(1, $m->foo());
}
public function testCanMockAbstractWithAbstractProtectedMethod()
{
$m = $this->container->mock('MockeryTest_AbstractWithAbstractMethod');
$this->assertTrue($m instanceof MockeryTest_AbstractWithAbstractMethod);
}
public function testCanMockInterfaceWithPublicStaticMethod()
{
$m = $this->container->mock('MockeryTest_InterfaceWithPublicStaticMethod');
$this->assertTrue($m instanceof MockeryTest_InterfaceWithPublicStaticMethod);
}
public function testCanMockClassWithConstructor()
{
$m = $this->container->mock('MockeryTest_ClassConstructor');
$this->assertTrue($m instanceof MockeryTest_ClassConstructor);
}
public function testCanMockClassWithConstructorNeedingClassArgs()
{
$m = $this->container->mock('MockeryTest_ClassConstructor2');
$this->assertTrue($m instanceof MockeryTest_ClassConstructor2);
}
/**
* @group partial
*/
public function testCanPartiallyMockANormalClass()
{
$m = $this->container->mock('MockeryTest_PartialNormalClass[foo]');
$this->assertTrue($m instanceof MockeryTest_PartialNormalClass);
$m->shouldReceive('foo')->andReturn('cba');
$this->assertEquals('abc', $m->bar());
$this->assertEquals('cba', $m->foo());
}
/**
* @group partial
*/
public function testCanPartiallyMockAnAbstractClass()
{
$m = $this->container->mock('MockeryTest_PartialAbstractClass[foo]');
$this->assertTrue($m instanceof MockeryTest_PartialAbstractClass);
$m->shouldReceive('foo')->andReturn('cba');
$this->assertEquals('abc', $m->bar());
$this->assertEquals('cba', $m->foo());
}
/**
* @group partial
*/
public function testCanPartiallyMockANormalClassWith2Methods()
{
$m = $this->container->mock('MockeryTest_PartialNormalClass2[foo, baz]');
$this->assertTrue($m instanceof MockeryTest_PartialNormalClass2);
$m->shouldReceive('foo')->andReturn('cba');
$m->shouldReceive('baz')->andReturn('cba');
$this->assertEquals('abc', $m->bar());
$this->assertEquals('cba', $m->foo());
$this->assertEquals('cba', $m->baz());
}
/**
* @group partial
*/
public function testCanPartiallyMockAnAbstractClassWith2Methods()
{
$m = $this->container->mock('MockeryTest_PartialAbstractClass2[foo,baz]');
$this->assertTrue($m instanceof MockeryTest_PartialAbstractClass2);
$m->shouldReceive('foo')->andReturn('cba');
$m->shouldReceive('baz')->andReturn('cba');
$this->assertEquals('abc', $m->bar());
$this->assertEquals('cba', $m->foo());
$this->assertEquals('cba', $m->baz());
}
/**
* @expectedException \Mockery\Exception
* @group partial
*/
public function testThrowsExceptionIfSettingExpectationForNonMockedMethodOfPartialMock()
{
$this->markTestSkipped('For now...');
$m = $this->container->mock('MockeryTest_PartialNormalClass[foo]');
$this->assertTrue($m instanceof MockeryTest_PartialNormalClass);
$m->shouldReceive('bar')->andReturn('cba');
}
/**
* @expectedException \Mockery\Exception
* @group partial
*/
public function testThrowsExceptionIfClassOrInterfaceForPartialMockDoesNotExist()
{
$m = $this->container->mock('MockeryTest_PartialNormalClassXYZ[foo]');
}
/**
* @group issue/4
*/
public function testCanMockClassContainingMagicCallMethod()
{
$m = $this->container->mock('MockeryTest_Call1');
$this->assertTrue($m instanceof MockeryTest_Call1);
}
/**
* @group issue/4
*/
public function testCanMockClassContainingMagicCallMethodWithoutTypeHinting()
{
$m = $this->container->mock('MockeryTest_Call2');
$this->assertTrue($m instanceof MockeryTest_Call2);
}
/**
* @group issue/14
*/
public function testCanMockClassContainingAPublicWakeupMethod()
{
$m = $this->container->mock('MockeryTest_Wakeup1');
$this->assertTrue($m instanceof MockeryTest_Wakeup1);
}
/**
* @group issue/18
*/
public function testCanMockClassUsingMagicCallMethodsInPlaceOfNormalMethods()
{
$m = \Mockery::mock('Gateway');
$m->shouldReceive('iDoSomethingReallyCoolHere');
$m->iDoSomethingReallyCoolHere();
}
/**
* @group issue/18
*/
public function testCanPartialMockObjectUsingMagicCallMethodsInPlaceOfNormalMethods()
{
$m = \Mockery::mock(new Gateway);
$m->shouldReceive('iDoSomethingReallyCoolHere');
$m->iDoSomethingReallyCoolHere();
}
/**
* @group issue/13
*/
public function testCanMockClassWhereMethodHasReferencedParameter()
{
$m = \Mockery::mock(new MockeryTest_MethodParamRef);
}
/**
* @group issue/13
*/
public function testCanPartiallyMockObjectWhereMethodHasReferencedParameter()
{
$m = \Mockery::mock(new MockeryTest_MethodParamRef2);
}
/**
* @group issue/11
*/
public function testMockingAKnownConcreteClassCanBeGrantedAnArbitraryClassType()
{
$m = $this->container->mock('alias:MyNamespace\MyClass');
$m->shouldReceive('foo')->andReturn('bar');
$this->assertEquals('bar', $m->foo());
$this->assertTrue($m instanceof MyNamespace\MyClass);
}
/**
* @group issue/15
*/
public function testCanMockMultipleInterfaces()
{
$m = $this->container->mock('MockeryTest_Interface1, MockeryTest_Interface2');
$this->assertTrue($m instanceof MockeryTest_Interface1);
$this->assertTrue($m instanceof MockeryTest_Interface2);
}
/**
* @expectedException \Mockery\Exception
*/
public function testMockingMultipleInterfacesThrowsExceptionWhenGivenNonExistingClassOrInterface()
{
$m = $this->container->mock('DoesNotExist, MockeryTest_Interface2');
$this->assertTrue($m instanceof MockeryTest_Interface1);
$this->assertTrue($m instanceof MockeryTest_Interface2);
}
/**
* @group issue/15
*/
public function testCanMockClassAndApplyMultipleInterfaces()
{
$m = $this->container->mock('MockeryTestFoo, MockeryTest_Interface1, MockeryTest_Interface2');
$this->assertTrue($m instanceof MockeryTestFoo);
$this->assertTrue($m instanceof MockeryTest_Interface1);
$this->assertTrue($m instanceof MockeryTest_Interface2);
}
/**
* @group issue/7
*
* Noted: We could complicate internally, but a blind class is better built
* with a real class noted up front (stdClass is a perfect choice it is
* behaviourless). Fine, it's a muddle - but we need to draw a line somewhere.
*/
public function testCanMockStaticMethods()
{
\Mockery::setContainer($this->container);
$m = $this->container->mock('alias:MyNamespace\MyClass2');
$m->shouldReceive('staticFoo')->andReturn('bar');
$this->assertEquals('bar', \MyNameSpace\MyClass2::staticFoo());
\Mockery::resetContainer();
}
/**
* @group issue/7
* @expectedException \Mockery\CountValidator\Exception
*/
public function testMockedStaticMethodsObeyMethodCounting()
{
\Mockery::setContainer($this->container);
$m = $this->container->mock('alias:MyNamespace\MyClass3');
$m->shouldReceive('staticFoo')->once()->andReturn('bar');
$this->container->mockery_verify();
\Mockery::resetContainer();
}
/**
* @expectedException BadMethodCallException
*/
public function testMockedStaticThrowsExceptionWhenMethodDoesNotExist(){
\Mockery::setContainer($this->container);
$m = $this->container->mock('alias:MyNamespace\StaticNoMethod');
$this->assertEquals('bar', \MyNameSpace\StaticNoMethod::staticFoo());
\Mockery::resetContainer();
}
/**
* @group issue/17
*/
public function testMockingAllowsPublicPropertyStubbingOnRealClass()
{
$m = $this->container->mock('MockeryTestFoo');
$m->foo = 'bar';
$this->assertEquals('bar', $m->foo);
//$this->assertTrue(array_key_exists('foo', $m->mockery_getMockableProperties()));
}
/**
* @group issue/17
*/
public function testMockingAllowsPublicPropertyStubbingOnNamedMock()
{
$m = $this->container->mock('Foo');
$m->foo = 'bar';
$this->assertEquals('bar', $m->foo);
//$this->assertTrue(array_key_exists('foo', $m->mockery_getMockableProperties()));
}
/**
* @group issue/17
*/
public function testMockingAllowsPublicPropertyStubbingOnPartials()
{
$m = $this->container->mock(new stdClass);
$m->foo = 'bar';
$this->assertEquals('bar', $m->foo);
//$this->assertTrue(array_key_exists('foo', $m->mockery_getMockableProperties()));
}
/**
* @group issue/17
*/
public function testMockingDoesNotStubNonStubbedPropertiesOnPartials()
{
$m = $this->container->mock(new MockeryTest_ExistingProperty);
$this->assertEquals('bar', $m->foo);
$this->assertFalse(array_key_exists('foo', $m->mockery_getMockableProperties()));
}
public function testCreationOfInstanceMock()
{
$m = $this->container->mock('overload:MyNamespace\MyClass4');
$this->assertTrue($m instanceof \MyNamespace\MyClass4);
}
public function testInstantiationOfInstanceMock()
{
\Mockery::setContainer($this->container);
$m = $this->container->mock('overload:MyNamespace\MyClass5');
$instance = new \MyNamespace\MyClass5;
$this->assertTrue($instance instanceof \MyNamespace\MyClass5);
\Mockery::resetContainer();
}
public function testInstantiationOfInstanceMockImportsExpectations()
{
\Mockery::setContainer($this->container);
$m = $this->container->mock('overload:MyNamespace\MyClass6');
$m->shouldReceive('foo')->andReturn('bar');
$instance = new \MyNamespace\MyClass6;
$this->assertEquals('bar', $instance->foo());
\Mockery::resetContainer();
}
public function testInstantiationOfInstanceMocksIgnoresVerificationOfOriginMock()
{
\Mockery::setContainer($this->container);
$m = $this->container->mock('overload:MyNamespace\MyClass7');
$m->shouldReceive('foo')->once()->andReturn('bar');
$this->container->mockery_verify();
\Mockery::resetContainer(); //should not throw an exception
}
/**
* @expectedException \Mockery\CountValidator\Exception
*/
public function testInstantiationOfInstanceMocksAddsThemToContainerForVerification()
{
\Mockery::setContainer($this->container);
$m = $this->container->mock('overload:MyNamespace\MyClass8');
$m->shouldReceive('foo')->once();
$instance = new \MyNamespace\MyClass8;
$this->container->mockery_verify();
\Mockery::resetContainer();
}
public function testInstantiationOfInstanceMocksDoesNotHaveCountValidatorCrossover()
{
\Mockery::setContainer($this->container);
$m = $this->container->mock('overload:MyNamespace\MyClass9');
$m->shouldReceive('foo')->once();
$instance1 = new \MyNamespace\MyClass9;
$instance2 = new \MyNamespace\MyClass9;
$instance1->foo();
$instance2->foo();
$this->container->mockery_verify();
\Mockery::resetContainer();
}
/**
* @expectedException \Mockery\CountValidator\Exception
*/
public function testInstantiationOfInstanceMocksDoesNotHaveCountValidatorCrossover2()
{
\Mockery::setContainer($this->container);
$m = $this->container->mock('overload:MyNamespace\MyClass10');
$m->shouldReceive('foo')->once();
$instance1 = new \MyNamespace\MyClass10;
$instance2 = new \MyNamespace\MyClass10;
$instance1->foo();
$this->container->mockery_verify();
\Mockery::resetContainer();
}
public function testMethodParamsPassedByReferenceHaveReferencePreserved()
{
$m = $this->container->mock('MockeryTestRef1');
$m->shouldReceive('foo')->with(
\Mockery::on(function(&$a) {$a += 1;return true;}),
\Mockery::any()
);
$a = 1;
$b = 1;
$m->foo($a, $b);
$this->assertEquals(2, $a);
$this->assertEquals(1, $b);
}
/**
* Meant to test the same logic as
* testCanOverrideExpectedParametersOfExtensionPHPClassesToPreserveRefs,
* but:
* - doesn't require an extension
* - isn't actually known to be used
*/
public function testCanOverrideExpectedParametersOfInternalPHPClassesToPreserveRefs()
{
\Mockery::getConfiguration()->setInternalClassMethodParamMap(
'DateTime', 'modify', array('&$string')
);
// @ used to avoid E_STRICT for incompatible signature
@$m = $this->container->mock('DateTime');
$this->assertInstanceOf("Mockery\MockInterface", $m, "Mocking failed, remove @ error suppresion to debug");
$m->shouldReceive('modify')->with(
\Mockery::on(function(&$string) {$string = 'foo'; return true;})
);
$data ='bar';
$m->modify($data);
$this->assertEquals('foo', $data);
$this->container->mockery_verify();
\Mockery::resetContainer();
\Mockery::getConfiguration()->resetInternalClassMethodParamMaps();
}
/**
* Real world version of
* testCanOverrideExpectedParametersOfInternalPHPClassesToPreserveRefs
*/
public function testCanOverrideExpectedParametersOfExtensionPHPClassesToPreserveRefs()
{
if (!class_exists('MongoCollection', false)) $this->markTestSkipped('ext/mongo not installed');
\Mockery::getConfiguration()->setInternalClassMethodParamMap(
'MongoCollection', 'insert', array('&$data', '$options')
);
// @ used to avoid E_STRICT for incompatible signature
@$m = $this->container->mock('MongoCollection');
$this->assertInstanceOf("Mockery\MockInterface", $m, "Mocking failed, remove @ error suppresion to debug");
$m->shouldReceive('insert')->with(
\Mockery::on(function(&$data) {$data['_id'] = 123; return true;}),
\Mockery::type('array')
);
$data = array('a'=>1,'b'=>2);
$m->insert($data, array());
$this->assertTrue(isset($data['_id']));
$this->assertEquals(123, $data['_id']);
$this->container->mockery_verify();
\Mockery::resetContainer();
\Mockery::getConfiguration()->resetInternalClassMethodParamMaps();
}
public function testCanCreateNonOverridenInstanceOfPreviouslyOverridenInternalClasses()
{
\Mockery::getConfiguration()->setInternalClassMethodParamMap(
'DateTime', 'modify', array('&$string')
);
// @ used to avoid E_STRICT for incompatible signature
@$m = $this->container->mock('DateTime');
$this->assertInstanceOf("Mockery\MockInterface", $m, "Mocking failed, remove @ error suppresion to debug");
$rc = new ReflectionClass($m);
$rm = $rc->getMethod('modify');
$params = $rm->getParameters();
$this->assertTrue($params[0]->isPassedByReference());
\Mockery::getConfiguration()->resetInternalClassMethodParamMaps();
$m = $this->container->mock('DateTime');
$this->assertInstanceOf("Mockery\MockInterface", $m, "Mocking failed");
$rc = new ReflectionClass($m);
$rm = $rc->getMethod('modify');
$params = $rm->getParameters();
$this->assertFalse($params[0]->isPassedByReference());
\Mockery::resetContainer();
\Mockery::getConfiguration()->resetInternalClassMethodParamMaps();
}
/**
* @group abstract
*/
public function testCanMockAbstractClassWithAbstractPublicMethod()
{
$m = $this->container->mock('MockeryTest_AbstractWithAbstractPublicMethod');
$this->assertTrue($m instanceof MockeryTest_AbstractWithAbstractPublicMethod);
}
/**
* @issue issue/21
*/
public function testClassDeclaringIssetDoesNotThrowException()
{
\Mockery::setContainer($this->container);
$m = $this->container->mock('MockeryTest_IssetMethod');
$this->container->mockery_verify();
\Mockery::resetContainer();
}
/**
* @issue issue/21
*/
public function testClassDeclaringUnsetDoesNotThrowException()
{
\Mockery::setContainer($this->container);
$m = $this->container->mock('MockeryTest_UnsetMethod');
$this->container->mockery_verify();
\Mockery::resetContainer();
}
/**
* @issue issue/35
*/
public function testCallingSelfOnlyReturnsLastMockCreatedOrCurrentMockBeingProgrammedSinceTheyAreOneAndTheSame()
{
\Mockery::setContainer($this->container);
$m = $this->container->mock('MockeryTestFoo');
$this->assertFalse($this->container->self() instanceof MockeryTestFoo2);
//$m = $this->container->mock('MockeryTestFoo2');
//$this->assertTrue($this->container->self() instanceof MockeryTestFoo2);
//$m = $this->container->mock('MockeryTestFoo');
//$this->assertFalse(\Mockery::self() instanceof MockeryTestFoo2);
//$this->assertTrue(\Mockery::self() instanceof MockeryTestFoo);
\Mockery::resetContainer();
}
/**
* @issue issue/89
*/
public function testCreatingMockOfClassWithExistingToStringMethodDoesntCreateClassWithTwoToStringMethods()
{
\Mockery::setContainer($this->container);
$m = $this->container->mock('MockeryTest_WithToString'); // this would fatal
$m->shouldReceive("__toString")->andReturn('dave');
$this->assertEquals("dave", "$m");
}
public function testGetExpectationCount_freshContainer()
{
$this->assertEquals(0, $this->container->mockery_getExpectationCount());
}
public function testGetExpectationCount_simplestMock()
{
$m = $this->container->mock();
$m->shouldReceive('foo')->andReturn('bar');
$this->assertEquals(1, $this->container->mockery_getExpectationCount());
}
public function testMethodsReturningParamsByReferenceDoesNotErrorOut()
{
$this->container->mock('MockeryTest_ReturnByRef');
$mock = $this->container->mock('MockeryTest_ReturnByRef');
$mock->shouldReceive("get")->andReturn($var = 123);
$this->assertSame($var, $mock->get());
}
public function testMockCallableTypeHint()
{
if(PHP_VERSION_ID >= 50400) {
$this->container->mock('MockeryTest_MockCallableTypeHint');
}
}
public function testCanMockClassWithReservedWordMethod()
{
if (!extension_loaded("redis")) {
$this->markTestSkipped(
"phpredis not installed"
);;
}
$this->container->mock("Redis");
}
public function testUndeclaredClassIsDeclared()
{
$this->assertFalse(class_exists("BlahBlah"));
$mock = $this->container->mock("BlahBlah");
$this->assertInstanceOf("BlahBlah", $mock);
}
public function testUndeclaredClassWithNamespaceIsDeclared()
{
$this->assertFalse(class_exists("MyClasses\Blah\BlahBlah"));
$mock = $this->container->mock("MyClasses\Blah\BlahBlah");
$this->assertInstanceOf("MyClasses\Blah\BlahBlah", $mock);
}
public function testUndeclaredClassWithNamespaceIncludingLeadingOperatorIsDeclared()
{
$this->assertFalse(class_exists("\MyClasses\DaveBlah\BlahBlah"));
$mock = $this->container->mock("\MyClasses\DaveBlah\BlahBlah");
$this->assertInstanceOf("\MyClasses\DaveBlah\BlahBlah", $mock);
}
public function testMockingPhpredisExtensionClassWorks()
{
if (!class_exists('Redis')) {
$this->markTestSkipped('PHPRedis extension required for this test');
}
$m = $this->container->mock('Redis');
}
public function testIssetMappingUsingProxiedPartials_CheckNoExceptionThrown()
{
$var = $this->container->mock(new MockeryTestIsset_Bar());
$mock = $this->container->mock(new MockeryTestIsset_Foo($var));
$mock->shouldReceive('bar')->once();
$mock->bar();
$this->container->mockery_teardown(); // closed by teardown()
}
/**
* @group traversable1
*/
public function testCanMockInterfacesExtendingTraversable()
{
$mock = $this->container->mock('MockeryTest_InterfaceWithTraversable');
$this->assertInstanceOf('MockeryTest_InterfaceWithTraversable', $mock);
$this->assertInstanceOf('ArrayAccess', $mock);
$this->assertInstanceOf('Countable', $mock);
$this->assertInstanceOf('Traversable', $mock);
}
/**
* @group traversable2
*/
public function testCanMockInterfacesAlongsideTraversable()
{
$mock = $this->container->mock('stdClass, ArrayAccess, Countable, Traversable');
$this->assertInstanceOf('stdClass', $mock);
$this->assertInstanceOf('ArrayAccess', $mock);
$this->assertInstanceOf('Countable', $mock);
$this->assertInstanceOf('Traversable', $mock);
}
public function testInterfacesCanHaveAssertions()
{
\Mockery::setContainer($this->container);
$m = $this->container->mock('stdClass, ArrayAccess, Countable, Traversable');
$m->shouldReceive('foo')->once();
$m->foo();
$this->container->mockery_verify();
\Mockery::resetContainer();
}
public function testMockingIteratorAggregateDoesNotImplementIterator()
{
$mock = $this->container->mock('MockeryTest_ImplementsIteratorAggregate');
$this->assertInstanceOf('IteratorAggregate', $mock);
$this->assertInstanceOf('Traversable', $mock);
$this->assertNotInstanceOf('Iterator', $mock);
}
public function testMockingInterfaceThatExtendsIteratorDoesNotImplementIterator()
{
$mock = $this->container->mock('MockeryTest_InterfaceThatExtendsIterator');
$this->assertInstanceOf('Iterator', $mock);
$this->assertInstanceOf('Traversable', $mock);
}
public function testMockingInterfaceThatExtendsIteratorAggregateDoesNotImplementIterator()
{
$mock = $this->container->mock('MockeryTest_InterfaceThatExtendsIteratorAggregate');
$this->assertInstanceOf('IteratorAggregate', $mock);
$this->assertInstanceOf('Traversable', $mock);
$this->assertNotInstanceOf('Iterator', $mock);
}
public function testMockingIteratorAggregateDoesNotImplementIteratorAlongside()
{
$mock = $this->container->mock('IteratorAggregate');
$this->assertInstanceOf('IteratorAggregate', $mock);
$this->assertInstanceOf('Traversable', $mock);
$this->assertNotInstanceOf('Iterator', $mock);
}
public function testMockingIteratorDoesNotImplementIteratorAlongside()
{
$mock = $this->container->mock('Iterator');
$this->assertInstanceOf('Iterator', $mock);
$this->assertInstanceOf('Traversable', $mock);
}
public function testMockingIteratorDoesNotImplementIterator()
{
$mock = $this->container->mock('MockeryTest_ImplementsIterator');
$this->assertInstanceOf('Iterator', $mock);
$this->assertInstanceOf('Traversable', $mock);
}
public function testMockeryCloseForIllegalIssetFileInclude()
{
$m = \Mockery::mock('StdClass')
->shouldReceive('get')
->andReturn(false)
->getMock();
$m->get();
\Mockery::close();
}
public function testMockeryShouldDistinguishBetweenConstructorParamsAndClosures()
{
$obj = new MockeryTestFoo();
$mock = $this->container->mock('MockeryTest_ClassMultipleConstructorParams[dave]',
array( &$obj, 'foo' ));
}
/** @group nette */
public function testMockeryShouldNotMockCallstaticMagicMethod()
{
$mock = $this->container->mock('MockeryTest_CallStatic');
}
/**
* @issue issue/139
*/
public function testCanMockClassWithOldStyleConstructorAndArguments()
{
$mock = $this->container->mock('MockeryTest_OldStyleConstructor');
}
/** @group issue/144 */
public function testMockeryShouldInterpretEmptyArrayAsConstructorArgs()
{
$mock = $this->container->mock("EmptyConstructorTest", array());
$this->assertSame(0, $mock->numberOfConstructorArgs);
}
/** @group issue/144 */
public function testMockeryShouldCallConstructorByDefaultWhenRequestingPartials()
{
$mock = $this->container->mock("EmptyConstructorTest[foo]");
$this->assertSame(0, $mock->numberOfConstructorArgs);
}
/** @group issue/158 */
public function testMockeryShouldRespectInterfaceWithMethodParamSelf()
{
$this->container->mock('MockeryTest_InterfaceWithMethodParamSelf');
}
/** @group issue/162 */
public function testMockeryDoesntTryAndMockLowercaseToString()
{
$this->container->mock('MockeryTest_Lowercase_ToString');
}
/** @group issue/175 */
public function testExistingStaticMethodMocking()
{
\Mockery::setContainer($this->container);
$mock = $this->container->mock('MockeryTest_PartialStatic[mockMe]');
$mock->shouldReceive('mockMe')->with(5)->andReturn(10);
$this->assertEquals(10, $mock::mockMe(5));
$this->assertEquals(3, $mock::keepMe(3));
}
/**
* @group issue/154
* @expectedException InvalidArgumentException
* @expectedExceptionMessage protectedMethod() cannot be mocked as it a protected method and mocking protected methods is not allowed for this mock
*/
public function testShouldThrowIfAttemptingToStubProtectedMethod()
{
$mock = $this->container->mock('MockeryTest_WithProtectedAndPrivate');
$mock->shouldReceive("protectedMethod");
}
/**
* @group issue/154
* @expectedException InvalidArgumentException
* @expectedExceptionMessage privateMethod() cannot be mocked as it is a private method
*/
public function testShouldThrowIfAttemptingToStubPrivateMethod()
{
$mock = $this->container->mock('MockeryTest_WithProtectedAndPrivate');
$mock->shouldReceive("privateMethod");
}
public function testWakeupMagicIsNotMockedToAllowSerialisationInstanceHack()
{
$mock = $this->container->mock('DateTime');
}
/**
* @group issue/154
*/
public function testCanMockMethodsWithRequiredParamsThatHaveDefaultValues()
{
$mock = $this->container->mock('MockeryTest_MethodWithRequiredParamWithDefaultValue');
$mock->shouldIgnoreMissing();
$mock->foo(null, 123);
}
/**
* @test
* @group issue/294
* @expectedException Mockery\Exception\RuntimeException
* @expectedExceptionMessage Could not load mock DateTime, class already exists
*/
public function testThrowsWhenNamedMockClassExistsAndIsNotMockery()
{
$builder = new MockConfigurationBuilder();
$builder->setName("DateTime");
$mock = $this->container->mock($builder);
}
}
class MockeryTest_CallStatic {
public static function __callStatic($method, $args){}
}
class MockeryTest_ClassMultipleConstructorParams {
public function __construct($a, $b) {}
public function dave() {}
}
interface MockeryTest_InterfaceWithTraversable extends \ArrayAccess, \Traversable, \Countable {
public function self();
}
class MockeryTestIsset_Bar {
public function doSomething() {}
}
class MockeryTestIsset_Foo {
private $var;
public function __construct($var) {
$this->var = $var;
}
public function __get($name) {
$this->var->doSomething();
}
public function __isset($name) {
return (bool) strlen($this->__get($name));
}
}
class MockeryTest_IssetMethod
{
protected $_properties = array();
public function __construct() {}
public function __isset($property) {
return isset($this->_properties[$property]);
}
}
class MockeryTest_UnsetMethod
{
protected $_properties = array();
public function __construct() {}
public function __unset($property) {
unset($this->_properties[$property]);
}
}
class MockeryTestFoo {
public function foo() { return 'foo'; }
}
class MockeryTestFoo2 {
public function foo() { return 'foo'; }
public function bar() { return 'bar'; }
}
final class MockeryFoo3 {
public function foo() { return 'baz'; }
}
class MockeryFoo4 {
final public function foo() { return 'baz'; }
public function bar() { return 'bar'; }
}
interface MockeryTest_Interface {}
interface MockeryTest_Interface1 {}
interface MockeryTest_Interface2 {}
interface MockeryTest_InterfaceWithAbstractMethod
{
public function set();
}
interface MockeryTest_InterfaceWithPublicStaticMethod
{
public static function self();
}
abstract class MockeryTest_AbstractWithAbstractMethod
{
abstract protected function set();
}
class MockeryTest_WithProtectedAndPrivate
{
protected function protectedMethod() {}
private function privateMethod() {}
}
class MockeryTest_ClassConstructor {
public function __construct($param1) {}
}
class MockeryTest_ClassConstructor2 {
protected $param1;
public function __construct(stdClass $param1) { $this->param1 = $param1; }
public function getParam1() { return $this->param1; }
public function foo() { return 'foo'; }
public function bar() { return $this->foo(); }
}
class MockeryTest_Call1 {
public function __call($method, array $params) {}
}
class MockeryTest_Call2 {
public function __call($method, $params) {}
}
class MockeryTest_Wakeup1 {
public function __construct() {}
public function __wakeup() {}
}
class MockeryTest_ExistingProperty {
public $foo = 'bar';
}
abstract class MockeryTest_AbstractWithAbstractPublicMethod{
abstract public function foo($a, $b);
}
// issue/18
class SoCool
{
public function iDoSomethingReallyCoolHere()
{
return 3;
}
}
class Gateway
{
public function __call($method, $args)
{
$m = new SoCool();
return call_user_func_array(array($m, $method), $args);
}
}
class MockeryTestBar1 {
public function method1()
{
return $this;
}
}
class MockeryTest_ReturnByRef {
public $i = 0;
public function &get()
{
return $this->$i;
}
}
class MockeryTest_MethodParamRef {
public function method1(&$foo){return true;}
}
class MockeryTest_MethodParamRef2 {
public function method1(&$foo){return true;}
}
class MockeryTestRef1 {
public function foo(&$a, $b) {}
}
class MockeryTest_PartialNormalClass {
public function foo() {return 'abc';}
public function bar() {return 'abc';}
}
abstract class MockeryTest_PartialAbstractClass {
abstract public function foo();
public function bar() {return 'abc';}
}
class MockeryTest_PartialNormalClass2 {
public function foo() {return 'abc';}
public function bar() {return 'abc';}
public function baz() {return 'abc';}
}
abstract class MockeryTest_PartialAbstractClass2 {
abstract public function foo();
public function bar() {return 'abc';}
abstract public function baz();
}
class MockeryTest_TestInheritedType {}
if(PHP_VERSION_ID >= 50400) {
class MockeryTest_MockCallableTypeHint {
public function foo(callable $baz) {$baz();}
public function bar(callable $callback = null) {$callback();}
}
}
class MockeryTest_WithToString {
public function __toString() {}
}
class MockeryTest_ImplementsIteratorAggregate implements \IteratorAggregate {
public function getIterator()
{
return new \ArrayIterator(array());
}
}
class MockeryTest_ImplementsIterator implements \Iterator {
public function rewind(){}
public function current(){}
public function key(){}
public function next(){}
public function valid(){}
}
class MockeryTest_OldStyleConstructor {
public function MockeryTest_OldStyleConstructor($arg) {}
}
class EmptyConstructorTest {
public $numberOfConstructorArgs;
public function __construct()
{
$this->numberOfConstructorArgs = count(func_get_args());
}
public function foo() {
}
}
interface MockeryTest_InterfaceWithMethodParamSelf {
public function foo(self $bar);
}
class MockeryTest_Lowercase_ToString {
public function __tostring() { }
}
class MockeryTest_PartialStatic {
public static function mockMe($a)
{
return $a;
}
public static function keepMe($b)
{
return $b;
}
}
class MockeryTest_MethodWithRequiredParamWithDefaultValue {
public function foo(\DateTime $bar = null, $baz) {}
}
interface MockeryTest_InterfaceThatExtendsIterator extends \Iterator {
public function foo();
}
interface MockeryTest_InterfaceThatExtendsIteratorAggregate extends \IteratorAggregate {
public function foo();
}
|
gpl-2.0
|
tualatin/tailforwindows
|
Tail4WindowsUi.Utils/Converters/VisibilityToInverseBoolConverter.cs
|
1658
|
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace Org.Vs.TailForWin.Ui.Utils.Converters
{
/// <summary>
/// Visibility to inverse bool converter
/// </summary>
[ValueConversion(typeof(Visibility), typeof(bool))]
public class VisibilityToInverseBoolConverter : IValueConverter
{
/// <summary>
/// Convert
/// </summary>
/// <param name="value">Value</param>
/// <param name="targetType">Target type</param>
/// <param name="parameter">Parameter</param>
/// <param name="culture">Culture</param>
/// <returns>Converted value</returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => value is Visibility visibility && visibility != Visibility.Collapsed;
/// <summary>
/// Convert
/// </summary>
/// <param name="value">Value</param>
/// <param name="targetType">Target type</param>
/// <param name="parameter">Parameter</param>
/// <param name="culture">Culture</param>
/// <returns>Converted value</returns>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var flag = false;
if ( value != null )
{
var boolType = value.GetType();
if ( boolType == typeof(bool) )
{
flag = (bool) value;
}
else if ( boolType == typeof(bool?) )
{
var nullable = (bool?) value;
flag = nullable.Value;
}
}
else
{
flag = true;
}
return flag ? Visibility.Visible : Visibility.Collapsed;
}
}
}
|
gpl-2.0
|
palmergs/eunomia-cms
|
app/controllers/api/v1/content_items_controller.rb
|
1408
|
class Api::V1::ContentItemsController < Api::ApiController
def index
@content_items = ContentItem.page(params[:p])
render json: @content_items, meta: {
pagination: {
total_pages: @content_items.total_pages,
current_page: @content_items.current_page
}
}
end
def show
@content_item = ContentItem.find(params[:id])
render json: @content_item
end
def create
@content_item = ContentItem.new(create_content_item_params)
if @content_item.save
render json: @content_item
else
render json: { errors: @content_item.errors.full_messages }, status: :unprocessable_entity
end
end
def update
@content_item = ContentItem.find(params[:id])
if @content_item.update_attributes(update_content_item_params)
render json: @content_item
else
render json: { errors: @content_item.errors.full_messages }, status: :unprocessable_entity
end
end
def destroy
@content_item = ContentItem.find(params[:id])
if @content_item.destroy
render head: :ok
else
render json: {}, status: :unprocessable_entity
end
end
private
def create_content_item_params
params.require(:content_item).permit(:parent_id, :content, :structure_item_id)
end
def update_content_item_params
params.require(:content_item).permit(:parent_id, :content, :structure_item_id)
end
end
|
gpl-2.0
|
vitorluis/SSHClient
|
events/settings_window_events.py
|
2164
|
# -*- coding: utf-8 -*-
import shutil
import settings
from windows.file_export_dialog import FileExportDialog
from model.settings import Settings
from windows.message_box import MessageBox
class SettingsWindowEvents:
# Properties
window = None
builder = None
refresh_list_callback = None
def __init__(self, window, builder, refresh_list_callback):
# Copy the parameters
self.window = window
self.builder = builder
self.refresh_list_callback = refresh_list_callback
def on_btn_save_clicked(self, btn):
# Get the properties
x11_forward = self.builder.get_object("chk_enable_x11")
request_compression = self.builder.get_object("chk_request_compress")
force_ipv4 = self.builder.get_object("radio_force_ipv4")
force_ipv6 = self.builder.get_object("radio_force_ipv6")
# Set the config on Settings
app_settings = Settings()
app_settings.x11_forward = int(x11_forward.get_active())
app_settings.request_compression = int(request_compression.get_active())
app_settings.force_ipv4 = int(force_ipv4.get_active())
app_settings.force_ipv6 = int(force_ipv6.get_active())
# Now, save
if app_settings.save():
self.window.destroy()
else:
# Show message box about error
MessageBox("Error while saving the settings, please try again.")
def on_btn_close_clicked(self, btn):
self.window.destroy()
def on_btn_export_clicked(self, btn):
FileExportDialog()
def on_btn_import_clicked(self, btn):
# Get the FileChooser
file_chooser = self.builder.get_object("file_import_db")
# Get the file
file = file_chooser.get_filename()
# Check if the file is filled
if file is not None:
# Copy the file
shutil.copy(file, settings.DB_FILE)
# Call the callback to reload the list
if self.refresh_list_callback is not None:
self.refresh_list_callback()
# Show the message box
MessageBox("Database imported successfully")
|
gpl-2.0
|
ShengyuanEstate/website
|
wp-content/plugins/realia-paypal/includes/class-realia-paypal-customizations.php
|
617
|
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class Realia_Customizations
*
* @access public
* @package Realia_Paypal/Classes/Customizations
* @return void
*/
class Realia_Paypal_Customizations {
/**
* Initialize customizations
*
* @access public
* @return void
*/
public static function init() {
self::includes();
}
/**
* Include all customizations
*
* @access public
* @return void
*/
public static function includes() {
require_once REALIA_PAYPAL_DIR . 'includes/customizations/class-realia-paypal-customizations-paypal.php';
}
}
Realia_PayPal_Customizations::init();
|
gpl-2.0
|
r03eRt/electroelite_new
|
wp-content/plugins/dnd-shortcodes/admin/core_shortcodes.php
|
8297
|
<?php
/*********** Shortcode: Content Section ************************************************************/
$ABdevDND_shortcodes['section_dd'] = array(
'hide_in_dnd' => true,
'nesting' => '1',
'child' => 'column_dd',
'child_title' => __('Section Column', 'dnd-shortcodes'),
'child_button' => __('Add Column', 'dnd-shortcodes'),
'attributes' => array(
'section_title' => array(
'description' => __('Section Title', 'dnd-shortcodes'),
),
'section_id' => array(
'description' => __('Section ID', 'dnd-shortcodes'),
'info' => __('ID can be used for menu navigation, e.g. #about-us', 'dnd-shortcodes'),
),
'section_intro' => array(
'description' => __('Intro Text', 'dnd-shortcodes'),
),
'section_outro' => array(
'description' => __('Outro Text', 'dnd-shortcodes'),
),
'class' => array(
'description' => __('Class', 'dnd-shortcodes'),
'info' => __('Additional custom classes for custom styling', 'dnd-shortcodes'),
),
'fullwidth' => array(
'description' => __('Fullwidth Content', 'dnd-shortcodes'),
'type' => 'checkbox',
'default' => '0',
),
'no_column_margin' => array(
'description' => __('No Margin on Columns', 'dnd-shortcodes'),
'type' => 'checkbox',
'default' => '0',
),
'equalize_five' => array(
'description' => __('5 Columns Equalize', 'dnd-shortcodes'),
'type' => 'checkbox',
'default' => '0',
'info' => __('Check this if you want 5 columns to be equal width (out of grid, use only 2/12 and 3/12 columns)', 'dnd-shortcodes'),
),
'bg_color' => array(
'description' => __('Background Color', 'dnd-shortcodes'),
'type' => 'color',
),
'bg_image' => array(
'type' => 'image',
'description' => __('Background Image', 'dnd-shortcodes'),
),
'parallax' => array(
'description' => __('Parallax Amount', 'dnd-shortcodes'),
'info' => __('Amout of parallax effect on background image, 0.1 means 10% of scroll amount, 2 means twice of scroll amount, leave blank for no parallax', 'dnd-shortcodes'),
),
'video_bg' => array(
'description' => __('Video Background', 'dnd-shortcodes'),
'type' => 'checkbox',
'default' => '0',
'info' => __('If checked video background will be enabled. Video files should have same name as Background Image, and same path, only different extensions (mp4,webm,ogv files required). You can use Miro Converter to convert files in required formats.', 'dnd-shortcodes'),
),
),
'content' => array(
'default' => 'Columns here',
'description' => __('Content', 'dnd-shortcodes'),
),
'description' => __('Section With Columns', 'dnd-shortcodes'),
'info' => __("Sum of all column's span attributes must be 12", 'dnd-shortcodes' )
);
function ABdevDND_section_dd_shortcode( $attributes, $content = null ) {
extract(shortcode_atts(ABdevDND_extract_attributes('section_dd'), $attributes));
$bg_color_output = ($bg_color!='')?'background-color:'.$bg_color.';' : '';
$bg_image_output = ($bg_image!='')?' data-background_image="'.$bg_image.'"' : '';
$parallax_output = ($parallax!='')?' data-parallax="'.$parallax.'"' : '';
$background_output = ($bg_image!='')?'background-image:url('.$bg_image.');' : '';
$class .= ($parallax!='') ?' dnd-parallax' : '';
$class .= ($video_bg==1) ?' dnd-video-bg' : '';
$class .= ($fullwidth==1) ?' section_body_fullwidth' : '';
$class .= ($no_column_margin==1) ?' section_no_column_margin' : '';
$class .= ($equalize_five==1) ?' section_equalize_5' : '';
$class .= ($section_title!='' || $section_intro!='') ?' section_with_header' : '';
$section_title = ($section_title!='') ? '<h3>'.$section_title.'</h3>' : '';
$section_id = ($section_id!='') ? ' id="'.$section_id.'"' : '';
$section_intro = ($section_intro!='') ? '<p>'.$section_intro.'</p>' : '';
$section_header = ($section_title!='' || $section_intro!='') ? '<header><div class="dnd_container">'.$section_title.$section_intro.'</div></header>' : '';
$section_footer = ($section_outro!='') ? '<footer><div class="dnd_container">'.$section_outro.'</div></footer>' : '';
$video_pi = pathinfo($bg_image);
$video_no_ext_path = dirname($bg_image).'/'.$video_pi['filename'];
$video_out=($video_bg==1) ? '
<video style="position:absolute;top:0;left:0;min-height:100%;min-width:100%;z-index:0;" poster="'.$bg_image.'" loop="1" autoplay="1" preload="metadata" controls="controls">
<source type="video/mp4" src="'.$video_no_ext_path.'.mp4" />
<source type="video/webm" src="'.$video_no_ext_path.'.webm" />
<source type="video/ogg" src="'.$video_no_ext_path.'.ogv" />
</video>
' : '';
return '<section'.$section_id.' class="dnd_section_dd '.$class.'"'.$bg_image_output.$parallax_output.' style="'.$bg_color_output.$background_output.'">
'.$section_header.'
<div class="dnd_section_content"><div class="dnd_container">'.do_shortcode($content).'</div></div>
'.$section_footer.'
'.$video_out.'
</section>';
}
/*********** Shortcode: Content Column ************************************************************/
$ABdevDND_shortcodes['column_dd'] = array(
'nesting' => '1',
'hidden' => '1',
'hide_in_dnd' => true,
'attributes' => array(
'span' => array(
'default' => '1',
'description' => __('Span 1-12 Columns', 'dnd-shortcodes'),
),
'animation' => array(
'default' => '',
'description' => __('Entrance Animation', 'dnd-shortcodes'),
'type' => 'select',
'values' => array(
'' => __('None', 'dnd-shortcodes'),
'flip' => __('Flip', 'dnd-shortcodes'),
'flipInX' => __('Flip In X', 'dnd-shortcodes'),
'flipInY' => __('Flip In Y', 'dnd-shortcodes'),
'fadeIn' => __('Fade In', 'dnd-shortcodes'),
'fadeInUp' => __('Fade In Up', 'dnd-shortcodes'),
'fadeInDown' => __('Fade In Down', 'dnd-shortcodes'),
'fadeInLeft' => __('Fade In Left', 'dnd-shortcodes'),
'fadeInRight' => __('Fade In Right', 'dnd-shortcodes'),
'fadeInUpBig' => __('Fade In Up Big', 'dnd-shortcodes'),
'fadeInDownBig' => __('Fade In Down Big', 'dnd-shortcodes'),
'fadeInLeftBig' => __('Fade In Left Big', 'dnd-shortcodes'),
'fadeInRightBig' => __('Fade In Right Big', 'dnd-shortcodes'),
'slideInLeft' => __('Slide In Left', 'dnd-shortcodes'),
'slideInRight' => __('Slide In Right', 'dnd-shortcodes'),
'bounceIn' => __('Bounce In', 'dnd-shortcodes'),
'bounceInDown' => __('Bounce In Down', 'dnd-shortcodes'),
'bounceInUp' => __('Bounce In Up', 'dnd-shortcodes'),
'bounceInLeft' => __('Bounce In Left', 'dnd-shortcodes'),
'bounceInRight' => __('Bounce In Right', 'dnd-shortcodes'),
'rotateIn' => __('Rotate In', 'dnd-shortcodes'),
'rotateInDownLeft' => __('Rotate In Down Left', 'dnd-shortcodes'),
'rotateInDownRight' => __('Rotate In Down Right', 'dnd-shortcodes'),
'rotateInUpLeft' => __('Rotate In Up Left', 'dnd-shortcodes'),
'rotateInUpRight' => __('Rotate In Up Right', 'dnd-shortcodes'),
'lightSpeedIn' => __('Light Speed In', 'dnd-shortcodes'),
'rollIn' => __('Roll In', 'dnd-shortcodes'),
'flash' => __('Flash', 'dnd-shortcodes'),
'bounce' => __('Bounce', 'dnd-shortcodes'),
'shake' => __('Shake', 'dnd-shortcodes'),
'tada' => __('Tada', 'dnd-shortcodes'),
'swing' => __('Swing', 'dnd-shortcodes'),
'wobble' => __('Wobble', 'dnd-shortcodes'),
'pulse' => __('Pulse', 'dnd-shortcodes'),
),
),
'duration' => array(
'description' => __('Animation Duration (in ms)', 'dnd-shortcodes'),
'default' => '1000',
),
'delay' => array(
'description' => __('Animation Delay (in ms)', 'dnd-shortcodes'),
'default' => '0',
),
'class' => array(
'description' => __('Class', 'dnd-shortcodes'),
'info' => __('Additional custom classes for custom styling', 'dnd-shortcodes'),
),
),
'content' => array(
'description' => __('Column Content', 'dnd-shortcodes'),
),
'description' => __('Column', 'dnd-shortcodes' )
);
function ABdevDND_column_dd_shortcode( $attributes, $content = null ) {
extract(shortcode_atts(ABdevDND_extract_attributes('column_dd'), $attributes));
$parametars_out='';
if($animation!=''){
$class.= ' dnd-animo';
$parametars_out = ' data-animation="'.$animation.'" data-duration="'.$duration.'" data-delay="'.$delay.'"';
}
return '<div class="dnd_column_dd_span'.$span.' '.$class.'"'.$parametars_out.'>'.do_shortcode($content).'</div>';
}
|
gpl-2.0
|
hundren/daydayup
|
chat_db.js
|
3271
|
/**
* Created by coofly on 2014/8/6.
*/
var mysql = require('mysql');
// var db_config = {
// host : 'localhost',
// port : 3306,
// user : 'root',
// password : 'root',
// database : 'dayup'
// };
// var db_config = {
// host : 'dayup.cfpx3bvlkbyh.us-west-2.rds.amazonaws.com',
// port : 3306,
// user : 'root',
// password : 'daydayup',
// database : 'daydayup'
// };
var db_config = {
host : '120.79.153.58',
port : 3306,
user : 'root',
password : 'NUNOCh@XJ2E#De@U&t$36xozMCFhMnGW',
database : 'dayup'
};
if(process.env.QXCHAT_CONFIG) {
var env_config = JSON.parse(process.env.QXCHAT_CONFIG).mysql;
db_config.host = env_config.host;
db_config.port = env_config.port;
db_config.user = env_config.username;
db_config.password = env_config.password;
db_config.database = env_config.db_name;
}
var pool = mysql.createPool({
connectionLimit : 2,
connectTimeout : 10000, // 10s
host : db_config.host,
port : db_config.port,
user : db_config.user,
password : db_config.password,
database : db_config.database,
multipleStatements: true,
charset:'UTF8_GENERAL_CI'
});
//初始化数据库结构
pool.getConnection(function(err, connection){
if (err) throw err;
// create table if it does'nt exist
connection.query(
"CREATE TABLE IF NOT EXISTS `chat_logs` (" +
" `id` int(10) unsigned NOT NULL AUTO_INCREMENT," +
" `name` tinytext NOT NULL," +
" `content` text NOT NULL," +
" `time` datetime NOT NULL," +
" PRIMARY KEY (`time`)," +
" UNIQUE KEY `id` (`id`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;"
);
connection.release();
});
/**
* 释放数据库连接
*/
exports.release = function(connection) {
connection.end(function(error) {
console.log('Connection closed');
});
};
/**
* 执行查询
*/
exports.execQuery = function(options) {
pool.getConnection(function(error, connection) {
if(error) {
console.log('DB-获取数据库连接异常!');
throw error;
}
/*
* connection.query('USE ' + config.db, function(error, results) { if(error) { console.log('DB-选择数据库异常!'); connection.end(); throw error; } });
*/
// 查询参数
var sql = options['sql'];
var args = options['args'];
var handler = options['handler'];
// 执行查询
if(!args) {
// connection.query("SET NAMES utf8;");
var query = connection.query(sql, function(error, results) {
if(error) {
console.log('DB-执行查询语句异常!');
throw error;
}
// 处理结果
handler(results);
});
console.log(query.sql);
} else {
// connection.query("SET NAMES utf8;");
var query = connection.query(sql, args, function(error, results) {
if(error) {
console.log('DB-执行查询语句异常!');
throw error;
}
// 处理结果
handler(results);
});
console.log(query.sql);
}
// 返回连接池
connection.release(function(error) {
if(error) {
console.log('DB-关闭数据库连接异常!');
throw error;
}
});
// callback.apply(null, [err,results[1],fields]);
});
};
|
gpl-2.0
|
fonic/libktorrent
|
src/interfaces/torrentinterface.cpp
|
1616
|
/***************************************************************************
* Copyright (C) 2005 by Joris Guisson *
* joris.guisson@gmail.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 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 "torrentinterface.h"
namespace bt
{
TorrentInterface::TorrentInterface()
{}
TorrentInterface::~TorrentInterface()
{}
}
|
gpl-2.0
|
epicsdeb/rtems-gcc-newlib
|
libstdc++-v3/testsuite/19_diagnostics/runtime_error/what-2.cc
|
1424
|
// 2001-02-26 Benjamin Kosnik <bkoz@redhat.com>
// Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007
// Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.
// This 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
// 19.1 Exception classes
#include <string>
#include <stdexcept>
#include <cstring>
#include <testsuite_hooks.h>
// libstdc++/2089
class fuzzy_logic : public std::runtime_error
{
public:
fuzzy_logic() : std::runtime_error("whoa") { }
};
void test03()
{
bool test __attribute__((unused)) = true;
try
{ throw fuzzy_logic(); }
catch(const fuzzy_logic& obj)
{ VERIFY( std::strcmp("whoa", obj.what()) == 0 ); }
catch(...)
{ VERIFY( false ); }
}
int main(void)
{
test03();
return 0;
}
|
gpl-2.0
|
ThibautShr/ScrumBoard
|
client/app/admin/admin.js
|
220
|
'use strict';
angular.module('scrumBoardApp')
.config(function ($routeProvider) {
$routeProvider
.when('/admin', {
templateUrl: 'app/admin/admin.html',
controller: 'AdminCtrl'
});
});
|
gpl-2.0
|
tongpa/PollSurveyWeb
|
pollandsurvey/service/optionservice.py
|
11072
|
#-*-coding: utf-8 -*-
from datetime import datetime, date
from tgext.pyutilservice import Utility
from tg import expose, flash, require, url, lurl, request, redirect, tmpl_context,validate,response
from pollandsurvey import model
from surveyobject import JsontoObject
import sys
import json
import types
import logging;
from _mysql import result
log = logging.getLogger(__name__);
from tgext.pyutilservice import URLUtility, PasswordType, TypeQuestionProject, extraLog, FixDifficultyLevel
__all__ = ['OptionService']
class OptionService(object):
def __init__(self, mymodel=None):
self.utility = Utility();
self.modules ='CREATESURVEY.OPTIONSERVICE'
if mymodel is None:
self.mymodel = model
self.mymodel = mymodel
def manageOption(self, optionObject=None):
option=self.createOption(optionObject=optionObject) #createOption - New or Update
if option :
self.mapAccessControl(optionObject=optionObject, option=option) #map acc
self.setQuestionGroupAmount(optionObject=optionObject, option=option) #QuestionGroupAmount - poll and not poll
def createOption(self, optionObject=None):
option = optionObject.options
option.random_answer = self.utility.convertToBit(option.random_answer)
option.activate_date = self.utility.startDate(option.activate_date)
option.expire_date = self.utility.finishDate(option.expire_date)
option.show_score = self.utility.convertToBit(option.show_score)
option.show_navigator = self.utility.convertToBit(option.show_navigator)
option.id_question_option = self.utility.setIfEmpty(option.id_question_option)
if (self.utility.isEmpty(optionObject.id_question_option)):
option.save()
else :
option.updateall()
return option
def setQuestionGroupAmount(self, optionObject=None, option=None):
if str(optionObject.project_type) == str(TypeQuestionProject.poll.value) : #poll
self.mapPollQuestionGroupAmount(optionObject=optionObject, option=option)
else: #not poll , map question, set question level amount
self.mapQuestionGroupAmount(optionObject=optionObject, option=option)
#poll - One group
def mapPollQuestionGroupAmount(self, optionObject=None, option=None):
numberquestiondata = model.NumberQuestionGroup.getByOptionFirst(optionid=option.id_question_option);
group_project = model.QuestionGroup.getGroupByProject(projectid=option.id_question_project);
groupamount = model.NumberQuestionGroup();
groupamount.id_question_group_amount = None;
if(numberquestiondata) :
groupamount.id_question_group_amount = numberquestiondata.id_question_group_amount
groupamount.id_question_option = option.id_question_option
groupamount.id_question_group = group_project.id_question_group
groupamount.amount = optionObject.use_question_no
groupamount.updateall()
#not poll - multi group question
def mapQuestionGroupAmount(self, optionObject=None, option=None):
getGroupQuestion = model.QuestionGroup.getByProject(projectid = optionObject.id_question_project)
if optionObject.number_question :
for groupQuestion in getGroupQuestion :
self.ManageGroupAmount(idquestiongroup=groupQuestion.id_question_group,numquestiondata=optionObject.number_question ,idoption=option.id_question_option);
else:
numberquestiondata = model.NumberQuestionGroup.getByOptionFirst(option.id_question_option);
if (not numberquestiondata) : #add
QuestionGroup = model.QuestionGroup.getByProject(option.id_question_project);
for question_group in QuestionGroup:
groupamount = model.NumberQuestionGroup();
groupamount.id_question_group_amount = None;
groupamount.id_question_option = option.id_question_option;
groupamount.id_question_group = question_group.id_question_group;
groupamount.amount = len(question_group.questions);
groupamount.save()
if(groupamount):
getNumberQuestion, total = model.QuestionGroup.getAmountSummaryForGrouping(idproject = option.id_question_project, idoption=option.id_question_option)
NumberQuestion=[]
for num in getNumberQuestion :
if(str(groupamount.id_question_group) == str(num['id_question_group'])):
if(num['count_difficulty_level'] != 0):
NumberQuestion.append({'id_question_level_amount':None,
'id_fix_difficulty_level': num['id_fix_difficulty_level'],
'select_value' : num['count_difficulty_level']
})
self.manamgeLevelAmount(groupAmount=groupamount, NumberQuestionObject=NumberQuestion)
def ManageGroupAmount(self, idquestiongroup=None, numquestiondata=None, idoption=None):
groupamount = model.NumberQuestionGroup();
summary_select=0
idgroupamount=None
NumberQuestion=[]
for numquestion in numquestiondata:
if (numquestion['id_question_group_amount'] == 0):
numquestion['id_question_group_amount']=None
if (str(numquestion['id_question_group']) == str(idquestiongroup)):
if(numquestion['count_difficulty_level'] != 0):
summary_select+=numquestion['select_value']
idgroupamount=numquestion['id_question_group_amount']
NumberQuestion.append({'id_question_level_amount':numquestion['id_question_level_amount'],
'id_fix_difficulty_level': numquestion['id_fix_difficulty_level'],
'select_value' : numquestion['select_value']
})
groupamount.id_question_group_amount=idgroupamount
groupamount.id_question_option=idoption
groupamount.id_question_group=idquestiongroup
groupamount.amount=summary_select
if(not self.utility.setIfEmpty(idgroupamount)):
groupamount.save()
else:
groupamount.updateall()
if(groupamount):
self.manamgeLevelAmount(groupAmount=groupamount, NumberQuestionObject=NumberQuestion)
def manamgeLevelAmount(self, groupAmount=None, NumberQuestionObject=None):
for num in range(0,len(NumberQuestionObject)):
if(NumberQuestionObject[num]['id_question_level_amount']==0):
NumberQuestionObject[num]['id_question_level_amount'] =None
LevelAmount = model.NumberQuestionLevelAmount();
LevelAmount.id_question_level_amount=self.utility.setIfEmpty(NumberQuestionObject[num]['id_question_level_amount'])
LevelAmount.id_question_group_amount=groupAmount.id_question_group_amount
LevelAmount.id_fix_difficulty_level=NumberQuestionObject[num]['id_fix_difficulty_level']
LevelAmount.amount=NumberQuestionObject[num]['select_value']
if(self.utility.setIfEmpty(NumberQuestionObject[num]['id_question_level_amount'])):
LevelAmount.updateall()
else :
LevelAmount.save()
def mapAccessControl(self, optionObject=None, option=None):
map_accesscontrol = model.MapAccessControlOption();
map_accesscontrol.id_map_access_control_option = optionObject.id_map_access_control_option
if (self.utility.isEmpty(optionObject.id_map_access_control_option)):
map_accesscontrol.id_map_access_control_option=None
map_accesscontrol.id_access_control_group = optionObject.id_access_control_group
map_accesscontrol.id_question_option = option.id_question_option
map_accesscontrol.access_code = optionObject.access_code
acc_public = model.AccessControlGroup.getByAccId(idacc=optionObject.id_access_control_group)
if (str(acc_public.id_password_type) == str(PasswordType.public.value)) :
if (self.utility.isEmpty(optionObject.access_code)):
map_accesscontrol.access_code=self.utility.my_random_string(string_length=25)
else :
if acc_public :
map_accesscontrol.active=0
map_accesscontrol.updateall()
def deleteOption(self, optionObject=None):
result=False
data = JsontoObject(optionObject);
option = model.QuestionOption.getId(data.id_question_option)
if option :
option.active = 0
result=True
return result
def getListOption(self, searchObject=None):
data=[]
question,total = model.QuestionOption.getByProject(idProject = searchObject.idsearch, page=int(searchObject.page)-1, page_size=int(searchObject.limit))
data = self.setIsExpire(question)
return data,total
def setIsExpire(self, question=None):
dataOptionSummary=[]
for q in question:
q['isManage']=False
q['isExpire']=not(self.utility.isActiveFromDate(None, q['activate_date'], q['expire_date']))
if((q['isExpire']==True) or (q['send_status']==1)):
q['isManage']=True
dataOptionSummary.append(q)
return dataOptionSummary
#amount summary
def getAmountData(self, searchObject=None):
dataNumberAmount=[]
try :
data = model.QuestionGroup.getamountsummary(idoption=searchObject.idsearch, idproject=searchObject.keysearch)
for d in data :
idquestiongroup=d['id_question_group']
d['easy_level'] = model.Question.getByLevel(idquestiongroup=idquestiongroup, level=str(FixDifficultyLevel.easy_level.value))
d['normal_level'] = model.Question.getByLevel(idquestiongroup=idquestiongroup, level=str(FixDifficultyLevel.normal_level.value))
d['difficult_level'] = model.Question.getByLevel(idquestiongroup=idquestiongroup, level=str(FixDifficultyLevel.difficult_level.value))
dataNumberAmount.append(d)
except Exception as e:
log.error("%s" %e, extra=extraLog(modules=self.modules));
return dataNumberAmount
|
gpl-2.0
|
mbalkrishna/jproject1
|
sites/all/themes/wia/page.tpl.php
|
641
|
<?php require_once "inc/header-inner.inc.php";?>
<!--Content Sec start-->
<div class="content-section search-content">
<div class="container margintop40 paddingbottom60">
<?php print render($title_prefix); ?>
<?php if ($title): ?>
<h1<?php print $tabs ? ' class="with-tabs"' : '' ?>>
<?php print htmlspecialchars_decode($title); ?></h1>
<?php endif; ?>
<?php print render($title_suffix); ?>
<?php print render($page['header']); ?>
<?php if(isset($messages)){print $messages;} ?>
<?php print render($page['content']); ?>
<?php print render($page['footer']); ?>
</div>
</div>
<!--Content End start-->
<?php require_once "inc/footer.inc.php";?>
|
gpl-2.0
|
ljh198275823/504-GeneralLibrary
|
Barcode/_1D/Symbologies/MSI.cs
|
3980
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Barcode._1D.Symbologies
{
class MSI : BarcodeCommon, IBarcode
{
/// <summary>
/// MSI encoding
/// Written by: Brad Barnhill
/// </summary>
private string[] MSI_Code = { "100100100100", "100100100110", "100100110100", "100100110110", "100110100100", "100110100110", "100110110100", "100110110110", "110100100100", "110100100110" };
private TYPE Encoded_Type = TYPE.UNSPECIFIED;
public MSI(string input, TYPE EncodedType)
{
Encoded_Type = EncodedType;
Raw_Data = input;
}//MSI
/// <summary>
/// Encode the raw data using the MSI algorithm.
/// </summary>
private string Encode_MSI()
{
//check for non-numeric chars
if (!CheckNumericOnly(Raw_Data))
Error("EMSI-1: Numeric Data Only");
string PreEncoded = Raw_Data;
//get checksum
if (Encoded_Type == TYPE.MSI_Mod10 || Encoded_Type == TYPE.MSI_2Mod10)
{
string odds = "";
string evens = "";
for (int i = PreEncoded.Length - 1; i >= 0; i -= 2)
{
odds = PreEncoded[i].ToString() + odds;
if (i - 1 >= 0)
evens = PreEncoded[i - 1].ToString() + evens;
}//for
//multiply odds by 2
odds = Convert.ToString((Int32.Parse(odds) * 2));
int evensum = 0;
int oddsum = 0;
foreach (char c in evens)
evensum += Int32.Parse(c.ToString());
foreach (char c in odds)
oddsum += Int32.Parse(c.ToString());
int checksum = 10 - ((oddsum + evensum) % 10);
PreEncoded += checksum.ToString();
}//if
if (Encoded_Type == TYPE.MSI_Mod11 || Encoded_Type == TYPE.MSI_Mod11_Mod10)
{
int sum = 0;
int weight = 2;
for (int i = PreEncoded.Length - 1; i >= 0; i--)
{
if (weight > 7) weight = 2;
sum += Int32.Parse(PreEncoded[i].ToString()) * weight++;
}//foreach
int checksum = 11 - (sum % 11);
PreEncoded += checksum.ToString();
}//else
if (Encoded_Type == TYPE.MSI_2Mod10 || Encoded_Type == TYPE.MSI_Mod11_Mod10)
{
//get second check digit if 2 mod 10 was selected or Mod11/Mod10
string odds = "";
string evens = "";
for (int i = PreEncoded.Length - 1; i >= 0; i -= 2)
{
odds = PreEncoded[i].ToString() + odds;
if (i - 1 >= 0)
evens = PreEncoded[i - 1].ToString() + evens;
}//for
//multiply odds by 2
odds = Convert.ToString((Int32.Parse(odds) * 2));
int evensum = 0;
int oddsum = 0;
foreach (char c in evens)
evensum += Int32.Parse(c.ToString());
foreach (char c in odds)
oddsum += Int32.Parse(c.ToString());
int checksum = 10 - ((oddsum + evensum) % 10);
PreEncoded += checksum.ToString();
}//if
string result = "110";
foreach (char c in PreEncoded)
{
result += MSI_Code[Int32.Parse(c.ToString())];
}//foreach
//add stop character
result += "1001";
return result;
}//Encode_MSI
#region IBarcode Members
public string Encoded_Value
{
get { return Encode_MSI(); }
}
#endregion
}//class
}//namepsace
|
gpl-2.0
|
riskey95/HiShoot2-Template-LG-L7-II-Dual
|
src/com/riskey/hishoot2templatelgl7ii/MainActivity.java
|
249
|
package com.riskey.hishoot2templatelgl7ii;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
|
gpl-2.0
|
XSilent/KataBerlinClock
|
test/clock.js
|
5016
|
var assert = require('assert');
var Clock = require("../app/clock.js").Clock;
describe('Berlin Clock', function(){
// ----------------------------------------------------------------------------------------
// hour row 1
// ----------------------------------------------------------------------------------------
describe('#foo()', function(){
it('should return the berlin time for 00:00:00', function(){
var clock = new Clock('00:00:00');
assert.equal('OOOO', clock.getHourRow1());
});
}),
describe('#foo()', function(){
it('should return the berlin time for 13:17:01', function(){
var clock = new Clock('13:17:01');
assert.equal('RROO', clock.getHourRow1());
});
}),
describe('#foo()', function(){
it('should return the berlin time for 23:59:59', function(){
var clock = new Clock('23:59:59');
assert.equal('RRRR', clock.getHourRow1());
});
}),
// ----------------------------------------------------------------------------------------
// Hour row 2
// ----------------------------------------------------------------------------------------
describe('#foo()', function(){
it('should return the berlin time hour row 2 for 00:00:00', function(){
var clock = new Clock('00:00:00');
assert.equal('OOOO', clock.getHourRow2());
});
}),
describe('#foo()', function(){
it('should return the berlin time hour row 2 for 13:17:01', function(){
var clock = new Clock('13:17:01');
assert.equal('RRRO', clock.getHourRow2());
});
}),
describe('#foo()', function(){
it('should return the berlin time hour row 2 for 23:59:59', function(){
var clock = new Clock('23:59:59');
assert.equal('RRRO', clock.getHourRow2());
});
}),
describe('#foo()', function(){
it('should return the berlin time hour row 2 for 24:00:00', function(){
var clock = new Clock('24:00:00');
assert.equal('RRRR', clock.getHourRow2());
});
}),
// ----------------------------------------------------------------------------------------
// Minutes row 1
// ----------------------------------------------------------------------------------------
describe('#foo()', function(){
it('should return the berlin time minutes row 1 for 00:11:00', function(){
var clock = new Clock('00:11:00');
assert.equal('YYOOOOOOOOO', clock.getMinutesRow1());
});
}),
describe('#foo()', function(){
it('should return the berlin time minutes row 1 for 00:00:00', function(){
var clock = new Clock('00:00:00');
assert.equal('OOOOOOOOOOO', clock.getMinutesRow1());
});
}),
describe('#foo()', function(){
it('should return the berlin time minutes row 1 for 13:17:01', function(){
var clock = new Clock('13:17:01');
assert.equal('YYROOOOOOOO', clock.getMinutesRow1());
});
}),
describe('#foo()', function(){
it('should return the berlin time minutes row 1 for 23:59:59', function(){
var clock = new Clock('23:59:59');
assert.equal('YYRYYRYYRYY', clock.getMinutesRow1());
});
}),
describe('#foo()', function(){
it('should return the berlin time minutes row 1 for 24:00:00', function(){
var clock = new Clock('24:00:00');
assert.equal('OOOOOOOOOOO', clock.getMinutesRow1());
});
}),
// ----------------------------------------------------------------------------------------
// Minutes row 2
// ----------------------------------------------------------------------------------------
describe('#foo()', function(){
it('should return the berlin time minutes row 2 for 00:11:00', function(){
var clock = new Clock('00:11:00');
assert.equal('YOOO', clock.getMinutesRow2());
});
}),
describe('#foo()', function(){
it('should return the berlin time minutes row 2 for 00:00:00', function(){
var clock = new Clock('00:00:00');
assert.equal('OOOO', clock.getMinutesRow2());
});
}),
describe('#foo()', function(){
it('should return the berlin time minutes row 2 for 13:17:01', function(){
var clock = new Clock('13:17:01');
assert.equal('YYOO', clock.getMinutesRow2());
});
}),
describe('#foo()', function(){
it('should return the berlin time minutes row 2 for 23:59:59', function(){
var clock = new Clock('23:59:59');
assert.equal('YYYY', clock.getMinutesRow2());
});
}),
describe('#foo()', function(){
it('should return the berlin time minutes row 2 for 24:00:00', function(){
var clock = new Clock('24:00:00');
assert.equal('OOOO', clock.getMinutesRow2());
});
}),
// ----------------------------------------------------------------------------------------
// Seconds
// ----------------------------------------------------------------------------------------
describe('#foo()', function(){
it('should return the berlin time seconds for 00:00:00', function(){
var clock = new Clock('00:00:00');
assert.equal('Y', clock.getSeconds());
});
}),
describe('#foo()', function(){
it('should return the berlin time seconds for 13:17:01', function(){
var clock = new Clock('13:17:01');
assert.equal('O', clock.getSeconds());
});
})
});
|
gpl-2.0
|
HouraiTeahouse/FantasyCrescendo
|
Assets/Code/src/Runtime/Input/TestInputSource.cs
|
1014
|
using HouraiTeahouse.FantasyCrescendo.Matches;
using HouraiTeahouse.FantasyCrescendo.Players;
using UnityEngine;
namespace HouraiTeahouse.FantasyCrescendo {
public class TestInputSource : IInputSource<MatchInput> {
MatchInput input;
public TestInputSource(MatchConfig config) {
input = new MatchInput(config);
// Force all inputs to be valid by "predicting" it.
input.Predict();
}
public MatchInput SampleInput() {
var playerInput = new PlayerInput {
Movement = new Vector2(ButtonAxis(KeyCode.A, KeyCode.D), ButtonAxis(KeyCode.S, KeyCode.W)),
//TODO(james7132): Make Tap Jump Configurable
Jump = Input.GetKey(KeyCode.W),
};
var inputValue = input;
for (int i = 0; i < inputValue.PlayerCount; i++) {
if (i == 0) {
inputValue[i] = playerInput;
}
}
return inputValue;
}
float ButtonAxis(KeyCode neg, KeyCode pos) {
var val = Input.GetKey(neg) ? -1.0f : 0.0f;
return val + (Input.GetKey(pos) ? 1.0f : 0.0f);
}
}
}
|
gpl-2.0
|
utopszkij/li-de
|
componens_telepitok/com_szavazasok/admin/models/model.php
|
12926
|
<?php
/**
* @version $Id:Model.php 1 2014-04-13Z FT $
* @package Szavazasok
* @subpackage Models
* @copyright Copyright (C) 2014, Fogler Tibor. All rights reserved.
* @license #GNU/GPL
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
/**
* Model
* @author Michael Liebler
*/
jimport( 'joomla.application.component.model' );
class SzavazasokModel extends JModelLegacy {
/**
* Items data array
*
* @var array
*/
protected $_data = null;
/**
* Items total
*
* @var integer
*/
protected $_total = null;
/**
* ID
*
* @var integer
*/
protected $_id = null;
/**
* Default Filter
*
* @var mixed
*/
protected $_default_filter = null;
/**
* Default Filter
*
* @var mixed
*/
protected $_default_table = null;
/**
* JQuery
*
* @var object
*/
protected $_query;
/**
* JQuery
*
* @var object
*/
protected $_state_field;
/**
* @var string The URL option for the component.
*/
protected $option = null;
/**
* @var string context the context to find session data.
*/
protected $_context = null;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$app = &JFactory::getApplication('administrator');
// Guess the option from the class name (Option)Model(View).
if (empty($this->option)) {
$r = null;
if (!preg_match('/(.*)Model/i', get_class($this), $r)) {
JError::raiseError(500, JText::_('No Model Name'));
}
$this->option = 'com_'.strtolower($r[1]);
}
$this->_query = $this->_db->getQuery(true);
$table = $this->getTable();
if ($table) {
$this->_default_table = $table->getTableName();
if (isset($table->published)) $this->_state_field = 'published';
}
if (empty($this->_context)) {
$this->_context = $this->option.'.'.$this->getName();
}
$array = JRequest :: getVar('cid', array (
0
), '', 'array');
$edit = JRequest :: getVar('edit', true);
if ($edit)
$this->setId((int) $array[0]);
// Get the pagination request variables
$limit = $app ->getUserStateFromRequest( $this->_context .'.limit', 'limit', $app->getCfg('list_limit', 0), 'int' );
$limitstart = $app ->getUserStateFromRequest( $this->_context .'.limitstart', 'limitstart', 0, 'int' );
// In case limit has been changed, adjust limitstart accordingly
$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
$this->setState('limit', $limit);
$this->setState('limitstart', $limitstart);
}
/**
* Method to get the item identifier
*
* @access public
* @return $_id int Item Identifier
*/
public function getId()
{
return $this->_id;
}
/**
* Method to set the item identifier
*
* @access public
* @param int Item identifier
*/
public function setId($id)
{
// Set item id and wipe data
$this->_id = $id;
$this->_data = null;
}
/**
* Return a List of vendor-Items
* @access public
* @return $_data array
*/
public function getData()
{
// Lets load the content if it doesn't already exist
if (empty($this->_data)) {
$query = $this->_buildQuery();
$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
}
return $this->_data;
}
public function getDefaultFilter()
{
return $this->_default_filter;
}
/**
* Method to get the row form.
*
* @return mixed JForm object on success, false on failure.
* @since 1.6
*/
public function getForm($name = null)
{
if (!$name) {
$name = $this->getName();
}
// Initialize variables.
$app = &JFactory::getApplication();
// Get the form.
$form = $this->_getForm($name, 'form', array('control' => 'jform'));
JFormHelper::addRulePath(JPATH_COMPONENT_ADMINISTRATOR.'/models/rules');
// Check for an error.
if (JError::isError($form)) {
$this->setError($form->getMessage());
return false;
}
// Check the session for previously entered form data.
$data = $app->getUserState($this->_context.'.edit.'.$name.'.data', array());
// Bind the form data if present.
if (!empty($data)) {
$form->bind($data);
}
return $form;
}
/**
* Method to get a form object.
*
* @param string $xml The form data. Can be XML string if file flag is set to false.
* @param array $options Optional array of parameters.
* @param boolean $clear Optional argument to force load a new form.
* @return mixed JForm object on success, False on error.
*/
private function &_getForm($xml, $name = 'form', $options = array(), $clear = false)
{
// Handle the optional arguments.
$options['control'] = JArrayHelper::getValue($options, 'control', false);
// Create a signature hash.
$hash = md5($xml.serialize($options));
// Check if we can use a previously loaded form.
if (isset($this->_forms[$hash]) && !$clear) {
return $this->_forms[$hash];
}
// Get the form.
jimport('joomla.form.form');
JForm::addFormPath(JPATH_COMPONENT_ADMINISTRATOR.'/models/forms');
JForm::addFieldPath(JPATH_COMPONENT_ADMINISTRATOR.'/models/fields');
$form = JForm::getInstance($name, $xml, $options, false);
// Check for an error.
if (JError::isError($form)) {
$this->setError($form->getMessage());
$false = false;
return $form;
}
// Store the form for later.
$this->_forms[$hash] = $form;
return $form;
}
/**
* Method to get an Item
*
* @access public
* @return $item array
*/
public function getItem()
{
$item = & $this->getTable();
$item->load($this->_id);
if (isset($item->params)) {
$params = json_decode($item->params);
$item->params = new JObject();
$item->params ->setProperties(JArrayHelper::fromObject($params));
}
return $item;
}
/**
* Method to delete an Item
*
* @access public
* @param $cid int
* @return $affected int
*/
public function delete($cid)
{
$db = & JFactory::getDBO();
$query = 'DELETE FROM '.$this->_default_table.' WHERE id '.$this->_multiDbCondIfArray($cid);
$db->setQuery( $query);
$db->query();
$affected = $db->getAffectedRows();
return $affected ;
}
/**
* Method to store the vendor
*
* @access public
* @return boolean True on success
*/
public function store($data)
{
// Implemented in child classes
}
/**
* Method to get a pagination object
*
* @access public
* @return integer
*/
public function getPagination()
{
// Lets load the content if it doesn't already exist
if (empty($this->_pagination)) {
jimport('joomla.html.pagination');
$this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
}
return $this->_pagination;
}
/**
* Method to get the total number of items
*
* @access public
* @return integer
*/
public function getTotal()
{
// Lets load the content if it doesn't already exist
if (empty($this->_total)) {
$query = $this->_buildQuery();
$this->_total = $this->_getListCount($query);
}
return $this->_total;
}
/**
* Method to (un)publish an item
*
* @access public
* @return boolean True on success
*/
public function publish($cid = array (), $publish = 1)
{
$user = & JFactory :: getUser();
if (count($cid)) {
JArrayHelper :: toInteger($cid);
$cids = implode(',', $cid);
$query = 'UPDATE '.$this->_default_table.' SET published = ' . (int) $publish . ' WHERE id IN ( ' . $cids . ' )';
$this->_db->setQuery($query);
if (!$this->_db->query()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
}
return true;
}
/**
* Method to move a item
*
* @access public
* @return boolean True on success
*/
public function saveorder($cid, $order)
{
$row = & $this->getTable();
$groupings = array ();
// update ordering values
for ($i = 0; $i < count($cid); $i++) {
$row->load((int) $cid[$i]);
if ($row->ordering != $order[$i]) {
$row->ordering = $order[$i];
if (!$row->store()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
}
}
return true;
}
/**
* Method to move an item
*
* @access public
* @return boolean True on success
*/
public function move($direction)
{
$row =& $this->getTable();
if (!$row->load($this->_id)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
$table = $this->getTable();
$where = "";
if ($row->catid) {
$where = ' catid = '.(int) $row->catid.' AND published >= 0 ';
}
if (!$row->move( $direction, $where )) {
$this->setError($this->_db->getErrorMsg());
return false;
}
return true;
}
/**
* Method to checkin/unlock the item
*
* @access public
* @return boolean True on success
*/
public function checkin()
{
if ($this->_id) {
$item = & $this->getTable();
if (!$item->checkin($this->_id)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
}
return false;
}
/**
* Method to checkout/lock the item
*
* @access public
* @param int $uid User ID of the user checking the article out
* @return boolean True on success
*/
public function checkout($uid = null)
{
if ($this->_id) {
// Make sure we have a user id to checkout the vendor with
if (is_null($uid)) {
$user = & JFactory :: getUser();
$uid = $user->get('id');
}
// Lets get to it and checkout the thing...
$item = & $this->getTable();
if (!$item->checkout($uid, $this->_id)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
return true;
}
return false;
}
/**
* Method to set the Default Filter Column
*
* @access public
* @param mixed Default Filter
*/
public function setDefaultFilter($filter)
{
$this->_default_filter = $filter;
}
/**
* Method to build the query
*
* @access private
* @return string query
*/
protected function _buildQuery()
{
static $instance;
if(!empty($instance)) {
return $instance;
}
$this->_query->select('a.*');
$this->_query->from($this->_default_table.' AS a');
$this->_buildContentWhere();
$this->_buildContentOrderBy();
$instance = $this->_query->__toString();
return $instance;
}
/**
* Method to build the Joins
*
* @access private
*/
protected function _buildJoins()
{
}
/**
* Method to build the Order Clause
*
* @access private
* @return string orderby
*/
protected function _buildContentOrderBy()
{
$app = &JFactory::getApplication('administrator');
$context = $option.'.'.strtolower($this->getName()).'.list.';
$filter_order = $app ->getUserStateFromRequest($context . 'filter_order', 'filter_order', $this->_default_filter, 'cmd');
$filter_order_Dir = $app ->getUserStateFromRequest($context . 'filter_order_Dir', 'filter_order_Dir', '', 'word');
$this->_query->order($filter_order . ' ' . $filter_order_Dir );
}
/**
* Method to build the Where Clause
*
* @access private
* @return string orderby
*/
protected function _buildContentWhere()
{
$app = &JFactory::getApplication('administrator');
$context = $this->option.'.'.strtolower($this->getName()).'.list.';
$search = $app->getUserStateFromRequest($context . 'search', 'search', '', 'string');
if ($search) {
$where[] = 'LOWER('.$this->getDefaultFilter().') LIKE ' . $this->_db->Quote('%' . $search . '%');
$this->_query->where('LOWER('.$this->getDefaultFilter().') LIKE ' . $this->_db->Quote('%' . $search . '%'));
}
if ($this->_state_field) {
$filter_state = $app->getUserStateFromRequest($context . 'filter_state', 'filter_state', '', 'word');
switch($filter_state) {
case 'P':
$this->_query->where('a.published = 1');
break;
case 'U':
$this->_query->where('a.published = 0');
break;
case 'T':
$this->_query->where('a.published = -2');
break;
}
}
}
protected function _multiDbCondIfArray($search)
{
$ret = (is_array($search)) ? " IN ('" . implode("','", $search) . "') " : " = '" . $search . "' ";
return $ret;
}
/**
* Method to validate the form data.
*
* @param object $form The form to validate against.
* @param array $data The data to validate.
* @return mixed Array of filtered data if valid, false otherwise.
* @since 1.1
*/
public function validate($form, $data)
{
// Filter and validate the form data.
$data = $form->filter($data);
$return = $form->validate($data);
// Check for an error.
if (JError::isError($return)) {
$this->setError($return->getMessage());
return false;
}
// Check the validation results.
if ($return === false) {
// Get the validation messages from the form.
foreach ($form->getErrors() as $message) {
$this->setError($message);
}
return false;
}
return $data;
}
}
|
gpl-2.0
|
acevest/acecode
|
learn/python/urllib.0.py
|
558
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------
# File Name: urllib.0.py
# Author: Zhao Yanbai
# Thu Oct 1 12:15:20 2015
# Description: none
# ------------------------------------------------------------------------
import urllib
import urllib2
import urlparse
url = "http://192.168.1.101:8080/sqli/Less-1/index.php?id=1"
print urlparse.urlsplit(url)
request = urllib2.Request(url)
response = urllib2.urlopen(request)
print response.read()
response.close()
|
gpl-2.0
|
spacemonkeythe/userManagementApp
|
features/step_definitions/profile_edit_steps.rb
|
627
|
Given(/^I am signed in user$/) do
visit login_path
fill_in "Email", with: @user.email
fill_in "Password", with: @user.password
click_button "Sign in"
end
Given(/^I am on the edit profile page$/) do
visit root_path
find_link("Account").click
find_link("Settings").click
end
When(/^I try to update data$/) do
click_button "Update my account"
end
When(/^I try to delete my account$/) do
find_link("delete").click
page.driver.browser.switch_to.alert.accept
end
Then(/^account should be deleted$/) do
page.driver.browser.switch_to.alert.accept
expect(page).to have_content("A user has been removed.")
end
|
gpl-2.0
|
Pleisterman/gameDevelopment
|
gameDevelopment/spaceInvaders/javascript/invaderOneModule.js
|
14957
|
/*
* Author: Pleisterman
* Info:
* Web: www.pleisterman.nl
* Mail: info@pleisterman.nl
* GitHub: Pleisterman
*
* Purpose: this module controls the drawing one invader for the application space invaders
*
*
* Last revision: 21-05-2015
*
* Status: code: ready
* comments: ready
* memory: ready
* development: ready
*
* NOTICE OF LICENSE
*
* Copyright (C) 2015 Pleisterman
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
( function( gameDevelopment ){
gameDevelopment.invaderOneModule = function( ) {
/*
* module invaderOneModule
*
*
* functions:
* private:
* construct called internal
* setPosition called by the public function
* layoutChange called by the public function
* animate called by the public function
* sideHit called by the public function, check if the invader hits side of movement rect
* update called by the public function, update the movement
* getBottom called by the public function, check for bottom position
* destruct called by the public function, unsubscribe from events
* debug
* public:
* setPosition called by the invadersModule
* layoutChange called by the invadersModule
* animate called by the invadersModule
* sideHit called by the invadersModule
* getBottom called by the invadersModule
* destruct called by the invadersModule
*
* event subscription:
* bulletCollisionDetect called from a bullet module
*
* event calls:
* scoreChange
*
*/
// private
var self = this;
self.MODULE = 'invaderOneModule';
self.debugOn = false;
self.canvasSurface = null;
self.position = { "top" : 0, // percentage of background height
"left" : 0, // percentage of background width
"height" : 0, // percentage of background height
"width" : 0 }; // percentage of background width
self.clearRect = { "top" : 0, // px, the rect that the image was drawn in
"left" : 0, // px
"height" : 0, // px
"width" : 0 }; // px
self.drawRect = { "top" : 0, // px, the rect that the image is drawn in
"left" : 0, // px
"height" : 0, // px
"width" : 0 }; // px
self.imagePartWidth = 125; // px of original image
self.blockWidth = 1; // number of invaderblock this invader occupies in horizontal direction
self.blockHeight = 1; // number of invaderblock this invader occupies in vertical direction
self.alive = true; // store if invader is alive
self.strength = 2; // store the strength of invader
self.hits = 0; // store the number of hits taken by invader
self.bombType = 1; // store bomb type for bomb release function
self.hitScore = 20; // store the score for when a bullet hits invader
self.difficultyHitScore = 5; // store the extra score per diificulty level
self.killScore = 100; // store the score for when invader destructs
self.difficultyKillScore = 20; // store the extra score per diificulty level
// functions
self.construct = function() {
//self.debug( 'construct' );
// get the canvas surface to draw on
self.canvasSurface = document.getElementById( 'invadersDrawLayer' ).getContext( '2d' );
self.hitScore += jsProject.getValue( "difficulty", "game" ) * self.difficultyHitScore;
self.killscore += jsProject.getValue( "difficulty", "game" ) * self.difficultyKillScore;
// subscribe to events
jsProject.subscribeToEvent( 'bulletCollisionDetect', self.bulletCollisionDetect );
};
self.bulletCollisionDetect = function() {
if( !self.alive ){
return;
}
// get the rect of the colliding object
var rect = jsProject.getValue( "collisionRect", "game" );
// check basic intersect
if( rect["top"] < self.position["top"] ||
rect["left"] > self.position["left"] + self.position["width"] ||
rect["left"] + rect["width"] < self.position["left"] ){
return;
}
// done check basic intersect
// check expanded intersect
var left = Math.max( rect["left"], self.position["left"] );
var right = Math.min( rect["left"] + rect["width"], self.position["left"] + self.position["width"] );
var top = Math.max( rect["top"], self.position["top"] );
var bottom = Math.min( rect["top"] + rect["height"], self.position["top"] + self.position["height"] );
if( right >= left && bottom >= top ){
// there is a collision
// get the callback
var callback = jsProject.getValue( "collisionCallback", "game" );
if( callback ){
// get the hitStrength of the collision
self.hits += callback();
jsProject.setValue( "collisionCallback", "game", null );
// more hits then strentgh
if( self.hits > self.strength ){
// hide invader
self.alive = false;
self.canvasSurface.clearRect( self.clearRect["left"], self.clearRect["top"], self.clearRect["width"], self.clearRect["height"] );
// add kill to score
jsProject.setValue( "score", "game", jsProject.getValue( "score", "game" ) + self.killScore );
jsProject.callEvent( "scoreChange" );
// done add kill to score
}
else {
// add hit to score
jsProject.setValue( "score", "game", jsProject.getValue( "score", "game" ) + self.hitScore );
jsProject.callEvent( "scoreChange" );
// done add hit to score
}
}
// animate without delay
self.animate( true );
}
// done check expanded intersect
};
self.setPosition = function( top, left, height, width, verticalSpacing, horizontalSpacing ) {
// set position of the invader
self.position["top"] = top;
self.position["left"] = left;
// done set position of the invader
// calculate dimensions of invader
self.position["height"] = ( ( self.blockHeight - 1 ) * verticalSpacing ) + ( self.blockHeight * height );
self.position["width"] = ( ( self.blockWidth - 1 ) * horizontalSpacing ) + ( self.blockWidth * width );;
// done calculate dimensions of invader
};
self.update = function( changeHorizontal, changeVertical ){
if( !self.alive ){
return;
}
// change the position
self.position["top"] += changeVertical;
self.position["left"] += changeHorizontal;
// set the new drawRect
self.drawRect["top"] = ( $( '#background' ).height() / 100 ) * self.position["top"];
self.drawRect["left"] = ( $( '#background' ).width() / 100 ) * self.position["left"];
};
self.layoutChange = function(){
if( !self.alive ){
return;
}
//self.debug( 'layoutChange' );
// reset clearRect
self.clearRect["top"] = 0;
self.clearRect["left"] = 0;
self.clearRect["height"] = 0;
self.clearRect["width"] = 0;
// done reset clearRect
// calculate drawRect
self.drawRect["top"] = ( $( '#background').height() / 100 ) * self.position["top"];
self.drawRect["left"] = ( $( '#background').width() / 100 ) * self.position["left"];
self.drawRect["height"] = ( $( '#background').height() / 100 ) * self.position["height"];
self.drawRect["width"] = ( $( '#background').width() / 100 ) * self.position["width"];
// done calculate drawRect
};
self.clearRect = function( ){
//self.debug( 'clearRect' );
if( !self.alive ){
return;
}
// clear the clearRect
self.canvasSurface.clearRect( self.clearRect["left"], self.clearRect["top"], self.clearRect["width"], self.clearRect["height"] );
};
self.animate = function( ){
if( !self.alive ){
return;
}
// change the state
if( self.state === 0 ){
self.state = 1;
}
else {
self.state = 0;
}
// done change the state
// draw image
// get the current part according to the state
var imagePartLeft = self.state * self.imagePartWidth;
// get the image
var image = jsProject.getResource( 'invaderOne', 'image' );
self.canvasSurface.drawImage( image, imagePartLeft, 0, self.imagePartWidth, image.height,
self.drawRect["left"], self.drawRect["top"], self.drawRect["width"], self.drawRect["height"] );
// done draw image
// clearRect = drawRect
self.clearRect["top"] = self.drawRect["top"];
self.clearRect["left"] = self.drawRect["left"];
self.clearRect["height"] = self.drawRect["height"];
self.clearRect["width"] = self.drawRect["width"];
// done clearRect = drawRect
};
self.sideHit = function( change, minimum, maximum ){
if( !self.alive ){
return false;
}
// check left side
if( change < 0 ){
if( self.position["left"] + change < minimum ){
// hit left side
return true;
}
} // done check left side
else { // check right side
if( self.position["left"] + self.position["width"] + change > maximum ){
// hit right side
return true;
}
} // done check right side
// no side hit
return false;
};
self.getBottom = function( ){
// return top + height
return self.position["top"] + self.position["height"];
};
self.releaseBomb = function( ){
if( !self.alive ){
return;
}
// set the values for the bomb
jsProject.setValue( "bombType", "game", self.bombType );
jsProject.setValue( "bombStartTop", "game", self.position["top"] + self.position['height'] );
jsProject.setValue( "bombStartLeft", "game", ( self.position["left"] ) );
// call the event
jsProject.callEvent( "releaseBomb" );
};
self.destruct = function(){
//unsubscribe from events
jsProject.unSubscribeFromEvent( 'bulletCollisionDetect', self.bulletCollisionDetect );
};
// debug
self.debug = function( string ) {
if( self.debugOn ) {
jsProject.debug( self.MODULE + ' ' + string );
}
};
// initialize the class
self.construct();
// public
return {
setPosition : function( top, left, height, width, verticalSpacing, horizontalSpacing ) {
self.setPosition( top, left, height, width, verticalSpacing, horizontalSpacing );
},
update : function( changeHorizontal, changeVertical ) {
self.update( changeHorizontal, changeVertical );
},
animate : function() {
self.animate();
},
clearRect : function(){
self.clearRect();
},
layoutChange : function() {
self.layoutChange();
},
getBottom : function() {
return self.getBottom( );
},
sideHit : function( change, minimum, maximum ) {
return self.sideHit( change, minimum, maximum );
},
releaseBomb : function() {
return self.releaseBomb();
},
isAlive : function() {
return self.alive;
},
destruct : function() {
return self.destruct();
}
};
};
})( gameDevelopment );
|
gpl-2.0
|
shpandrak/shpansurvey
|
src/main/js/shpanbot.ts
|
7448
|
/**
* Created by shpandrak on 11/21/14.
*/
/// <reference path="shpantext.ts" />
interface BotActionPlugin{
(runner:BotRunner, option: BotOption, step:BotStep);
}
function doTheBot(titleElement:HTMLElement, consoleElement:HTMLElement, outputElement:HTMLElement, bot: Bot){
var botRunner:BotRunner = new BotRunner(bot, titleElement, consoleElement, outputElement);
botRunner.run();
}
function runSampleBot(titleElement:HTMLElement, consoleElement:HTMLElement, outputElement:HTMLElement){
var stepRoot:BotStep = new BotStep(
'root',
'Hi.$[d,3,2000]I am the first bot.$[w,2000] Surrender now, or fight.',[
new BotOption(
'1',
'Surrender',
new BotAction('alert', {
text: 'Good thinking..'
})
),
new BotOption(
'2',
'Fight',
new BotAction('step', {
stepId: 'fight'
})
),
new BotOption(
'3',
'Calm Down Bot',
new BotAction('alert', {
text: 'Never!'
})
)
]);
var stepFight:BotStep = new BotStep(
'fight',
'OK.. so this is how its going to be$[w,200].$[w,200].$[w,200].$[w,200].$[w,200].$[w,200].$[w,200].$[w,200].$[w,200].$[w,200].$[d,9] so how far are you willing to go?',[
new BotOption(
'1',
'To The Death',
new BotAction("alert", {
text: 'Luckily for you bot is still under construction...'
})
),
new BotOption(
'2',
'To The Pain',
new BotAction("step", {
stepId: 'pain'
})
)
]);
var stepPain:BotStep = new BotStep(
'pain',
'I\'ll explain$[da,1000]and I\'ll use small words so that you\'ll be sure to understand$[da,500]you warthog-faced buffoon.$[da,1000]' +
'"To the pain" means$[w,100].$[w,100].$[w,100].$[da] the first thing you lose will be your feet$[w,1000] below the ankles$[da,1000]' +
'then your hands$[w,1000] at the wrists$[da,1000]Next,$[w,400] your nose.',[
new BotOption(
'1',
'aaaa',
new BotAction("step", {
stepId: 'root'
})
),
new BotOption(
'2',
'bbbbb',
new BotAction("step", {
stepId: 'root'
})
)
]);
var bot:Bot = new Bot(
"The First Bot!",
"shpandrak@gmail.com",
[
stepRoot,
stepFight,
stepPain
],
"root");
doTheBot(titleElement, consoleElement, outputElement, bot);
}
class BotAction{
type: string;
values: { [s: string]: string; };
constructor(type: string, values: { [s: string]: string; }){
this.type = type;
this.values = values;
}
}
class BotOption{
id:string;
text: string;
action: BotAction;
constructor(id:string, text: string,action: BotAction){
this.id = id;
this.text = text;
this.action = action;
}
}
class BotStep{
id:string;
text: string;
options: Array<BotOption>;
constructor(id:string, text:string, options: Array<BotOption>){
this.id = id;
this.text = text;
this.options = options;
}
}
class Bot{
name: string;
creator: string;
steps: Array<BotStep>;
firstStepId: string;
constructor(name: string, creator: string, steps: Array<BotStep>, firstStepId: string){
this.name = name;
this.creator = creator;
this.steps = steps;
this.firstStepId = firstStepId;
}
}
class BotRunner{
private shpanText:ShpanText;
private titleElement:HTMLElement;
private consoleElement:HTMLElement;
private outputElement:HTMLElement;
private bot:Bot;
private botSteps: { [s: string]: BotStep; };
// Initializing default action plugins
private actionPlugins: { [s: string]: BotActionPlugin; } = {
'step': function (runner:BotRunner, option: BotOption, step:BotStep){
runner.runStep(option.action.values['stepId'])
},
'link': function (runner:BotRunner, option: BotOption, step:BotStep) {
var href:string = option.action.values['href'];
window.location.href = href;
},
'alert': function (runner:BotRunner, option: BotOption, step:BotStep) {
alert(option.action.values['alert']);
}
};
constructor(bot:Bot, titleElement:HTMLElement, consoleElement:HTMLElement, outputElement:HTMLElement){
this.bot = bot;
this.titleElement = titleElement;
this.consoleElement = consoleElement;
this.outputElement = outputElement;
this.shpanText = new ShpanText(consoleElement);
this.botSteps = {};
bot.steps.forEach((currStep) =>{
this.botSteps[currStep.id] = currStep;
})
}
public run(){
this.titleElement.innerHTML= this.bot.name;
this.runStep(this.bot.firstStepId);
}
public addActionPlugin(actionId:string, actionPlugin:BotActionPlugin){
this.actionPlugins[actionId] = actionPlugin;
}
public print(shpanText:string, callback:ShpanTextCallback = null){
this.shpanText.printShpanText(shpanText, callback);
}
public runStep(stepId:string){
var botStep:BotStep = this.botSteps[stepId];
this.outputElement.innerHTML = '';
this.consoleElement.innerHTML = '';
this.shpanText.printShpanText(botStep.text, () => {
this.displayBotStepOptions(botStep);
});
}
private displayBotStepOptions(botStep) {
var first:boolean = true;
botStep.options.forEach((currOption) => {
if (first) {
first = false;
} else {
this.outputElement.appendChild(document.createTextNode(' | '));
}
var a:HTMLAnchorElement = document.createElement("a");
a.textContent = currOption.text;
a.href = "javascript:undefined";
var actionPlugin:BotActionPlugin = this.actionPlugins[currOption.action.type];
if (actionPlugin == null){
console.error("invalid action plugin " + currOption.action.type);
a.addEventListener("click", ()=> {
alert('Bonk!');
});
}else{
a.addEventListener("click", (ev:MouseEvent)=> {
ev.preventDefault();
// Allowing something to say before redirecting
var textBeforeRedirect:string = currOption.action.values['text'];
if (textBeforeRedirect != null){
this.shpanText.printShpanText('$[da]' + textBeforeRedirect, ()=>{
actionPlugin(this, currOption, botStep);
});
}else{
actionPlugin(this, currOption, botStep);
}
});
}
this.outputElement.appendChild(a);
});
}
}
|
gpl-2.0
|
toblerone554/java
|
operadoresLogicos.java
|
241
|
public class operadoresLogicos
{
public static void main(String[]args)
{
int p=4;
int f=2;
if ((p>0)||(++f>0))
{
p++;
}
System.out.println("p vale " +p);
System.out.println("f vale " +f);
}
}
|
gpl-2.0
|
ferfialho/gorainhadapaz
|
wp-content/plugins/nextgen-gallery/products/photocrati_nextgen/modules/widget/class.widget_slideshow.php
|
4577
|
<?php
class C_Widget_Slideshow extends WP_Widget
{
function __construct()
{
$widget_ops = array('classname' => 'widget_slideshow', 'description' => __('Show a NextGEN Gallery Slideshow', 'nggallery'));
$this->WP_Widget('slideshow', __('NextGEN Slideshow', 'nggallery'), $widget_ops);
}
function form($instance)
{
global $wpdb;
// used for rendering utilities
$parent = C_Component_Registry::get_instance()->get_utility('I_Widget');
// defaults
$instance = wp_parse_args(
(array)$instance,
array(
'galleryid' => '0',
'height' => '120',
'title' => 'Slideshow',
'width' => '160'
)
);
$parent->render_partial(
'photocrati-widget#form_slideshow',
array(
'self' => $this,
'instance' => $instance,
'title' => esc_attr($instance['title']),
'height' => esc_attr($instance['height']),
'width' => esc_attr($instance['width']),
'tables' => $wpdb->get_results("SELECT * FROM {$wpdb->nggallery} ORDER BY 'name' ASC")
)
);
}
function update($new_instance, $old_instance)
{
$nh = $new_instance['height'];
$nw = $new_instance['width'];
if (empty($nh) || (int)$nh === 0)
$new_instance['height'] = 120;
if (empty($nw) || (int)$nw === 0)
$new_instance['width'] = 160;
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['galleryid'] = (int) $new_instance['galleryid'];
$instance['height'] = (int) $new_instance['height'];
$instance['width'] = (int) $new_instance['width'];
return $instance;
}
function widget($args, $instance)
{
$router = C_Router::get_instance();
wp_enqueue_style('nextgen_widgets_style', $router->get_static_url('photocrati-widget#widgets.css'));
wp_enqueue_style('nextgen_basic_slideshow_style', $router->get_static_url('photocrati-nextgen_basic_gallery#slideshow/nextgen_basic_slideshow.css'));
// these are handled by extract() but I want to silence my IDE warnings that these vars don't exist
$before_widget = NULL;
$before_title = NULL;
$after_widget = NULL;
$after_title = NULL;
$widget_id = NULL;
extract($args);
$parent = C_Component_Registry::get_instance()->get_utility('I_Widget');
$title = apply_filters('widget_title', empty($instance['title']) ? __('Slideshow', 'nggallery') : $instance['title'], $instance, $this->id_base);
$out = $this->render_slideshow($instance['galleryid'], $instance['width'], $instance['height'], $args);
$parent->render_partial(
'photocrati-widget#display_slideshow',
array(
'self' => $this,
'instance' => $instance,
'title' => $title,
'out' => $out,
'before_widget' => $before_widget,
'before_title' => $before_title,
'after_widget' => $after_widget,
'after_title' => $after_title,
'widget_id' => $widget_id
)
);
}
function render_slideshow($galleryID, $irWidth = '', $irHeight = '', $args)
{
$registry = C_Component_Registry::get_instance();
$renderer = $registry->get_utility('I_Displayed_Gallery_Renderer');
$params = array(
'container_ids' => $galleryID,
'display_type' => 'photocrati-nextgen_basic_slideshow',
'gallery_width' => $irWidth,
'gallery_height' => $irHeight,
'source' => 'galleries',
'slug' => 'widget-' . $args['widget_id'],
'entity_types' => array('image'),
'show_thumbnail_link' => FALSE,
'ngg_triggers_display' => 'never'
);
if (0 === $galleryID)
{
$params['source'] = 'random_images';
unset($params['container_ids']);
}
$retval = $renderer->display_images($params, NULL);
$retval = apply_filters('ngg_show_slideshow_widget_content', $retval, $galleryID, $irWidth, $irHeight);
return $retval;
}
}
|
gpl-2.0
|
labshasan/PHP-Laravel
|
sis/items.php
|
1285
|
<?php
include_once('lib/library.php');
?>
<html>
<head>
<title>All Students</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/lib/bootstrap.css">
</head>
<body>
<div>
<table border="1">
<thead>
<tr>
<th>SL#</th>
<?php
foreach ($student_keys as $k1 => $v1) {
echo '<th>';
echo $v1;
echo '</th>';
}
?>
<th></th>
</tr>
</thead>
<tbody>
<?php
global $student_store;
$length = getStudentCount();
for ($i=0;$i<$length;$i++):
?>
<tr><td><?php echo $i+1?></td>
<?php
foreach ($student_keys as $k1 => $v1) {
echo '<td>';
echo $_SESSION[$student_store][$i][$k1];
echo '</td>';
}
?>
<td><a href='update.php?index=<?php echo $i?>'>Edit</a> |
<a href='delete.php?index=<?php echo $i?>'>Delete</a> |
<a href='detail.php?index=<?php echo $i?>'>Show</a>
</td>
</tr>
<?php
endfor;
?>
</tbody>
</table>
<a href="create.php">Create New Student Record</a>
</div>
</body>
</html>
|
gpl-2.0
|
wraiden/spacewalk
|
backend/satellite_tools/repo_plugins/uln_src.py
|
2772
|
"""
Copyright (C) 2014 Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation, version 2
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.
ULN plugin for spacewalk-repo-sync.
"""
import sys
sys.path.append('/usr/share/rhn')
from up2date_client.rpcServer import RetryServer, ServerList
from spacewalk.satellite_tools.repo_plugins.yum_src import ContentSource as yum_ContentSource
from spacewalk.satellite_tools.syncLib import RhnSyncException
ULNSRC_CONF = '/etc/rhn/spacewalk-repo-sync/uln.conf'
DEFAULT_UP2DATE_URL = "linux-update.oracle.com"
class ContentSource(yum_ContentSource):
def __init__(self, url, name):
if url[:6] != "uln://":
raise RhnSyncException("url format error, url must start with uln://")
yum_ContentSource.__init__(self, url, name, ULNSRC_CONF)
self.uln_url = None
self.uln_user = None
self.uln_pass = None
self.key = None
def _authenticate(self, url):
if url.startswith("uln:///"):
self.uln_url = "https://" + DEFAULT_UP2DATE_URL
label = url[7:]
elif url.startswith("uln://"):
parts = url[6:].split("/")
self.uln_url = "https://" + parts[0]
label = parts[1]
else:
raise RhnSyncException("url format error, url must start with uln://")
self.uln_user = self.yumbase.conf.username
self.uln_pass = self.yumbase.conf.password
self.url = self.uln_url + "/XMLRPC/GET-REQ/" + label
print("The download URL is: " + self.url)
if self.proxy_addr:
print("Trying proxy " + self.proxy_addr)
slist = ServerList([self.uln_url+"/rpc/api",])
s = RetryServer(slist.server(),
refreshCallback=None,
proxy=self.proxy_addr,
username=self.proxy_user,
password=self.proxy_pass,
timeout=5)
s.addServerList(slist)
self.key = s.auth.login(self.uln_user, self.uln_pass)
def setup_repo(self, repo, *args, **kwargs):
repo.http_headers = {'X-ULN-Api-User-Key': self.key}
yum_ContentSource.setup_repo(self, repo, *args, **kwargs)
|
gpl-2.0
|
camueller/SmartApplianceEnabler
|
src/test/angular/src/page/schedule/day-timeframe.page.ts
|
3374
|
import {
assertInput, assertSelectOptionMulti,
inputText, selectOptionMulti,
selectorInputByFormControlName,
selectorSelectByFormControlName,
selectorSelectedByFormControlName
} from '../../shared/form';
import {DayTimeframe} from '../../../../../main/angular/src/app/schedule/timeframe/day/day-timeframe';
import {isDebug} from '../../shared/helper';
import {getTranslation} from '../../shared/ngx-translate';
import {TimeUtil} from '../../../../../main/angular/src/app/shared/time-util';
export class DayTimeframePage {
public static async setDayTimeframe(t: TestController, dayTimeframe: DayTimeframe, selectorPrefix: string) {
await this.setStartTime(t, TimeUtil.timestringFromTimeOfDay(dayTimeframe.start), selectorPrefix);
await this.setEndTime(t, TimeUtil.timestringFromTimeOfDay(dayTimeframe.end), selectorPrefix);
await this.setDaysOfWeek(t, dayTimeframe.daysOfWeekValues, selectorPrefix);
}
public static async assertDayTimeframe(t: TestController, dayTimeframe: DayTimeframe, selectorPrefix: string) {
await this.assertStartTime(t, TimeUtil.timestringFromTimeOfDay(dayTimeframe.start), selectorPrefix);
await this.assertEndTime(t, TimeUtil.timestringFromTimeOfDay(dayTimeframe.end), selectorPrefix);
await this.assertDaysOfWeek(t, dayTimeframe.daysOfWeekValues, selectorPrefix);
}
public static async setStartTime(t: TestController, startTime: string, selectorPrefix: string) {
await inputText(t, selectorInputByFormControlName('startTime', selectorPrefix), startTime);
await t.pressKey('esc'); // close multi select overlay
}
public static async assertStartTime(t: TestController, startTime: string, selectorPrefix: string) {
await assertInput(t, selectorInputByFormControlName('startTime', selectorPrefix), startTime);
}
public static async setEndTime(t: TestController, endTime: string, selectorPrefix: string) {
await inputText(t, selectorInputByFormControlName('endTime', selectorPrefix), endTime);
await t.pressKey('esc'); // close multi select overlay
}
public static async assertEndTime(t: TestController, endTime: string, selectorPrefix: string) {
await assertInput(t, selectorInputByFormControlName('endTime', selectorPrefix), endTime);
}
public static async setDaysOfWeek(t: TestController, daysOfWeek: number[], selectorPrefix: string) {
await selectOptionMulti(t, selectorSelectByFormControlName('daysOfWeekValues', selectorPrefix), daysOfWeek);
}
public static async assertDaysOfWeek(t: TestController, daysOfWeek: number[], selectorPrefix: string) {
const dayOfWeekNames = [];
if (daysOfWeek.includes(1)) {
dayOfWeekNames.push('monday');
}
if (daysOfWeek.includes(2)) {
dayOfWeekNames.push('tuesday');
}
if (daysOfWeek.includes(3)) {
dayOfWeekNames.push('wednesday');
}
if (daysOfWeek.includes(4)) {
dayOfWeekNames.push('thursday');
}
if (daysOfWeek.includes(5)) {
dayOfWeekNames.push('friday');
}
if (daysOfWeek.includes(6)) {
dayOfWeekNames.push('saturday');
}
if (daysOfWeek.includes(7)) {
dayOfWeekNames.push('sunday');
}
if (daysOfWeek.includes(8)) {
dayOfWeekNames.push('holiday');
}
await assertSelectOptionMulti(t, selectorSelectByFormControlName('daysOfWeekValues', selectorPrefix), dayOfWeekNames, 'daysOfWeek_');
}
}
|
gpl-2.0
|
mathetos/my-plugin-info-widget
|
views/reviews-template.php
|
725
|
<?php
$wprepo = new WP_Ratings_Widget();
?>
<div class="wprrw_reviews_enabled">
<h4 class="wprrw_reviews_title">Reviews</h4>
<div class="wprrw_reviews_wrap" data-slick=\'{"slidesToShow": 1, "slidesToScroll": 1}\'>
<?php
$wprepo->wprrw_split_reviews($instance);
?>
</div>
</div>
<div class="reviews_nav">
<span class="prevArrow"><?php echo __('Previous Review', 'wppluginratings'); ?></span>
<span class="nextArrow"><?php echo __('Next Review', 'wppluginratings'); ?></span>
</div>
<div class="reviews_all">
<a href="https://wordpress.org/support/view/plugin-reviews/<?php echo $slug; ?>" target="_blank"><?php echo __('See all reviews', 'wppluginratings'); ?></a>
</div>
<?php
|
gpl-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.