code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Scores</title>
<style type="text/css">
html { font-family: Arial; }
table { empty-cells: hide; border-collapse: collapse; background-color: white; border: 2px solid black; }
th, td { padding: 3px 1.5ex; border: 1px solid black; border-top: 1px dotted black; border-bottom: 1px dotted black; }
td.score { text-align: right; }
th { background-color: rgb(208,208,191); border-bottom: 2px solid black; }
tr.fini td { background-color: rgb(251,249,238); border-bottom: 2px solid black; }
tr.fini td.date { background-color: white; }
tr.suite td.date { border-top: hidden; }
tr:hover,
tr.fini:hover td { background-color: rgb(238,234,221); }
</style>
</head>
<body>
<h1>Tableau des scores</h1>
<h2>Exercice Hotpotatoes : <em><?php echo $oSousActiv->oHotpotatoes->retTitre(); ?></em></h2>
<h3>Etudiant : <em><?php echo $oEtudiant->retNomComplet(); ?></em></h3>
<?php
if (empty($oHotpotScores)) {
echo "<p>Aucun score Hotpotatoes.</p>";
} else {
?>
<table border="1">
<thead>
<tr><th>Date de début de l'exercice</th><th>Durée</th><th>Score</th></tr>
</thead>
<tbody>
<?php
$derDate = 0;
foreach ($oHotpotScores as $oScore) {
$suite = ($oScore->retDateDebut()===$derDate ? true : false);
echo '<tr>'
.'<td class="date">'.( $suite ? '' : date('d/m/Y H:i',$oScore->retDateInitiale()) ).'</td>'
.'<td>'.$oScore->retDuree().'</td>'
.'<td class="score">'.$oScore->retScore().' %</td>'
.'</tr>';
$derDate = $oScore->retDateDebut();
}
?>
</tbody>
<?php } ?>
</table>
</body>
</html>
| Ced-le-pingouin/esprit-mirror | src/sousactiv/hotpotatoes/scores.tpl.php | PHP | gpl-2.0 | 1,680 |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.telegram.messenger.exoplayer2.source;
import android.util.Pair;
import org.telegram.messenger.exoplayer2.C;
import org.telegram.messenger.exoplayer2.ExoPlayer;
import org.telegram.messenger.exoplayer2.Timeline;
import org.telegram.messenger.exoplayer2.upstream.Allocator;
import org.telegram.messenger.exoplayer2.util.Assertions;
import org.telegram.messenger.exoplayer2.util.Util;
import java.io.IOException;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* Concatenates multiple {@link MediaSource}s. It is valid for the same {@link MediaSource} instance
* to be present more than once in the concatenation.
*/
public final class ConcatenatingMediaSource implements MediaSource {
private final MediaSource[] mediaSources;
private final Timeline[] timelines;
private final Object[] manifests;
private final Map<MediaPeriod, Integer> sourceIndexByMediaPeriod;
private final boolean[] duplicateFlags;
private Listener listener;
private ConcatenatedTimeline timeline;
/**
* @param mediaSources The {@link MediaSource}s to concatenate. It is valid for the same
* {@link MediaSource} instance to be present more than once in the array.
*/
public ConcatenatingMediaSource(MediaSource... mediaSources) {
this.mediaSources = mediaSources;
timelines = new Timeline[mediaSources.length];
manifests = new Object[mediaSources.length];
sourceIndexByMediaPeriod = new HashMap<>();
duplicateFlags = buildDuplicateFlags(mediaSources);
}
@Override
public void prepareSource(ExoPlayer player, boolean isTopLevelSource, Listener listener) {
this.listener = listener;
for (int i = 0; i < mediaSources.length; i++) {
if (!duplicateFlags[i]) {
final int index = i;
mediaSources[i].prepareSource(player, false, new Listener() {
@Override
public void onSourceInfoRefreshed(Timeline timeline, Object manifest) {
handleSourceInfoRefreshed(index, timeline, manifest);
}
});
}
}
}
@Override
public void maybeThrowSourceInfoRefreshError() throws IOException {
for (int i = 0; i < mediaSources.length; i++) {
if (!duplicateFlags[i]) {
mediaSources[i].maybeThrowSourceInfoRefreshError();
}
}
}
@Override
public MediaPeriod createPeriod(int index, Allocator allocator, long positionUs) {
int sourceIndex = timeline.getSourceIndexForPeriod(index);
int periodIndexInSource = index - timeline.getFirstPeriodIndexInSource(sourceIndex);
MediaPeriod mediaPeriod = mediaSources[sourceIndex].createPeriod(periodIndexInSource, allocator,
positionUs);
sourceIndexByMediaPeriod.put(mediaPeriod, sourceIndex);
return mediaPeriod;
}
@Override
public void releasePeriod(MediaPeriod mediaPeriod) {
int sourceIndex = sourceIndexByMediaPeriod.get(mediaPeriod);
sourceIndexByMediaPeriod.remove(mediaPeriod);
mediaSources[sourceIndex].releasePeriod(mediaPeriod);
}
@Override
public void releaseSource() {
for (int i = 0; i < mediaSources.length; i++) {
if (!duplicateFlags[i]) {
mediaSources[i].releaseSource();
}
}
}
private void handleSourceInfoRefreshed(int sourceFirstIndex, Timeline sourceTimeline,
Object sourceManifest) {
// Set the timeline and manifest.
timelines[sourceFirstIndex] = sourceTimeline;
manifests[sourceFirstIndex] = sourceManifest;
// Also set the timeline and manifest for any duplicate entries of the same source.
for (int i = sourceFirstIndex + 1; i < mediaSources.length; i++) {
if (mediaSources[i] == mediaSources[sourceFirstIndex]) {
timelines[i] = sourceTimeline;
manifests[i] = sourceManifest;
}
}
for (Timeline timeline : timelines) {
if (timeline == null) {
// Don't invoke the listener until all sources have timelines.
return;
}
}
timeline = new ConcatenatedTimeline(timelines.clone());
listener.onSourceInfoRefreshed(timeline, manifests.clone());
}
private static boolean[] buildDuplicateFlags(MediaSource[] mediaSources) {
boolean[] duplicateFlags = new boolean[mediaSources.length];
IdentityHashMap<MediaSource, Void> sources = new IdentityHashMap<>(mediaSources.length);
for (int i = 0; i < mediaSources.length; i++) {
MediaSource source = mediaSources[i];
if (!sources.containsKey(source)) {
sources.put(source, null);
} else {
duplicateFlags[i] = true;
}
}
return duplicateFlags;
}
/**
* A {@link Timeline} that is the concatenation of one or more {@link Timeline}s.
*/
private static final class ConcatenatedTimeline extends Timeline {
private final Timeline[] timelines;
private final int[] sourcePeriodOffsets;
private final int[] sourceWindowOffsets;
public ConcatenatedTimeline(Timeline[] timelines) {
int[] sourcePeriodOffsets = new int[timelines.length];
int[] sourceWindowOffsets = new int[timelines.length];
long periodCount = 0;
int windowCount = 0;
for (int i = 0; i < timelines.length; i++) {
Timeline timeline = timelines[i];
periodCount += timeline.getPeriodCount();
Assertions.checkState(periodCount <= Integer.MAX_VALUE,
"ConcatenatingMediaSource children contain too many periods");
sourcePeriodOffsets[i] = (int) periodCount;
windowCount += timeline.getWindowCount();
sourceWindowOffsets[i] = windowCount;
}
this.timelines = timelines;
this.sourcePeriodOffsets = sourcePeriodOffsets;
this.sourceWindowOffsets = sourceWindowOffsets;
}
@Override
public int getWindowCount() {
return sourceWindowOffsets[sourceWindowOffsets.length - 1];
}
@Override
public Window getWindow(int windowIndex, Window window, boolean setIds,
long defaultPositionProjectionUs) {
int sourceIndex = getSourceIndexForWindow(windowIndex);
int firstWindowIndexInSource = getFirstWindowIndexInSource(sourceIndex);
int firstPeriodIndexInSource = getFirstPeriodIndexInSource(sourceIndex);
timelines[sourceIndex].getWindow(windowIndex - firstWindowIndexInSource, window, setIds,
defaultPositionProjectionUs);
window.firstPeriodIndex += firstPeriodIndexInSource;
window.lastPeriodIndex += firstPeriodIndexInSource;
return window;
}
@Override
public int getPeriodCount() {
return sourcePeriodOffsets[sourcePeriodOffsets.length - 1];
}
@Override
public Period getPeriod(int periodIndex, Period period, boolean setIds) {
int sourceIndex = getSourceIndexForPeriod(periodIndex);
int firstWindowIndexInSource = getFirstWindowIndexInSource(sourceIndex);
int firstPeriodIndexInSource = getFirstPeriodIndexInSource(sourceIndex);
timelines[sourceIndex].getPeriod(periodIndex - firstPeriodIndexInSource, period, setIds);
period.windowIndex += firstWindowIndexInSource;
if (setIds) {
period.uid = Pair.create(sourceIndex, period.uid);
}
return period;
}
@Override
public int getIndexOfPeriod(Object uid) {
if (!(uid instanceof Pair)) {
return C.INDEX_UNSET;
}
Pair<?, ?> sourceIndexAndPeriodId = (Pair<?, ?>) uid;
if (!(sourceIndexAndPeriodId.first instanceof Integer)) {
return C.INDEX_UNSET;
}
int sourceIndex = (Integer) sourceIndexAndPeriodId.first;
Object periodId = sourceIndexAndPeriodId.second;
if (sourceIndex < 0 || sourceIndex >= timelines.length) {
return C.INDEX_UNSET;
}
int periodIndexInSource = timelines[sourceIndex].getIndexOfPeriod(periodId);
return periodIndexInSource == C.INDEX_UNSET ? C.INDEX_UNSET
: getFirstPeriodIndexInSource(sourceIndex) + periodIndexInSource;
}
private int getSourceIndexForPeriod(int periodIndex) {
return Util.binarySearchFloor(sourcePeriodOffsets, periodIndex, true, false) + 1;
}
private int getFirstPeriodIndexInSource(int sourceIndex) {
return sourceIndex == 0 ? 0 : sourcePeriodOffsets[sourceIndex - 1];
}
private int getSourceIndexForWindow(int windowIndex) {
return Util.binarySearchFloor(sourceWindowOffsets, windowIndex, true, false) + 1;
}
private int getFirstWindowIndexInSource(int sourceIndex) {
return sourceIndex == 0 ? 0 : sourceWindowOffsets[sourceIndex - 1];
}
}
}
| JungleTian/Telegram | TMessagesProj/src/main/java/org/telegram/messenger/exoplayer2/source/ConcatenatingMediaSource.java | Java | gpl-2.0 | 9,121 |
<?php
/**
*
* Adapted from Edward McIntyre's wp_bootstrap_navwalker class.
* Removed support for glyphicon and added support for Font Awesome
*
*/
/**
* Class Name: wp_bootstrap_navwalker
* GitHub URI: https://github.com/twittem/wp-bootstrap-navwalker
* Description: A custom WordPress nav walker class to implement the Bootstrap 3 navigation style in a custom theme using the WordPress built in menu manager.
* Version: 2.0.4
* Author: Edward McIntyre - @twittem
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
*/
//exit if accessed directly
if(!defined('ABSPATH')) exit;
class cronista_navwalker extends Walker_Nav_Menu {
/**
* @see Walker::start_lvl()
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of page. Used for padding.
*/
public function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat( "\t", $depth );
$output .= "\n$indent<ul role=\"menu\" class=\" dropdown-menu\">\n";
}
/**
* @see Walker::start_el()
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param int $current_page Menu item ID.
* @param object $args
*/
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
/**
* Dividers, Headers or Disabled
* =============================
* Determine whether the item is a Divider, Header, Disabled or regular
* menu item. To prevent errors we use the strcasecmp() function to so a
* comparison that is not case sensitive. The strcasecmp() function returns
* a 0 if the strings are equal.
*/
if ( strcasecmp( $item->attr_title, 'divider' ) == 0 && $depth === 1 ) {
$output .= $indent . '<li role="presentation" class="divider">';
} else if ( strcasecmp( $item->title, 'divider') == 0 && $depth === 1 ) {
$output .= $indent . '<li role="presentation" class="divider">';
} else if ( strcasecmp( $item->attr_title, 'dropdown-header') == 0 && $depth === 1 ) {
$output .= $indent . '<li role="presentation" class="dropdown-header">' . esc_attr( $item->title );
} else if ( strcasecmp($item->attr_title, 'disabled' ) == 0 ) {
$output .= $indent . '<li role="presentation" class="disabled"><a href="#">' . esc_attr( $item->title ) . '</a>';
} else {
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
/*
if ( $args->has_children )
$class_names .= ' dropdown';
*/
if($args->has_children && $depth === 0) { $class_names .= ' dropdown'; } elseif($args->has_children && $depth > 0) { $class_names .= ' dropdown-submenu'; }
if ( in_array( 'current-menu-item', $classes ) )
$class_names .= ' active';
// remove Font Awesome icon from classes array and save the icon
// we will add the icon back in via a <span> below so it aligns with
// the menu item
if ( in_array('fa', $classes)) {
$key = array_search('fa', $classes);
$icon = $classes[$key + 1];
$class_names = str_replace($classes[$key+1], '', $class_names);
$class_names = str_replace($classes[$key], '', $class_names);
}
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li' . $id . $value . $class_names .'>';
$atts = array();
$atts['title'] = ! empty( $item->title ) ? $item->title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : '';
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';
// If item has_children add atts to a.
// if ( $args->has_children && $depth === 0 ) {
if ( $args->has_children ) {
$atts['href'] = '#';
$atts['data-toggle'] = 'dropdown';
$atts['class'] = 'dropdown-toggle';
} else {
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
}
$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args );
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( ! empty( $value ) ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
$item_output = $args->before;
// Font Awesome icons
if ( ! empty( $icon ) )
$item_output .= '<a'. $attributes .'><span class="fa ' . esc_attr( $icon ) . '"></span> ';
else
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$item_output .= ( $args->has_children && 0 === $depth ) ? ' <span class="caret"></span></a>' : '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
/**
* Traverse elements to create list from elements.
*
* Display one element if the element doesn't have any children otherwise,
* display the element and its children. Will only traverse up to the max
* depth and no ignore elements under that depth.
*
* This method shouldn't be called directly, use the walk() method instead.
*
* @see Walker::start_el()
* @since 2.5.0
*
* @param object $element Data object
* @param array $children_elements List of elements to continue traversing.
* @param int $max_depth Max depth to traverse.
* @param int $depth Depth of current element.
* @param array $args
* @param string $output Passed by reference. Used to append additional content.
* @return null Null on failure with no changes to parameters.
*/
public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
if ( ! $element )
return;
$id_field = $this->db_fields['id'];
// Display this element.
if ( is_object( $args[0] ) )
$args[0]->has_children = ! empty( $children_elements[ $element->$id_field ] );
parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
}
/**
* Menu Fallback
* =============
* If this function is assigned to the wp_nav_menu's fallback_cb variable
* and a manu has not been assigned to the theme location in the WordPress
* menu manager the function with display nothing to a non-logged in user,
* and will add a link to the WordPress menu manager if logged in as an admin.
*
* @param array $args passed from the wp_nav_menu function.
*
*/
public static function fallback( $args ) {
if ( current_user_can( 'manage_options' ) ) {
extract( $args );
$fb_output = null;
if ( $container ) {
$fb_output = '<' . $container;
if ( $container_id )
$fb_output .= ' id="' . $container_id . '"';
if ( $container_class )
$fb_output .= ' class="' . $container_class . '"';
$fb_output .= '>';
}
$fb_output .= '<ul';
if ( $menu_id )
$fb_output .= ' id="' . $menu_id . '"';
if ( $menu_class )
$fb_output .= ' class="' . $menu_class . '"';
$fb_output .= '>';
$fb_output .= '<li><a href="' . esc_url(admin_url( 'nav-menus.php' )) . '">'.__('Asigna un menu','cronista').'</a></li>';
$fb_output .= '</ul>';
if ( $container )
$fb_output .= '</' . $container . '>';
echo $fb_output;
}
}
} | ttthanhDC/ProjectTeamWP | wp-content/themes/cronista/assets/functions/cronista_navwalker.php | PHP | gpl-2.0 | 7,699 |
<?php
namespace TYPO3\Flow\Persistence\Doctrine\Proxies\__CG__\project\emulate\Domain\Model;
/**
* THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
*/
class UserAccount extends \project\emulate\Domain\Model\UserAccount implements \Doctrine\ORM\Proxy\Proxy
{
private $_entityPersister;
private $_identifier;
public $__isInitialized__ = false;
public function __construct($entityPersister, $identifier)
{
$this->_entityPersister = $entityPersister;
$this->_identifier = $identifier;
}
/** @private */
public function __load()
{
if (!$this->__isInitialized__ && $this->_entityPersister) {
$this->__isInitialized__ = true;
if (method_exists($this, "__wakeup")) {
// call this after __isInitialized__to avoid infinite recursion
// but before loading to emulate what ClassMetadata::newInstance()
// provides.
$this->__wakeup();
}
if ($this->_entityPersister->load($this->_identifier, $this) === null) {
throw new \Doctrine\ORM\EntityNotFoundException();
}
unset($this->_entityPersister, $this->_identifier);
}
}
/** @private */
public function __isInitialized()
{
return $this->__isInitialized__;
}
public function __wakeup()
{
$this->__load();
return parent::__wakeup();
}
public function Flow_Aop_Proxy_fixMethodsAndAdvicesArrayForDoctrineProxies()
{
$this->__load();
return parent::Flow_Aop_Proxy_fixMethodsAndAdvicesArrayForDoctrineProxies();
}
public function Flow_Aop_Proxy_fixInjectedPropertiesForDoctrineProxies()
{
$this->__load();
return parent::Flow_Aop_Proxy_fixInjectedPropertiesForDoctrineProxies();
}
public function Flow_Aop_Proxy_invokeJoinPoint(\TYPO3\Flow\Aop\JoinPointInterface $joinPoint)
{
$this->__load();
return parent::Flow_Aop_Proxy_invokeJoinPoint($joinPoint);
}
public function getName()
{
$this->__load();
return parent::getName();
}
public function setName($name)
{
$this->__load();
return parent::setName($name);
}
public function getgender()
{
$this->__load();
return parent::getgender();
}
public function setgender($gender)
{
$this->__load();
return parent::setgender($gender);
}
public function getUsername()
{
$this->__load();
return parent::getUsername();
}
public function setUsername($username)
{
$this->__load();
return parent::setUsername($username);
}
public function getPassword()
{
$this->__load();
return parent::getPassword();
}
public function setPassword($password)
{
$this->__load();
return parent::setPassword($password);
}
public function getEmail()
{
$this->__load();
return parent::getEmail();
}
public function setEmail($email)
{
$this->__load();
return parent::setEmail($email);
}
public function getProfilePic()
{
$this->__load();
return parent::getProfilePic();
}
public function setProfilePic($profilePic)
{
$this->__load();
return parent::setProfilePic($profilePic);
}
public function getEmulatorPreference()
{
$this->__load();
return parent::getEmulatorPreference();
}
public function setEmulatorPreference($emulatorPreference)
{
$this->__load();
return parent::setEmulatorPreference($emulatorPreference);
}
public function getEmulatorMode()
{
$this->__load();
return parent::getEmulatorMode();
}
public function setEmulatorMode($emulatorMode)
{
$this->__load();
return parent::setEmulatorMode($emulatorMode);
}
public function Validate($userAccountRepository, $user)
{
$this->__load();
return parent::Validate($userAccountRepository, $user);
}
public function __sleep()
{
return array_merge(array('__isInitialized__'), parent::__sleep());
}
public function __clone()
{
if (!$this->__isInitialized__ && $this->_entityPersister) {
$this->__isInitialized__ = true;
$class = $this->_entityPersister->getClassMetadata();
$original = $this->_entityPersister->load($this->_identifier);
if ($original === null) {
throw new \Doctrine\ORM\EntityNotFoundException();
}
foreach ($class->reflFields as $field => $reflProperty) {
$reflProperty->setValue($this, $reflProperty->getValue($original));
}
unset($this->_entityPersister, $this->_identifier);
}
parent::__clone();
}
} | garvitdelhi/emulate | Data/Temporary/Development/Doctrine/Proxies/__CG__projectemulateDomainModelUserAccount.php | PHP | gpl-2.0 | 4,993 |
from settings import *
import pymysql
def getconn():
conn = pymysql.connect( charset = 'utf8',
host = DATABASES['default']['HOST'],
port = DATABASES['default']['PORT'],
user = DATABASES['default']['USER'],
passwd = DATABASES['default']['PASSWORD'],
db = DATABASES['default']['NAME'])
return conn
def loadSqlScript(sqlScript):
f = open(sqlScript)
query = ''
for line in f:
query = query + line
return query
| kassine/caparis2mysql | sqlTools.py | Python | gpl-2.0 | 602 |
/****************************************************************************
** $Id: qpngio.cpp 2 2005-11-16 15:49:26Z dmik $
**
** Implementation of PNG QImage IOHandler
**
** Created : 970521
**
** Copyright (C) 1992-2003 Trolltech AS. All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed under the terms of the Q Public License
** as defined by Trolltech AS of Norway and appearing in the file
** LICENSE.QPL included in the packaging of this file.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses may use this file in accordance with the Qt Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
** information about Qt Commercial License Agreements.
** See http://www.trolltech.com/qpl/ for QPL licensing information.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include "qpngio.h"
#ifndef QT_NO_IMAGEIO_PNG
#include "qasyncimageio.h"
#include "qiodevice.h"
#include <png.h>
#ifdef Q_OS_TEMP
#define CALLBACK_CALL_TYPE __cdecl
#else
#define CALLBACK_CALL_TYPE
#endif
/*
All PNG files load to the minimal QImage equivalent.
All QImage formats output to reasonably efficient PNG equivalents.
Never to grayscale.
*/
#if defined(Q_C_CALLBACKS)
extern "C" {
#endif
static
void CALLBACK_CALL_TYPE iod_read_fn(png_structp png_ptr, png_bytep data, png_size_t length)
{
QImageIO* iio = (QImageIO*)png_get_io_ptr(png_ptr);
QIODevice* in = iio->ioDevice();
while (length) {
int nr = in->readBlock((char*)data, length);
if (nr <= 0) {
png_error(png_ptr, "Read Error");
return;
}
length -= nr;
}
}
static
void CALLBACK_CALL_TYPE qpiw_write_fn( png_structp png_ptr, png_bytep data, png_size_t length )
{
QPNGImageWriter* qpiw = (QPNGImageWriter*)png_get_io_ptr( png_ptr );
QIODevice* out = qpiw->device();
uint nr = out->writeBlock( (char*)data, length );
if ( nr != length ) {
png_error( png_ptr, "Write Error" );
return;
}
}
static
void CALLBACK_CALL_TYPE qpiw_flush_fn( png_structp png_ptr )
{
QPNGImageWriter* qpiw = (QPNGImageWriter*)png_get_io_ptr( png_ptr );
QIODevice* out = qpiw->device();
out->flush();
}
#if defined(Q_C_CALLBACKS)
}
#endif
static
void setup_qt( QImage& image, png_structp png_ptr, png_infop info_ptr, float screen_gamma=0.0 )
{
if ( screen_gamma != 0.0 && png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) ) {
double file_gamma;
png_get_gAMA(png_ptr, info_ptr, &file_gamma);
png_set_gamma( png_ptr, screen_gamma, file_gamma );
}
png_uint_32 width;
png_uint_32 height;
int bit_depth;
int color_type;
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
0, 0, 0);
if ( color_type == PNG_COLOR_TYPE_GRAY ) {
// Black & White or 8-bit grayscale
if ( bit_depth == 1 && info_ptr->channels == 1 ) {
png_set_invert_mono( png_ptr );
png_read_update_info( png_ptr, info_ptr );
if (!image.create( width, height, 1, 2, QImage::BigEndian ))
return;
image.setColor( 1, qRgb(0,0,0) );
image.setColor( 0, qRgb(255,255,255) );
} else if (bit_depth == 16 && png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
png_set_expand(png_ptr);
png_set_strip_16(png_ptr);
png_set_gray_to_rgb(png_ptr);
if (!image.create(width, height, 32))
return;
image.setAlphaBuffer(TRUE);
if (QImage::systemByteOrder() == QImage::BigEndian)
png_set_swap_alpha(png_ptr);
png_read_update_info(png_ptr, info_ptr);
} else {
if ( bit_depth == 16 )
png_set_strip_16(png_ptr);
else if ( bit_depth < 8 )
png_set_packing(png_ptr);
int ncols = bit_depth < 8 ? 1 << bit_depth : 256;
png_read_update_info(png_ptr, info_ptr);
if (!image.create(width, height, 8, ncols))
return;
for (int i=0; i<ncols; i++) {
int c = i*255/(ncols-1);
image.setColor( i, qRgba(c,c,c,0xff) );
}
if ( png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ) {
const int g = info_ptr->trans_values.gray;
if (g < ncols) {
image.setAlphaBuffer(TRUE);
image.setColor(g, image.color(g) & RGB_MASK);
}
}
}
} else if ( color_type == PNG_COLOR_TYPE_PALETTE
&& png_get_valid(png_ptr, info_ptr, PNG_INFO_PLTE)
&& info_ptr->num_palette <= 256 )
{
// 1-bit and 8-bit color
if ( bit_depth != 1 )
png_set_packing( png_ptr );
png_read_update_info( png_ptr, info_ptr );
png_get_IHDR(png_ptr, info_ptr,
&width, &height, &bit_depth, &color_type, 0, 0, 0);
if (!image.create(width, height, bit_depth, info_ptr->num_palette,
QImage::BigEndian))
return;
int i = 0;
if ( png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ) {
image.setAlphaBuffer( TRUE );
while ( i < info_ptr->num_trans ) {
image.setColor(i, qRgba(
info_ptr->palette[i].red,
info_ptr->palette[i].green,
info_ptr->palette[i].blue,
info_ptr->trans[i]
)
);
i++;
}
}
while ( i < info_ptr->num_palette ) {
image.setColor(i, qRgba(
info_ptr->palette[i].red,
info_ptr->palette[i].green,
info_ptr->palette[i].blue,
0xff
)
);
i++;
}
} else {
// 32-bit
if ( bit_depth == 16 )
png_set_strip_16(png_ptr);
png_set_expand(png_ptr);
if ( color_type == PNG_COLOR_TYPE_GRAY_ALPHA )
png_set_gray_to_rgb(png_ptr);
if (!image.create(width, height, 32))
return;
// Only add filler if no alpha, or we can get 5 channel data.
if (!(color_type & PNG_COLOR_MASK_ALPHA)
&& !png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
png_set_filler(png_ptr, 0xff,
QImage::systemByteOrder() == QImage::BigEndian ?
PNG_FILLER_BEFORE : PNG_FILLER_AFTER);
// We want 4 bytes, but it isn't an alpha channel
} else {
image.setAlphaBuffer(TRUE);
}
if ( QImage::systemByteOrder() == QImage::BigEndian ) {
png_set_swap_alpha(png_ptr);
}
png_read_update_info(png_ptr, info_ptr);
}
// Qt==ARGB==Big(ARGB)==Little(BGRA)
if ( QImage::systemByteOrder() == QImage::LittleEndian ) {
png_set_bgr(png_ptr);
}
}
#if defined(Q_C_CALLBACKS)
extern "C" {
#endif
static void CALLBACK_CALL_TYPE qt_png_warning(png_structp /*png_ptr*/, png_const_charp message)
{
qWarning("libpng warning: %s", message);
}
#if defined(Q_C_CALLBACKS)
}
#endif
static
void read_png_image(QImageIO* iio)
{
png_structp png_ptr;
png_infop info_ptr;
png_infop end_info;
png_bytep* row_pointers;
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,0,0,0);
if (!png_ptr) {
iio->setStatus(-1);
return;
}
png_set_error_fn(png_ptr, 0, 0, qt_png_warning);
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, 0, 0);
iio->setStatus(-2);
return;
}
end_info = png_create_info_struct(png_ptr);
if (!end_info) {
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
iio->setStatus(-3);
return;
}
if (setjmp(png_ptr->jmpbuf)) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
iio->setStatus(-4);
return;
}
png_set_read_fn(png_ptr, (void*)iio, iod_read_fn);
png_read_info(png_ptr, info_ptr);
QImage image;
setup_qt(image, png_ptr, info_ptr, iio->gamma());
if (image.isNull()) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
iio->setStatus(-5);
return;
}
png_uint_32 width;
png_uint_32 height;
int bit_depth;
int color_type;
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
0, 0, 0);
uchar** jt = image.jumpTable();
row_pointers=new png_bytep[height];
for (uint y=0; y<height; y++) {
row_pointers[y]=jt[y];
}
png_read_image(png_ptr, row_pointers);
#if 0 // libpng takes care of this.
png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)
if (image.depth()==32 && png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
QRgb trans = 0xFF000000 | qRgb(
(info_ptr->trans_values.red << 8 >> bit_depth)&0xff,
(info_ptr->trans_values.green << 8 >> bit_depth)&0xff,
(info_ptr->trans_values.blue << 8 >> bit_depth)&0xff);
for (uint y=0; y<height; y++) {
for (uint x=0; x<info_ptr->width; x++) {
if (((uint**)jt)[y][x] == trans) {
((uint**)jt)[y][x] &= 0x00FFFFFF;
} else {
}
}
}
}
#endif
image.setDotsPerMeterX(png_get_x_pixels_per_meter(png_ptr,info_ptr));
image.setDotsPerMeterY(png_get_y_pixels_per_meter(png_ptr,info_ptr));
#ifndef QT_NO_IMAGE_TEXT
png_textp text_ptr;
int num_text=0;
png_get_text(png_ptr,info_ptr,&text_ptr,&num_text);
while (num_text--) {
image.setText(text_ptr->key,0,text_ptr->text);
text_ptr++;
}
#endif
delete [] row_pointers;
if ( image.hasAlphaBuffer() ) {
// Many PNG files lie (eg. from PhotoShop). Fortunately this loop will
// usually be quick to find those that tell the truth.
QRgb* c;
int n;
if (image.depth()==32) {
c = (QRgb*)image.bits();
n = image.bytesPerLine() * image.height() / 4;
} else {
c = image.colorTable();
n = image.numColors();
}
while ( n-- && qAlpha(*c++)==0xff )
;
if ( n<0 ) // LIAR!
image.setAlphaBuffer(FALSE);
}
iio->setImage(image);
png_read_end(png_ptr, end_info);
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
iio->setStatus(0);
}
QPNGImageWriter::QPNGImageWriter(QIODevice* iod) :
dev(iod),
frames_written(0),
disposal(Unspecified),
looping(-1),
ms_delay(-1),
gamma(0.0)
{
}
QPNGImageWriter::~QPNGImageWriter()
{
}
void QPNGImageWriter::setDisposalMethod(DisposalMethod dm)
{
disposal = dm;
}
void QPNGImageWriter::setLooping(int loops)
{
looping = loops;
}
void QPNGImageWriter::setFrameDelay(int msecs)
{
ms_delay = msecs;
}
void QPNGImageWriter::setGamma(float g)
{
gamma = g;
}
#ifndef QT_NO_IMAGE_TEXT
static void set_text(const QImage& image, png_structp png_ptr, png_infop info_ptr, bool short_not_long)
{
QValueList<QImageTextKeyLang> keys = image.textList();
if ( keys.count() ) {
png_textp text_ptr = new png_text[keys.count()];
int i=0;
for (QValueList<QImageTextKeyLang>::Iterator it=keys.begin();
it != keys.end(); ++it)
{
QString t = image.text(*it);
if ( (t.length() <= 200) == short_not_long ) {
if ( t.length() < 40 )
text_ptr[i].compression = PNG_TEXT_COMPRESSION_NONE;
else
text_ptr[i].compression = PNG_TEXT_COMPRESSION_zTXt;
text_ptr[i].key = (png_charp)(*it).key.data();
text_ptr[i].text = (png_charp)t.latin1();
//text_ptr[i].text = qstrdup(t.latin1());
i++;
}
}
png_set_text(png_ptr, info_ptr, text_ptr, i);
//for (int j=0; j<i; j++)
//free(text_ptr[i].text);
delete [] text_ptr;
}
}
#endif
bool QPNGImageWriter::writeImage(const QImage& image, int off_x, int off_y)
{
return writeImage(image, -1, off_x, off_y);
}
bool QPNGImageWriter::writeImage(const QImage& image, int quality_in, int off_x_in, int off_y_in)
{
QPoint offset = image.offset();
int off_x = off_x_in + offset.x();
int off_y = off_y_in + offset.y();
png_structp png_ptr;
png_infop info_ptr;
png_bytep* row_pointers;
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,0,0,0);
if (!png_ptr) {
return FALSE;
}
png_set_error_fn(png_ptr, 0, 0, qt_png_warning);
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, 0);
return FALSE;
}
if (setjmp(png_ptr->jmpbuf)) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return FALSE;
}
int quality = quality_in;
if (quality >= 0) {
if (quality > 9) {
#if defined(QT_CHECK_RANGE)
qWarning( "PNG: Quality %d out of range", quality );
#endif
quality = 9;
}
png_set_compression_level(png_ptr, quality);
}
if (gamma != 0.0) {
png_set_gAMA(png_ptr, info_ptr, 1.0/gamma);
}
png_set_write_fn(png_ptr, (void*)this, qpiw_write_fn, qpiw_flush_fn);
info_ptr->channels =
(image.depth() == 32)
? (image.hasAlphaBuffer() ? 4 : 3)
: 1;
png_set_IHDR(png_ptr, info_ptr, image.width(), image.height(),
image.depth() == 1 ? 1 : 8 /* per channel */,
image.depth() == 32
? image.hasAlphaBuffer()
? PNG_COLOR_TYPE_RGB_ALPHA
: PNG_COLOR_TYPE_RGB
: PNG_COLOR_TYPE_PALETTE, 0, 0, 0);
//png_set_sBIT(png_ptr, info_ptr, 8);
info_ptr->sig_bit.red = 8;
info_ptr->sig_bit.green = 8;
info_ptr->sig_bit.blue = 8;
if (image.depth() == 1 && image.bitOrder() == QImage::LittleEndian)
png_set_packswap(png_ptr);
png_colorp palette = 0;
png_bytep copy_trans = 0;
if (image.numColors()) {
// Paletted
int num_palette = image.numColors();
palette = new png_color[num_palette];
png_set_PLTE(png_ptr, info_ptr, palette, num_palette);
int* trans = new int[num_palette];
int num_trans = 0;
for (int i=0; i<num_palette; i++) {
QRgb rgb=image.color(i);
info_ptr->palette[i].red = qRed(rgb);
info_ptr->palette[i].green = qGreen(rgb);
info_ptr->palette[i].blue = qBlue(rgb);
if (image.hasAlphaBuffer()) {
trans[i] = rgb >> 24;
if (trans[i] < 255) {
num_trans = i+1;
}
}
}
if (num_trans) {
copy_trans = new png_byte[num_trans];
for (int i=0; i<num_trans; i++)
copy_trans[i] = trans[i];
png_set_tRNS(png_ptr, info_ptr, copy_trans, num_trans, 0);
}
delete [] trans;
}
if ( image.hasAlphaBuffer() ) {
info_ptr->sig_bit.alpha = 8;
}
// Swap ARGB to RGBA (normal PNG format) before saving on
// BigEndian machines
if ( QImage::systemByteOrder() == QImage::BigEndian ) {
png_set_swap_alpha(png_ptr);
}
// Qt==ARGB==Big(ARGB)==Little(BGRA)
if ( QImage::systemByteOrder() == QImage::LittleEndian ) {
png_set_bgr(png_ptr);
}
if (off_x || off_y) {
png_set_oFFs(png_ptr, info_ptr, off_x, off_y, PNG_OFFSET_PIXEL);
}
if ( frames_written > 0 )
png_set_sig_bytes(png_ptr, 8);
if ( image.dotsPerMeterX() > 0 || image.dotsPerMeterY() > 0 ) {
png_set_pHYs(png_ptr, info_ptr,
image.dotsPerMeterX(), image.dotsPerMeterY(),
PNG_RESOLUTION_METER);
}
#ifndef QT_NO_IMAGE_TEXT
// Write short texts early.
set_text(image,png_ptr,info_ptr,TRUE);
#endif
png_write_info(png_ptr, info_ptr);
#ifndef QT_NO_IMAGE_TEXT
// Write long texts later.
set_text(image,png_ptr,info_ptr,FALSE);
#endif
if ( image.depth() != 1 )
png_set_packing(png_ptr);
if ( image.depth() == 32 && !image.hasAlphaBuffer() )
png_set_filler(png_ptr, 0,
QImage::systemByteOrder() == QImage::BigEndian ?
PNG_FILLER_BEFORE : PNG_FILLER_AFTER);
if ( looping >= 0 && frames_written == 0 ) {
uchar data[13] = "NETSCAPE2.0";
// 0123456789aBC
data[0xB] = looping%0x100;
data[0xC] = looping/0x100;
png_write_chunk(png_ptr, (png_byte*)"gIFx", data, 13);
}
if ( ms_delay >= 0 || disposal!=Unspecified ) {
uchar data[4];
data[0] = disposal;
data[1] = 0;
data[2] = (ms_delay/10)/0x100; // hundredths
data[3] = (ms_delay/10)%0x100;
png_write_chunk(png_ptr, (png_byte*)"gIFg", data, 4);
}
png_uint_32 width;
png_uint_32 height;
int bit_depth;
int color_type;
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
0, 0, 0);
uchar** jt = image.jumpTable();
row_pointers=new png_bytep[height];
uint y;
for (y=0; y<height; y++) {
row_pointers[y]=jt[y];
}
png_write_image(png_ptr, row_pointers);
delete [] row_pointers;
png_write_end(png_ptr, info_ptr);
frames_written++;
if ( palette )
delete [] palette;
if ( copy_trans )
delete [] copy_trans;
png_destroy_write_struct(&png_ptr, &info_ptr);
return TRUE;
}
static
void write_png_image(QImageIO* iio)
{
QPNGImageWriter writer(iio->ioDevice());
int quality = iio->quality();
if ( quality >= 0 ) {
quality = QMIN( quality, 100 );
quality = (100-quality) * 9 / 91; // map [0,100] -> [9,0]
}
writer.setGamma(iio->gamma());
bool ok = writer.writeImage( iio->image(), quality );
iio->setStatus( ok ? 0 : -1 );
}
/*!
\class QPNGImagePacker qpngio.h
\brief The QPNGImagePacker class creates well-compressed PNG animations.
\ingroup images
\ingroup graphics
By using transparency, QPNGImagePacker allows you to build a PNG
image from a sequence of QImages.
Images are added using packImage().
*/
/*!
Creates an image packer that writes PNG data to IO device \a iod
using a \a storage_depth bit encoding (use 8 or 32, depending on
the desired quality and compression requirements).
If the image needs to be modified to fit in a lower-resolution
result (e.g. converting from 32-bit to 8-bit), use the \a
conversionflags to specify how you'd prefer this to happen.
\sa Qt::ImageConversionFlags
*/
QPNGImagePacker::QPNGImagePacker(QIODevice* iod, int storage_depth,
int conversionflags) :
QPNGImageWriter(iod),
depth(storage_depth),
convflags(conversionflags),
alignx(1)
{
}
/*!
Aligns pixel differences to \a x pixels. For example, using 8 can
improve playback on certain hardware. Normally the default of
1-pixel alignment (i.e. no alignment) gives better compression and
performance.
*/
void QPNGImagePacker::setPixelAlignment(int x)
{
alignx = x;
}
/*!
Adds the image \a img to the PNG animation, analyzing the
differences between this and the previous image to improve
compression.
*/
bool QPNGImagePacker::packImage(const QImage& img)
{
QImage image = img.convertDepth(32);
if ( previous.isNull() ) {
// First image
writeImage(image.convertDepth(depth,convflags));
} else {
bool done;
int minx, maxx, miny, maxy;
int w = image.width();
int h = image.height();
QRgb** jt = (QRgb**)image.jumpTable();
QRgb** pjt = (QRgb**)previous.jumpTable();
// Find left edge of change
done = FALSE;
for (minx = 0; minx < w && !done; minx++) {
for (int ty = 0; ty < h; ty++) {
if ( jt[ty][minx] != pjt[ty][minx] ) {
done = TRUE;
break;
}
}
}
minx--;
// Find right edge of change
done = FALSE;
for (maxx = w-1; maxx >= 0 && !done; maxx--) {
for (int ty = 0; ty < h; ty++) {
if ( jt[ty][maxx] != pjt[ty][maxx] ) {
done = TRUE;
break;
}
}
}
maxx++;
// Find top edge of change
done = FALSE;
for (miny = 0; miny < h && !done; miny++) {
for (int tx = 0; tx < w; tx++) {
if ( jt[miny][tx] != pjt[miny][tx] ) {
done = TRUE;
break;
}
}
}
miny--;
// Find right edge of change
done = FALSE;
for (maxy = h-1; maxy >= 0 && !done; maxy--) {
for (int tx = 0; tx < w; tx++) {
if ( jt[maxy][tx] != pjt[maxy][tx] ) {
done = TRUE;
break;
}
}
}
maxy++;
if ( minx > maxx ) minx=maxx=0;
if ( miny > maxy ) miny=maxy=0;
if ( alignx > 1 ) {
minx -= minx % alignx;
maxx = maxx - maxx % alignx + alignx - 1;
}
int dw = maxx-minx+1;
int dh = maxy-miny+1;
QImage diff(dw, dh, 32);
diff.setAlphaBuffer(TRUE);
int x, y;
if ( alignx < 1 )
alignx = 1;
for (y = 0; y < dh; y++) {
QRgb* li = (QRgb*)image.scanLine(y+miny)+minx;
QRgb* lp = (QRgb*)previous.scanLine(y+miny)+minx;
QRgb* ld = (QRgb*)diff.scanLine(y);
if ( alignx ) {
for (x = 0; x < dw; x+=alignx) {
int i;
for (i=0; i<alignx; i++) {
if ( li[x+i] != lp[x+i] )
break;
}
if ( i == alignx ) {
// All the same
for (i=0; i<alignx; i++) {
ld[x+i] = qRgba(0,0,0,0);
}
} else {
// Some different
for (i=0; i<alignx; i++) {
ld[x+i] = 0xff000000 | li[x+i];
}
}
}
} else {
for (x = 0; x < dw; x++) {
if ( li[x] != lp[x] )
ld[x] = 0xff000000 | li[x];
else
ld[x] = qRgba(0,0,0,0);
}
}
}
diff = diff.convertDepth(depth,convflags);
if ( !writeImage(diff, minx, miny) )
return FALSE;
}
previous = image;
return TRUE;
}
#ifndef QT_NO_ASYNC_IMAGE_IO
class QPNGFormat : public QImageFormat {
public:
QPNGFormat();
virtual ~QPNGFormat();
int decode(QImage& img, QImageConsumer* consumer,
const uchar* buffer, int length);
void info(png_structp png_ptr, png_infop info);
void row(png_structp png_ptr, png_bytep new_row,
png_uint_32 row_num, int pass);
void end(png_structp png_ptr, png_infop info);
#ifdef PNG_USER_CHUNKS_SUPPORTED
int user_chunk(png_structp png_ptr,
png_bytep data, png_uint_32 length);
#endif
private:
// Animation-level information
enum { MovieStart, FrameStart, Inside, End } state;
int first_frame;
int base_offx;
int base_offy;
// Image-level information
png_structp png_ptr;
png_infop info_ptr;
// Temporary locals during single data-chunk processing
QImageConsumer* consumer;
QImage* image;
int unused_data;
};
class QPNGFormatType : public QImageFormatType
{
QImageFormat* decoderFor(const uchar* buffer, int length);
const char* formatName() const;
};
/*
\class QPNGFormat qpngio.h
\brief The QPNGFormat class provides an incremental image decoder for PNG
image format.
\ingroup images
\ingroup graphics
This subclass of QImageFormat decodes PNG format images,
including animated PNGs.
Animated PNG images are standard PNG images. The PNG standard
defines two extension chunks that are useful for animations:
\list
\i gIFg - GIF-like Graphic Control Extension.
This includes frame disposal, user input flag (we ignore this),
and inter-frame delay.
\i gIFx - GIF-like Application Extension.
This is multi-purpose, but we just use the Netscape extension
which specifies looping.
\endlist
The subimages usually contain a offset chunk (oFFs) but need not.
The first image defines the "screen" size. Any subsequent image that
doesn't fit is clipped.
*/
/* ###TODO: decide on this point. gIFg gives disposal types, so it can be done.
All images paste (\e not composite, just place all-channel copying)
over the previous image to produce a subsequent frame.
*/
/*
\class QPNGFormatType qasyncimageio.h
\brief The QPNGFormatType class provides an incremental image decoder
for PNG image format.
\ingroup images
\ingroup graphics
\ingroup io
This subclass of QImageFormatType recognizes PNG format images, creating
a QPNGFormat when required. An instance of this class is created
automatically before any other factories, so you should have no need for
such objects.
*/
QImageFormat* QPNGFormatType::decoderFor(
const uchar* buffer, int length)
{
if (length < 8) return 0;
if (buffer[0]==137
&& buffer[1]=='P'
&& buffer[2]=='N'
&& buffer[3]=='G'
&& buffer[4]==13
&& buffer[5]==10
&& buffer[6]==26
&& buffer[7]==10)
return new QPNGFormat;
return 0;
}
const char* QPNGFormatType::formatName() const
{
return "PNG";
}
#if defined(Q_C_CALLBACKS)
extern "C" {
#endif
static void
CALLBACK_CALL_TYPE info_callback(png_structp png_ptr, png_infop info)
{
QPNGFormat* that = (QPNGFormat*)png_get_progressive_ptr(png_ptr);
that->info(png_ptr,info);
}
static void
CALLBACK_CALL_TYPE row_callback(png_structp png_ptr, png_bytep new_row,
png_uint_32 row_num, int pass)
{
QPNGFormat* that = (QPNGFormat*)png_get_progressive_ptr(png_ptr);
that->row(png_ptr,new_row,row_num,pass);
}
static void
CALLBACK_CALL_TYPE end_callback(png_structp png_ptr, png_infop info)
{
QPNGFormat* that = (QPNGFormat*)png_get_progressive_ptr(png_ptr);
that->end(png_ptr,info);
}
#if 0
#ifdef PNG_USER_CHUNKS_SUPPORTED
static int
CALLBACK_CALL_TYPE user_chunk_callback(png_structp png_ptr,
png_unknown_chunkp chunk)
{
QPNGFormat* that = (QPNGFormat*)png_get_progressive_ptr(png_ptr);
return that->user_chunk(png_ptr,chunk->data,chunk->size);
}
#endif
#endif
#if defined(Q_C_CALLBACKS)
}
#endif
/*!
Constructs a QPNGFormat object.
*/
QPNGFormat::QPNGFormat()
{
state = MovieStart;
first_frame = 1;
base_offx = 0;
base_offy = 0;
png_ptr = 0;
info_ptr = 0;
}
/*!
Destroys a QPNGFormat object.
*/
QPNGFormat::~QPNGFormat()
{
if ( png_ptr )
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
}
/*!
This function decodes some data into image changes.
Returns the number of bytes consumed.
*/
int QPNGFormat::decode(QImage& img, QImageConsumer* cons,
const uchar* buffer, int length)
{
consumer = cons;
image = &img;
if ( state != Inside ) {
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
if (!png_ptr) {
info_ptr = 0;
image = 0;
return -1;
}
png_set_error_fn(png_ptr, 0, 0, qt_png_warning);
png_set_compression_level(png_ptr, 9);
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
image = 0;
return -1;
}
if (setjmp((png_ptr)->jmpbuf)) {
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
image = 0;
return -1;
}
png_set_progressive_read_fn(png_ptr, (void *)this,
info_callback, row_callback, end_callback);
#ifdef PNG_USER_CHUNKS_SUPPORTED
// Can't do this yet. libpng has a crash bug with unknown (user) chunks.
// Warwick has sent them a patch.
// png_set_read_user_chunk_fn(png_ptr, 0, user_chunk_callback);
// png_set_keep_unknown_chunks(png_ptr, 2/*HANDLE_CHUNK_IF_SAFE*/, 0, 0);
#endif
if ( state != MovieStart && *buffer != 0211 ) {
// Good, no signature - the preferred way to concat PNG images.
// Skip them.
png_set_sig_bytes(png_ptr, 8);
}
state = Inside;
}
if ( !png_ptr ) return 0;
if (setjmp(png_ptr->jmpbuf)) {
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
image = 0;
state = MovieStart;
return -1;
}
unused_data = 0;
png_process_data(png_ptr, info_ptr, (png_bytep)buffer, length);
int l = length - unused_data;
// TODO: send incremental stuff to consumer (optional)
if ( state != Inside ) {
if ( png_ptr )
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
}
image = 0;
return l;
}
void QPNGFormat::info(png_structp png, png_infop)
{
png_set_interlace_handling(png);
setup_qt(*image, png, info_ptr);
}
void QPNGFormat::row(png_structp png, png_bytep new_row,
png_uint_32 row_num, int)
{
uchar* old_row = image->scanLine(row_num);
png_progressive_combine_row(png, old_row, new_row);
}
void QPNGFormat::end(png_structp png, png_infop info)
{
int offx = png_get_x_offset_pixels(png,info) - base_offx;
int offy = png_get_y_offset_pixels(png,info) - base_offy;
if ( first_frame ) {
base_offx = offx;
base_offy = offy;
first_frame = 0;
}
image->setOffset(QPoint(offx,offy));
image->setDotsPerMeterX(png_get_x_pixels_per_meter(png,info));
image->setDotsPerMeterY(png_get_y_pixels_per_meter(png,info));
#ifndef QT_NO_IMAGE_TEXT
png_textp text_ptr;
int num_text=0;
png_get_text(png,info,&text_ptr,&num_text);
while (num_text--) {
image->setText(text_ptr->key,0,text_ptr->text);
text_ptr++;
}
#endif
QRect r(0,0,image->width(),image->height());
consumer->frameDone(QPoint(offx,offy),r);
consumer->end();
state = FrameStart;
unused_data = (int)png->buffer_size; // Since libpng doesn't tell us
}
#ifdef PNG_USER_CHUNKS_SUPPORTED
/*
#ifndef QT_NO_IMAGE_TEXT
static bool skip(png_uint_32& max, png_bytep& data)
{
while (*data) {
if ( !max ) return FALSE;
max--;
data++;
}
if ( !max ) return FALSE;
max--;
data++; // skip to after NUL
return TRUE;
}
#endif
*/
int QPNGFormat::user_chunk(png_structp png,
png_bytep data, png_uint_32 length)
{
#if 0 // NOT SUPPORTED: experimental PNG animation.
// qDebug("Got %ld-byte %s chunk", length, png->chunk_name);
if ( 0==qstrcmp((char*)png->chunk_name, "gIFg")
&& length == 4 ) {
//QPNGImageWriter::DisposalMethod disposal =
// (QPNGImageWriter::DisposalMethod)data[0];
// ### TODO: use the disposal method
int ms_delay = ((data[2] << 8) | data[3])*10;
consumer->setFramePeriod(ms_delay);
return 1;
} else if ( 0==qstrcmp((char*)png->chunk_name, "gIFx")
&& length == 13 ) {
if ( qstrncmp((char*)data,"NETSCAPE2.0",11)==0 ) {
int looping = (data[0xC]<<8)|data[0xB];
consumer->setLooping(looping);
return 1;
}
}
#else
Q_UNUSED( png )
Q_UNUSED( data )
Q_UNUSED( length )
#endif
#ifndef QT_NO_IMAGE_TEXT
/*
libpng now supports this chunk.
if ( 0==qstrcmp((char*)png->chunk_name, "iTXt") && length>=6 ) {
const char* keyword = (const char*)data;
if ( !skip(length,data) ) return 0;
if ( length >= 4 ) {
char compression_flag = *data++;
char compression_method = *data++;
if ( compression_flag == compression_method ) {
// fool the compiler into thinking they're used
}
const char* lang = (const char*)data;
if ( !skip(length,data) ) return 0;
// const char* keyword_utf8 = (const char*)data;
if ( !skip(length,data) ) return 0;
const char* text_utf8 = (const char*)data;
if ( !skip(length,data) ) return 0;
QString text = QString::fromUtf8(text_utf8);
image->setText(keyword,lang[0] ? lang : 0,text);
return 1;
}
}
*/
#endif
return 0;
}
#endif
static QPNGFormatType* globalPngFormatTypeObject = 0;
#endif // QT_NO_ASYNC_IMAGE_IO
static bool done = FALSE;
void qCleanupPngIO()
{
#ifndef QT_NO_ASYNC_IMAGE_IO
if ( globalPngFormatTypeObject ) {
delete globalPngFormatTypeObject;
globalPngFormatTypeObject = 0;
}
#endif
done = FALSE;
}
void qInitPngIO()
{
if ( !done ) {
done = TRUE;
QImageIO::defineIOHandler( "PNG", "^.PNG\r", 0, read_png_image,
write_png_image);
#ifndef QT_NO_ASYNC_IMAGE_IO
globalPngFormatTypeObject = new QPNGFormatType;
#endif
qAddPostRoutine( qCleanupPngIO );
}
}
void qt_zlib_compression_hack()
{
compress(0,0,0,0);
uncompress(0,0,0,0);
}
#endif // QT_NO_IMAGEIO_PNG
| OS2World/LIB-QT3_Toolkit_Vbox | src/kernel/qpngio.cpp | C++ | gpl-2.0 | 30,630 |
#!/usr/bin/env python
#Mercurial extension to robustly integrate prompts with other processes
#Copyright (C) 2010-2011 Willem Verstraeten
#
#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.
import urllib2
from mercurial import ui, util
import struct, socket
from mercurial.i18n import _
try:
from mercurial.url import passwordmgr
except:
from mercurial.httprepo import passwordmgr
def sendInt( client, number):
length = struct.pack('>L', number)
client.sendall( length )
def send( client, data ):
if data is None:
sendInt(client, 0)
else:
sendInt(client, len(data))
client.sendall( data )
def receiveIntWithMessage(client, message):
requiredLength = struct.calcsize('>L')
buffer = ''
while len(buffer)<requiredLength:
chunk = client.recv(requiredLength-len(buffer))
if chunk == '':
raise util.Abort( message )
buffer = buffer + chunk
# struct.unpack always returns a tuple, even if that tuple only contains a single
# item. The trailing , is to destructure the tuple into its first element.
intToReturn, = struct.unpack('>L', buffer)
return intToReturn
def receiveInt(client):
return receiveIntWithMessage(client, "could not get information from server")
def receive( client ):
receiveWithMessage(client, "could not get information from server")
def receiveWithMessage( client, message ):
length = receiveIntWithMessage(client, message)
buffer = ''
while len(buffer) < length :
chunk = client.recv(length - len(buffer))
if chunk == '':
raise util.Abort( message)
buffer = buffer+chunk
return buffer
# decorator to cleanly monkey patch methods in mercurial
def monkeypatch_method(cls):
def decorator(func):
setattr(cls, func.__name__, func)
return func
return decorator
def sendchoicestoidea(ui, msg, choices, default):
port = int(ui.config( 'hg4ideaprompt', 'port', None, True))
if not port:
raise util.Abort("No port was specified")
numOfChoices = len(choices)
if not numOfChoices:
return default
client = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
try:
client.connect( ('127.0.0.1', port) )
send( client, msg )
sendInt( client, numOfChoices )
for choice in choices:
send( client, choice )
sendInt( client, default )
answer = receiveInt( client )
if answer == -1:
raise util.Abort("User cancelled")
else:
return answer
except:
raise
# determine which method to monkey patch :
# in Mercurial 1.4 the prompt method was renamed to promptchoice
if getattr(ui.ui, 'promptchoice', None):
@monkeypatch_method(ui.ui)
def promptchoice(self, msg, choices=None, default=0):
return sendchoicestoidea(self, msg, choices, default)
else:
@monkeypatch_method(ui.ui)
def prompt(self, msg, choices=None, default="y"):
resps = [s[s.index('&')+1].lower() for s in choices]
defaultIndex = resps.index( default )
responseIndex = sendchoicestoidea( self, msg, choices, defaultIndex)
return resps[responseIndex]
original_warn = ui.ui.warn
@monkeypatch_method(ui.ui)
def warn(self, *msg):
original_warn(self, *msg)
port = int(self.config( 'hg4ideawarn', 'port', None, True))
if not port:
raise util.Abort("No port was specified")
self.debug( "hg4idea prompt server waiting on port %s" % port )
client = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
self.debug( "connecting ..." )
client.connect( ('127.0.0.1', port) )
self.debug( "connected, sending data ..." )
sendInt( client, len(msg) )
for message in msg:
send( client, message )
def retrieve_pass_from_server(ui, uri,path, proposed_user):
port = int(ui.config('hg4ideapass', 'port', None, True))
if port is None:
raise util.Abort("No port was specified")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ui.debug("connecting ...")
client.connect(('127.0.0.1', port))
ui.debug("connected, sending data ...")
send(client, "getpass")
send(client, uri)
send(client, path)
send(client, proposed_user)
user = receiveWithMessage(client, "http authorization required")
password = receiveWithMessage(client, "http authorization required")
return user, password
original_retrievepass=passwordmgr.find_user_password
@monkeypatch_method(passwordmgr)
def find_user_password(self, realm, authuri):
try:
return original_retrievepass(self, realm, authuri)
except util.Abort:
# In mercurial 1.8 the readauthtoken method was replaced with
# the readauthforuri method, which has different semantics
if getattr(self, 'readauthtoken', None):
def read_hgrc_authtoken(ui, authuri):
return self.readauthtoken(authuri)
else:
def read_hgrc_authtoken(ui, authuri):
# hg 1.8
from mercurial.url import readauthforuri
res = readauthforuri(self.ui, authuri)
if res:
group, auth = res
return auth
else:
return None
user, password = urllib2.HTTPPasswordMgrWithDefaultRealm.find_user_password(self, realm, authuri)
if user is None:
auth = read_hgrc_authtoken(self.ui, authuri)
if auth:
user = auth.get("username")
reduced_uri, path= self.reduce_uri(authuri, False)
retrievedPass = retrieve_pass_from_server(self.ui, reduced_uri, path, user)
if retrievedPass is None:
raise util.Abort(_('http authorization required'))
user, passwd = retrievedPass
self.add_password(realm, authuri, user, passwd)
return retrievedPass | willemv/mercurial_prompthooks | prompthooks.py | Python | gpl-2.0 | 6,665 |
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Core functions used all over the scripts.
* This script is distinct from libraries/common.inc.php because this
* script is called from /test.
*
* @package PhpMyAdmin
*/
use PMA\libraries\Message;
use PMA\libraries\URL;
use PMA\libraries\Sanitize;
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* String handling (security)
*/
require_once 'libraries/string.lib.php';
/**
* checks given $var and returns it if valid, or $default of not valid
* given $var is also checked for type being 'similar' as $default
* or against any other type if $type is provided
*
* <code>
* // $_REQUEST['db'] not set
* echo PMA_ifSetOr($_REQUEST['db'], ''); // ''
* // $_REQUEST['sql_query'] not set
* echo PMA_ifSetOr($_REQUEST['sql_query']); // null
* // $cfg['EnableFoo'] not set
* echo PMA_ifSetOr($cfg['EnableFoo'], false, 'boolean'); // false
* echo PMA_ifSetOr($cfg['EnableFoo']); // null
* // $cfg['EnableFoo'] set to 1
* echo PMA_ifSetOr($cfg['EnableFoo'], false, 'boolean'); // false
* echo PMA_ifSetOr($cfg['EnableFoo'], false, 'similar'); // 1
* echo PMA_ifSetOr($cfg['EnableFoo'], false); // 1
* // $cfg['EnableFoo'] set to true
* echo PMA_ifSetOr($cfg['EnableFoo'], false, 'boolean'); // true
* </code>
*
* @param mixed &$var param to check
* @param mixed $default default value
* @param mixed $type var type or array of values to check against $var
*
* @return mixed $var or $default
*
* @see PMA_isValid()
*/
function PMA_ifSetOr(&$var, $default = null, $type = 'similar')
{
if (! PMA_isValid($var, $type, $default)) {
return $default;
}
return $var;
}
/**
* checks given $var against $type or $compare
*
* $type can be:
* - false : no type checking
* - 'scalar' : whether type of $var is integer, float, string or boolean
* - 'numeric' : whether type of $var is any number representation
* - 'length' : whether type of $var is scalar with a string length > 0
* - 'similar' : whether type of $var is similar to type of $compare
* - 'equal' : whether type of $var is identical to type of $compare
* - 'identical' : whether $var is identical to $compare, not only the type!
* - or any other valid PHP variable type
*
* <code>
* // $_REQUEST['doit'] = true;
* PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // false
* // $_REQUEST['doit'] = 'true';
* PMA_isValid($_REQUEST['doit'], 'identical', 'true'); // true
* </code>
*
* NOTE: call-by-reference is used to not get NOTICE on undefined vars,
* but the var is not altered inside this function, also after checking a var
* this var exists nut is not set, example:
* <code>
* // $var is not set
* isset($var); // false
* functionCallByReference($var); // false
* isset($var); // true
* functionCallByReference($var); // true
* </code>
*
* to avoid this we set this var to null if not isset
*
* @param mixed &$var variable to check
* @param mixed $type var type or array of valid values to check against $var
* @param mixed $compare var to compare with $var
*
* @return boolean whether valid or not
*
* @todo add some more var types like hex, bin, ...?
* @see http://php.net/gettype
*/
function PMA_isValid(&$var, $type = 'length', $compare = null)
{
if (! isset($var)) {
// var is not even set
return false;
}
if ($type === false) {
// no vartype requested
return true;
}
if (is_array($type)) {
return in_array($var, $type);
}
// allow some aliases of var types
$type = strtolower($type);
switch ($type) {
case 'identic' :
$type = 'identical';
break;
case 'len' :
$type = 'length';
break;
case 'bool' :
$type = 'boolean';
break;
case 'float' :
$type = 'double';
break;
case 'int' :
$type = 'integer';
break;
case 'null' :
$type = 'NULL';
break;
}
if ($type === 'identical') {
return $var === $compare;
}
// whether we should check against given $compare
if ($type === 'similar') {
switch (gettype($compare)) {
case 'string':
case 'boolean':
$type = 'scalar';
break;
case 'integer':
case 'double':
$type = 'numeric';
break;
default:
$type = gettype($compare);
}
} elseif ($type === 'equal') {
$type = gettype($compare);
}
// do the check
if ($type === 'length' || $type === 'scalar') {
$is_scalar = is_scalar($var);
if ($is_scalar && $type === 'length') {
return (bool) mb_strlen($var);
}
return $is_scalar;
}
if ($type === 'numeric') {
return is_numeric($var);
}
if (gettype($var) === $type) {
return true;
}
return false;
}
/**
* Removes insecure parts in a path; used before include() or
* require() when a part of the path comes from an insecure source
* like a cookie or form.
*
* @param string $path The path to check
*
* @return string The secured path
*
* @access public
*/
function PMA_securePath($path)
{
// change .. to .
$path = preg_replace('@\.\.*@', '.', $path);
return $path;
} // end function
/**
* displays the given error message on phpMyAdmin error page in foreign language,
* ends script execution and closes session
*
* loads language file if not loaded already
*
* @param string $error_message the error message or named error message
* @param string|array $message_args arguments applied to $error_message
* @param boolean $delete_session whether to delete session cookie
*
* @return void
*/
function PMA_fatalError(
$error_message, $message_args = null, $delete_session = true
) {
/* Use format string if applicable */
if (is_string($message_args)) {
$error_message = sprintf($error_message, $message_args);
} elseif (is_array($message_args)) {
$error_message = vsprintf($error_message, $message_args);
}
if (! empty($GLOBALS['is_ajax_request']) && $GLOBALS['is_ajax_request']) {
$response = PMA\libraries\Response::getInstance();
$response->setRequestStatus(false);
$response->addJSON('message', PMA\libraries\Message::error($error_message));
} else {
$error_message = strtr($error_message, array('<br />' => '[br]'));
// these variables are used in the included file libraries/error.inc.php
//first check if php-mbstring is available
if (function_exists('mb_detect_encoding')) {
//If present use gettext
$error_header = __('Error');
} else {
$error_header = 'Error';
}
$lang = $GLOBALS['lang'];
$dir = $GLOBALS['text_dir'];
// on fatal errors it cannot hurt to always delete the current session
if ($delete_session
&& isset($GLOBALS['session_name'])
&& isset($_COOKIE[$GLOBALS['session_name']])
) {
$GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
}
// Displays the error message
include './libraries/error.inc.php';
}
if (! defined('TESTSUITE')) {
exit;
}
}
/**
* Returns a link to the PHP documentation
*
* @param string $target anchor in documentation
*
* @return string the URL
*
* @access public
*/
function PMA_getPHPDocLink($target)
{
/* List of PHP documentation translations */
$php_doc_languages = array(
'pt_BR', 'zh', 'fr', 'de', 'it', 'ja', 'pl', 'ro', 'ru', 'fa', 'es', 'tr'
);
$lang = 'en';
if (in_array($GLOBALS['lang'], $php_doc_languages)) {
$lang = $GLOBALS['lang'];
}
return PMA_linkURL('http://php.net/manual/' . $lang . '/' . $target);
}
/**
* Warn or fail on missing extension.
*
* @param string $extension Extension name
* @param bool $fatal Whether the error is fatal.
* @param string $extra Extra string to append to message.
*
* @return void
*/
function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
{
/* Gettext does not have to be loaded yet here */
if (function_exists('__')) {
$message = __(
'The %s extension is missing. Please check your PHP configuration.'
);
} else {
$message
= 'The %s extension is missing. Please check your PHP configuration.';
}
$doclink = PMA_getPHPDocLink('book.' . $extension . '.php');
$message = sprintf(
$message,
'[a@' . $doclink . '@Documentation][em]' . $extension . '[/em][/a]'
);
if ($extra != '') {
$message .= ' ' . $extra;
}
if ($fatal) {
PMA_fatalError($message);
return;
}
$GLOBALS['error_handler']->addError(
$message,
E_USER_WARNING,
'',
'',
false
);
}
/**
* returns count of tables in given db
*
* @param string $db database to count tables for
*
* @return integer count of tables in $db
*/
function PMA_getTableCount($db)
{
$tables = $GLOBALS['dbi']->tryQuery(
'SHOW TABLES FROM ' . PMA\libraries\Util::backquote($db) . ';',
null, PMA\libraries\DatabaseInterface::QUERY_STORE
);
if ($tables) {
$num_tables = $GLOBALS['dbi']->numRows($tables);
$GLOBALS['dbi']->freeResult($tables);
} else {
$num_tables = 0;
}
return $num_tables;
}
/**
* Converts numbers like 10M into bytes
* Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
* (renamed with PMA prefix to avoid double definition when embedded
* in Moodle)
*
* @param string|int $size size (Default = 0)
*
* @return integer $size
*/
function PMA_getRealSize($size = 0)
{
if (! $size) {
return 0;
}
$scan = array(
'gb' => 1073741824, //1024 * 1024 * 1024,
'g' => 1073741824, //1024 * 1024 * 1024,
'mb' => 1048576,
'm' => 1048576,
'kb' => 1024,
'k' => 1024,
'b' => 1,
);
foreach ($scan as $unit => $factor) {
$sizeLength = strlen($size);
$unitLength = strlen($unit);
if ($sizeLength > $unitLength
&& strtolower(
substr(
$size,
$sizeLength - $unitLength
)
) == $unit
) {
return substr(
$size,
0,
$sizeLength - $unitLength
) * $factor;
}
}
return $size;
} // end function PMA_getRealSize()
/**
* boolean phpMyAdmin.PMA_checkPageValidity(string &$page, array $whitelist)
*
* checks given $page against given $whitelist and returns true if valid
* it optionally ignores query parameters in $page (script.php?ignored)
*
* @param string &$page page to check
* @param array $whitelist whitelist to check page against
*
* @return boolean whether $page is valid or not (in $whitelist or not)
*/
function PMA_checkPageValidity(&$page, $whitelist)
{
if (! isset($page) || !is_string($page)) {
return false;
}
if (in_array($page, $whitelist)) {
return true;
}
$_page = mb_substr(
$page,
0,
mb_strpos($page . '?', '?')
);
if (in_array($_page, $whitelist)) {
return true;
}
$_page = urldecode($page);
$_page = mb_substr(
$_page,
0,
mb_strpos($_page . '?', '?')
);
if (in_array($_page, $whitelist)) {
return true;
}
return false;
}
/**
* tries to find the value for the given environment variable name
*
* searches in $_SERVER, $_ENV then tries getenv() and apache_getenv()
* in this order
*
* @param string $var_name variable name
*
* @return string value of $var or empty string
*/
function PMA_getenv($var_name)
{
if (isset($_SERVER[$var_name])) {
return $_SERVER[$var_name];
}
if (isset($_ENV[$var_name])) {
return $_ENV[$var_name];
}
if (getenv($var_name)) {
return getenv($var_name);
}
if (function_exists('apache_getenv')
&& apache_getenv($var_name, true)
) {
return apache_getenv($var_name, true);
}
return '';
}
/**
* Send HTTP header, taking IIS limits into account (600 seems ok)
*
* @param string $uri the header to send
* @param bool $use_refresh whether to use Refresh: header when running on IIS
*
* @return void
*/
function PMA_sendHeaderLocation($uri, $use_refresh = false)
{
if ($GLOBALS['PMA_Config']->get('PMA_IS_IIS') && mb_strlen($uri) > 600) {
PMA\libraries\Response::getInstance()->disable();
echo PMA\libraries\Template::get('header_location')
->render(array('uri' => $uri));
return;
}
$response = PMA\libraries\Response::getInstance();
if (SID) {
if (mb_strpos($uri, '?') === false) {
$response->header('Location: ' . $uri . '?' . SID);
} else {
$separator = URL::getArgSeparator();
$response->header('Location: ' . $uri . $separator . SID);
}
return;
}
session_write_close();
if ($response->headersSent()) {
if (function_exists('debug_print_backtrace')) {
echo '<pre>';
debug_print_backtrace();
echo '</pre>';
}
trigger_error(
'PMA_sendHeaderLocation called when headers are already sent!',
E_USER_ERROR
);
}
// bug #1523784: IE6 does not like 'Refresh: 0', it
// results in a blank page
// but we need it when coming from the cookie login panel)
if ($GLOBALS['PMA_Config']->get('PMA_IS_IIS') && $use_refresh) {
$response->header('Refresh: 0; ' . $uri);
} else {
$response->header('Location: ' . $uri);
}
}
/**
* Outputs application/json headers. This includes no caching.
*
* @return void
*/
function PMA_headerJSON()
{
if (defined('TESTSUITE') && ! defined('PMA_TEST_HEADERS')) {
return;
}
// No caching
PMA_noCacheHeader();
// MIME type
header('Content-Type: application/json; charset=UTF-8');
// Disable content sniffing in browser
// This is needed in case we include HTML in JSON, browser might assume it's
// html to display
header('X-Content-Type-Options: nosniff');
}
/**
* Outputs headers to prevent caching in browser (and on the way).
*
* @return void
*/
function PMA_noCacheHeader()
{
if (defined('TESTSUITE') && ! defined('PMA_TEST_HEADERS')) {
return;
}
// rfc2616 - Section 14.21
header('Expires: ' . date(DATE_RFC1123));
// HTTP/1.1
header(
'Cache-Control: no-store, no-cache, must-revalidate,'
. ' pre-check=0, post-check=0, max-age=0'
);
header('Pragma: no-cache'); // HTTP/1.0
// test case: exporting a database into a .gz file with Safari
// would produce files not having the current time
// (added this header for Safari but should not harm other browsers)
header('Last-Modified: ' . date(DATE_RFC1123));
}
/**
* Sends header indicating file download.
*
* @param string $filename Filename to include in headers if empty,
* none Content-Disposition header will be sent.
* @param string $mimetype MIME type to include in headers.
* @param int $length Length of content (optional)
* @param bool $no_cache Whether to include no-caching headers.
*
* @return void
*/
function PMA_downloadHeader($filename, $mimetype, $length = 0, $no_cache = true)
{
if ($no_cache) {
PMA_noCacheHeader();
}
/* Replace all possibly dangerous chars in filename */
$filename = str_replace(array(';', '"', "\n", "\r"), '-', $filename);
if (!empty($filename)) {
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename="' . $filename . '"');
}
header('Content-Type: ' . $mimetype);
// inform the server that compression has been done,
// to avoid a double compression (for example with Apache + mod_deflate)
$notChromeOrLessThan43 = PMA_USR_BROWSER_AGENT != 'CHROME' // see bug #4942
|| (PMA_USR_BROWSER_AGENT == 'CHROME' && PMA_USR_BROWSER_VER < 43);
if (strpos($mimetype, 'gzip') !== false && $notChromeOrLessThan43) {
header('Content-Encoding: gzip');
}
header('Content-Transfer-Encoding: binary');
if ($length > 0) {
header('Content-Length: ' . $length);
}
}
/**
* Returns value of an element in $array given by $path.
* $path is a string describing position of an element in an associative array,
* eg. Servers/1/host refers to $array[Servers][1][host]
*
* @param string $path path in the array
* @param array $array the array
* @param mixed $default default value
*
* @return mixed array element or $default
*/
function PMA_arrayRead($path, $array, $default = null)
{
$keys = explode('/', $path);
$value =& $array;
foreach ($keys as $key) {
if (! isset($value[$key])) {
return $default;
}
$value =& $value[$key];
}
return $value;
}
/**
* Stores value in an array
*
* @param string $path path in the array
* @param array &$array the array
* @param mixed $value value to store
*
* @return void
*/
function PMA_arrayWrite($path, &$array, $value)
{
$keys = explode('/', $path);
$last_key = array_pop($keys);
$a =& $array;
foreach ($keys as $key) {
if (! isset($a[$key])) {
$a[$key] = array();
}
$a =& $a[$key];
}
$a[$last_key] = $value;
}
/**
* Removes value from an array
*
* @param string $path path in the array
* @param array &$array the array
*
* @return void
*/
function PMA_arrayRemove($path, &$array)
{
$keys = explode('/', $path);
$keys_last = array_pop($keys);
$path = array();
$depth = 0;
$path[0] =& $array;
$found = true;
// go as deep as required or possible
foreach ($keys as $key) {
if (! isset($path[$depth][$key])) {
$found = false;
break;
}
$depth++;
$path[$depth] =& $path[$depth - 1][$key];
}
// if element found, remove it
if ($found) {
unset($path[$depth][$keys_last]);
$depth--;
}
// remove empty nested arrays
for (; $depth >= 0; $depth--) {
if (! isset($path[$depth+1]) || count($path[$depth+1]) == 0) {
unset($path[$depth][$keys[$depth]]);
} else {
break;
}
}
}
/**
* Returns link to (possibly) external site using defined redirector.
*
* @param string $url URL where to go.
*
* @return string URL for a link.
*/
function PMA_linkURL($url)
{
if (!preg_match('#^https?://#', $url) || defined('PMA_SETUP')) {
return $url;
}
$params = array();
$params['url'] = $url;
$url = URL::getCommon($params);
//strip off token and such sensitive information. Just keep url.
$arr = parse_url($url);
parse_str($arr["query"], $vars);
$query = http_build_query(array("url" => $vars["url"]));
$url = './url.php?' . $query;
return $url;
}
/**
* Checks whether domain of URL is whitelisted domain or not.
* Use only for URLs of external sites.
*
* @param string $url URL of external site.
*
* @return boolean True: if domain of $url is allowed domain,
* False: otherwise.
*/
function PMA_isAllowedDomain($url)
{
$arr = parse_url($url);
$domain = $arr["host"];
$domainWhiteList = array(
/* Include current domain */
$_SERVER['SERVER_NAME'],
/* phpMyAdmin domains */
'wiki.phpmyadmin.net', 'www.phpmyadmin.net', 'phpmyadmin.net',
'docs.phpmyadmin.net',
/* mysql.com domains */
'dev.mysql.com','bugs.mysql.com',
/* mariadb domains */
'mariadb.org',
/* php.net domains */
'php.net',
/* Github domains*/
'github.com','www.github.com',
/* Following are doubtful ones. */
'www.primebase.com',
'pbxt.blogspot.com',
'www.percona.com',
'mysqldatabaseadministration.blogspot.com',
'ronaldbradford.com',
'xaprb.com',
);
if (in_array(mb_strtolower($domain), $domainWhiteList)) {
return true;
}
return false;
}
/**
* Adds JS code snippets to be displayed by the PMA\libraries\Response class.
* Adds a newline to each snippet.
*
* @param string $str Js code to be added (e.g. "token=1234;")
*
* @return void
*/
function PMA_addJSCode($str)
{
$response = PMA\libraries\Response::getInstance();
$header = $response->getHeader();
$scripts = $header->getScripts();
$scripts->addCode($str);
}
/**
* Adds JS code snippet for variable assignment
* to be displayed by the PMA\libraries\Response class.
*
* @param string $key Name of value to set
* @param mixed $value Value to set, can be either string or array of strings
* @param bool $escape Whether to escape value or keep it as it is
* (for inclusion of js code)
*
* @return void
*/
function PMA_addJSVar($key, $value, $escape = true)
{
PMA_addJSCode(Sanitize::getJsValue($key, $value, $escape));
}
/**
* Replace some html-unfriendly stuff
*
* @param string $buffer String to process
*
* @return string Escaped and cleaned up text suitable for html
*/
function PMA_mimeDefaultFunction($buffer)
{
$buffer = htmlspecialchars($buffer);
$buffer = str_replace(' ', ' ', $buffer);
$buffer = preg_replace("@((\015\012)|(\015)|(\012))@", '<br />' . "\n", $buffer);
return $buffer;
}
/**
* Displays SQL query before executing.
*
* @param array|string $query_data Array containing queries or query itself
*
* @return void
*/
function PMA_previewSQL($query_data)
{
$retval = '<div class="preview_sql">';
if (empty($query_data)) {
$retval .= __('No change');
} elseif (is_array($query_data)) {
foreach ($query_data as $query) {
$retval .= PMA\libraries\Util::formatSql($query);
}
} else {
$retval .= PMA\libraries\Util::formatSql($query_data);
}
$retval .= '</div>';
$response = PMA\libraries\Response::getInstance();
$response->addJSON('sql_data', $retval);
exit;
}
/**
* recursively check if variable is empty
*
* @param mixed $value the variable
*
* @return bool true if empty
*/
function PMA_emptyRecursive($value)
{
$empty = true;
if (is_array($value)) {
array_walk_recursive(
$value,
function ($item) use (&$empty) {
$empty = $empty && empty($item);
}
);
} else {
$empty = empty($value);
}
return $empty;
}
/**
* Creates some globals from $_POST variables matching a pattern
*
* @param array $post_patterns The patterns to search for
*
* @return void
*/
function PMA_setPostAsGlobal($post_patterns)
{
foreach (array_keys($_POST) as $post_key) {
foreach ($post_patterns as $one_post_pattern) {
if (preg_match($one_post_pattern, $post_key)) {
$GLOBALS[$post_key] = $_POST[$post_key];
}
}
}
}
/**
* Creates some globals from $_REQUEST
*
* @param string $param db|table
*
* @return void
*/
function PMA_setGlobalDbOrTable($param)
{
$GLOBALS[$param] = '';
if (PMA_isValid($_REQUEST[$param])) {
// can we strip tags from this?
// only \ and / is not allowed in db names for MySQL
$GLOBALS[$param] = $_REQUEST[$param];
$GLOBALS['url_params'][$param] = $GLOBALS[$param];
}
}
/**
* PATH_INFO could be compromised if set, so remove it from PHP_SELF
* and provide a clean PHP_SELF here
*
* @return void
*/
function PMA_cleanupPathInfo()
{
global $PMA_PHP_SELF, $_PATH_INFO;
$PMA_PHP_SELF = PMA_getenv('PHP_SELF');
$_PATH_INFO = PMA_getenv('PATH_INFO');
if (! empty($_PATH_INFO) && ! empty($PMA_PHP_SELF)) {
$path_info_pos = mb_strrpos($PMA_PHP_SELF, $_PATH_INFO);
$pathLength = $path_info_pos + mb_strlen($_PATH_INFO);
if ($pathLength === mb_strlen($PMA_PHP_SELF)) {
$PMA_PHP_SELF = mb_substr($PMA_PHP_SELF, 0, $path_info_pos);
}
}
$PMA_PHP_SELF = htmlspecialchars($PMA_PHP_SELF);
}
/**
* Checks that required PHP extensions are there.
* @return void
*/
function PMA_checkExtensions()
{
/**
* Warning about mbstring.
*/
if (! function_exists('mb_detect_encoding')) {
PMA_warnMissingExtension('mbstring', true);
}
/**
* We really need this one!
*/
if (! function_exists('preg_replace')) {
PMA_warnMissingExtension('pcre', true);
}
/**
* JSON is required in several places.
*/
if (! function_exists('json_encode')) {
PMA_warnMissingExtension('json', true);
}
}
/* Compatibility with PHP < 5.6 */
if(! function_exists('hash_equals')) {
/**
* Timing attack safe string comparison
*
* @param string $a first string
* @param string $b second string
*
* @return boolean whether they are equal
*/
function hash_equals($a, $b) {
$ret = strlen($a) ^ strlen($b);
$ret |= array_sum(unpack("C*", $a ^ $b));
return ! $ret;
}
}
| zixtor/phpmyadmin | libraries/core.lib.php | PHP | gpl-2.0 | 25,508 |
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using Meta.Net.Objects;
namespace Meta.Net.Metadata.Factories
{
internal class CheckConstraintFactory
{
private int SchemaNameOrdinal { get; set; }
private int TableNameOrdinal { get; set; }
private int ColumnNameOrdinal { get; set; }
private int ObjectNameOrdinal { get; set; }
private int DefinitionOrdinal { get; set; }
private int IsTableConstraintOrdinal { get; set; }
private int IsDisabledOrdinal { get; set; }
private int IsNotForReplicationOrdinal { get; set; }
private int IsNotTrustedOrdinal { get; set; }
private int IsSystemNamedOrdinal { get; set; }
public CheckConstraintFactory(IDataRecord reader)
{
SchemaNameOrdinal = reader.GetOrdinal("SchemaName");
TableNameOrdinal = reader.GetOrdinal("TableName");
ColumnNameOrdinal = reader.GetOrdinal("ColumnName");
ObjectNameOrdinal = reader.GetOrdinal("ObjectName");
DefinitionOrdinal = reader.GetOrdinal("Definition");
IsTableConstraintOrdinal = reader.GetOrdinal("IsTableConstraint");
IsDisabledOrdinal = reader.GetOrdinal("IsDisabled");
IsNotForReplicationOrdinal = reader.GetOrdinal("IsNotForReplication");
IsNotTrustedOrdinal = reader.GetOrdinal("IsNotTrusted");
IsSystemNamedOrdinal = reader.GetOrdinal("IsSystemNamed");
}
public void CreateCheckConstraint(
Dictionary<string, UserTable> userTables,
IDataReader reader)
{
var schemaName = Convert.ToString(reader[SchemaNameOrdinal]);
var tableName = Convert.ToString(reader[TableNameOrdinal]);
var userTableNamespaceBuilder = new StringBuilder(schemaName.Length + tableName.Length + 1);
userTableNamespaceBuilder.Append(schemaName).
Append(Constants.Dot).
Append(tableName);
var userTableNamespace = userTableNamespaceBuilder.ToString();
if (!userTables.ContainsKey(userTableNamespace))
return;
var userTable = userTables[userTableNamespace];
if (userTable == null)
return;
var checkConstraint = new CheckConstraint
{
UserTable = userTable,
ColumnName = Convert.ToString(reader[ColumnNameOrdinal]),
ObjectName = Convert.ToString(reader[ObjectNameOrdinal]),
Definition = Convert.ToString(reader[DefinitionOrdinal]),
IsTableConstraint = Convert.ToBoolean(reader[IsTableConstraintOrdinal]),
IsDisabled = Convert.ToBoolean(reader[IsDisabledOrdinal]),
IsNotForReplication = Convert.ToBoolean(reader[IsNotForReplicationOrdinal]),
IsNotTrusted = Convert.ToBoolean(reader[IsNotTrustedOrdinal]),
IsSystemNamed = Convert.ToBoolean(reader[IsSystemNamedOrdinal])
};
userTable.CheckConstraints.Add(checkConstraint);
}
}
}
| OhRyanOh/Meta.Net | Meta.Net/Metadata/Factories/CheckConstraintFactory.cs | C# | gpl-2.0 | 3,157 |
// ---------------------------------------------------------------------- //
// //
// Copyright (c) 2007-2014 //
// Digital Beacon, LLC //
// //
// ---------------------------------------------------------------------- //
using System;
using System.Collections;
namespace DigitalBeacon.Model
{
/// This is the interface for all business objects that have a code property
/// </summary>
public interface ICodedEntity : IBaseEntity
{
/// <summary>
/// The code property
/// </summary>
string Code { get; set; }
}
}
| digitalbeacon/sitebase | Model/ICodedEntity.cs | C# | gpl-2.0 | 790 |
var FabrikModalRepeat = new Class({
initialize: function (el, names, field) {
this.names = names;
this.field = field;
this.content = false;
this.setup = false;
this.elid = el;
this.win = {};
this.el = {};
this.field = {};
// If the parent field is inserted via js then we delay the loading untill the html is present
if (!this.ready()) {
this.timer = this.testReady.periodical(500, this);
} else {
this.setUp();
}
},
ready: function () {
return typeOf(document.id(this.elid)) === 'null' ? false : true;
},
testReady: function () {
if (!this.ready()) {
return;
}
if (this.timer) {
clearInterval(this.timer);
}
this.setUp();
},
setUp: function () {
this.button = document.id(this.elid + '_button');
if (this.mask) {
this.mask.destroy();
}
this.mask = new Mask(document.body, {style: {'background-color': '#000', 'opacity': 0.4, 'z-index': 9998}});
document.addEvent('click:relay(*[data-modal=' + this.elid + '])', function (e, target) {
var tbl;
// Correct when in repeating group
var id = target.getNext('input').id;
this.field[id] = target.getNext('input');
var c = target.getParent('li');
this.origContainer = c;
tbl = c.getElement('table');
if (typeOf(tbl) !== 'null') {
this.el[id] = tbl;
}
this.openWindow(id);
}.bind(this));
},
openWindow: function (target) {
var makeWin = false;
if (!this.win[target]) {
makeWin = true;
this.makeTarget(target);
}
this.el[target].inject(this.win[target], 'top');
this.el[target].show();
if (!this.win[target] || makeWin) {
this.makeWin(target);
}
// Testing moviing out of makeWin
//this.build(target);
this.win[target].show();
this.win[target].position();
this.resizeWin(true, target);
this.win[target].position();
this.mask.show();
},
makeTarget: function (target) {
this.win[target] = new Element('div', {'data-modal-content': target, 'styles': {'padding': '5px', 'background-color': '#fff', 'display': 'none', 'z-index': 9999}}).inject(document.body);
},
makeWin: function (target) {
// Testing adopting in.out on show/hide
//this.win[target].adopt(this.el[target]);
var close = new Element('button.btn.button').set('text', 'close');
close.addEvent('click', function (e) {
e.stop();
this.store(target);
this.el[target].hide();
this.el[target].inject(this.origContainer);
this.close();
}.bind(this));
var controls = new Element('div.controls', {'styles': {'text-align': 'right'}}).adopt(close);
this.win[target].adopt(controls);
this.win[target].position();
this.content = this.el[target];
this.build(target);
this.watchButtons(this.win[target], target);
},
resizeWin: function (setup, target) {
console.log(target);
Object.each(this.win, function (win, key) {
var size = this.el[key].getDimensions(true);
var wsize = win.getDimensions(true);
var y = setup ? wsize.y : size.y + 30;
win.setStyles({'width': size.x + 'px', 'height': (y) + 'px'});
}.bind(this));
},
close: function () {
Object.each(this.win, function (win, key) {
win.hide();
});
this.mask.hide();
},
_getRadioValues: function (target) {
var radiovals = [];
this.getTrs(target).each(function (tr) {
var v = (sel = tr.getElement('input[type=radio]:checked')) ? sel.get('value') : v = '';
radiovals.push(v);
});
return radiovals;
},
_setRadioValues: function (radiovals, target) {
// Reapply radio button selections
this.getTrs(target).each(function (tr, i) {
if (r = tr.getElement('input[type=radio][value=' + radiovals[i] + ']')) {
r.checked = 'checked';
}
});
},
watchButtons: function (win, target) {
win.addEvent('click:relay(a.add)', function (e) {
if (tr = this.findTr(e)) {
// Store radio button selections
var radiovals = this._getRadioValues(target);
var body = tr.getParent('table').getElement('tbody');
this.tmpl.clone(true, true).inject(body);
/*if (tr.getChildren('th').length !== 0) {
var body = tr.getParent('table').getElement('tbody');
this.tmpl.clone(true, true).inject(body);
} else {
tr.clone(true, true).inject(tr, 'after');
}*/
this.stripe(target);
// Reapply values as renaming radio buttons
this._setRadioValues(radiovals, target);
this.resizeWin(false, target);
}
win.position();
e.stop();
}.bind(this));
win.addEvent('click:relay(a.remove)', function (e) {
// If only one row -don't remove
var rows = this.content.getElements('tbody tr');
if (rows.length <= 1) {
// return;
}
if (tr = this.findTr(e)) {
tr.dispose();
}
this.resizeWin(false, target);
win.position();
e.stop();
}.bind(this));
},
getTrs: function (target) {
return this.win[target].getElement('tbody').getElements('tr');
},
stripe: function (target) {
trs = this.getTrs(target);
for (var i = 0; i < trs.length; i ++) {
trs[i].removeClass('row1').removeClass('row0');
trs[i].addClass('row' + i % 2);
var chx = trs[i].getElements('input[type=radio]');
chx.each(function (r) {
r.name = r.name.replace(/\[([0-9])\]/, '[' + i + ']');
});
}
},
build: function (target) {
if (!this.win[target]) {
this.makeWin(target);
}
var a = JSON.decode(this.field[target].get('value'));
if (typeOf(a) === 'null') {
a = {};
}
var tr = this.win[target].getElement('tbody').getElement('tr');
var keys = Object.keys(a);
var newrow = keys.length === 0 || a[keys[0]].length === 0 ? true : false;
var rowcount = newrow ? 1 : a[keys[0]].length;
// Build the rows from the json object
for (var i = 1; i < rowcount; i ++) {
tr.clone().inject(tr, 'after');
}
this.stripe(target);
var trs = this.getTrs(target);
// Populate the cloned fields with the json values
for (i = 0; i < rowcount; i++) {
keys.each(function (k) {
trs[i].getElements('*[name*=' + k + ']').each(function (f) {
if (f.get('type') === 'radio') {
if (f.value === a[k][i]) {
f.checked = true;
}
} else {
// Works for input,select and textareas
f.value = a[k][i];
}
});
});
}
this.tmpl = tr;
if (newrow) {
tr.dispose();
}
},
findTr: function (e) {
var tr = e.target.getParents().filter(function (p) {
return p.get('tag') === 'tr';
});
return (tr.length === 0) ? false : tr[0];
},
store: function (target) {
var c = this.content;
c = this.el[target];
// Get the current values
var json = {};
for (var i = 0; i < this.names.length; i++) {
var n = this.names[i];
var fields = c.getElements('*[name*=' + n + ']');
json[n] = [];
fields.each(function (field) {
if (field.get('type') === 'radio') {
if (field.get('checked') === true) {
json[n].push(field.get('value'));
}
} else {
json[n].push(field.get('value'));
}
}.bind(this));
}
// Store them in the parent field.
this.field[target].value = JSON.encode(json);
return true;
}
}); | emundus/v5 | administrator/components/com_fabrik/models/fields/fabrikmodalrepeat.js | JavaScript | gpl-2.0 | 7,061 |
<?php
function _appthemes_localize_scripts() {
// jQuery Validate
wp_register_script( 'validate-lang', APP_FRAMEWORK_URI . '/js/validate/jquery.validate-lang.js', array( 'validate' ) );
wp_localize_script( 'validate-lang', 'validateL10n', array(
'required' => __( 'This field is required.', APP_TD ),
'remote' => __( 'Please fix this field.', APP_TD ),
'email' => __( 'Please enter a valid email address.', APP_TD ),
'url' => __( 'Please enter a valid URL.', APP_TD ),
'date' => __( 'Please enter a valid date.', APP_TD ),
'dateISO' => __( 'Please enter a valid date (ISO).', APP_TD ),
'number' => __( 'Please enter a valid number.', APP_TD ),
'digits' => __( 'Please enter only digits.', APP_TD ),
'creditcard' => __( 'Please enter a valid credit card number.', APP_TD ),
'equalTo' => __( 'Please enter the same value again.', APP_TD ),
'maxlength' => __( 'Please enter no more than {0} characters.', APP_TD ),
'minlength' => __( 'Please enter at least {0} characters.', APP_TD ),
'rangelength' => __( 'Please enter a value between {0} and {1} characters long.', APP_TD ),
'range' => __( 'Please enter a value between {0} and {1}.', APP_TD ),
'max' => __( 'Please enter a value less than or equal to {0}.', APP_TD ),
'min' => __( 'Please enter a value greater than or equal to {0}.', APP_TD ),
) );
// jQuery Colorbox
wp_register_script( 'colorbox-lang', APP_FRAMEWORK_URI . '/js/colorbox/jquery.colorbox-lang.js', array( 'colorbox' ) );
wp_localize_script( 'colorbox-lang', 'colorboxL10n', array(
'current' => __( 'image {current} of {total}', APP_TD ),
'previous' => __( 'previous', APP_TD ),
'next' => __( 'next', APP_TD ),
'close' => __( 'close', APP_TD ),
'xhrError' => __( 'This content failed to load.', APP_TD ),
'imgError' => __( 'This image failed to load.', APP_TD ),
'slideshowStart' => __( 'start slideshow', APP_TD ),
'slideshowStop' => __( 'stop slideshow', APP_TD ),
) );
}
| dakshatechnologies/renovize | wp-content/themes/renovizenew/framework/js/localization.php | PHP | gpl-2.0 | 2,069 |
/*
* Copyright (c) 2007 Henrique Pinto <henrique.pinto@kdemail.net>
* Copyright (c) 2008-2009 Harald Hvaal <haraldhv@stud.ntnu.no>
* Copyright (c) 2010 Raphael Kubo da Costa <rakuco@FreeBSD.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ( INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "readonlylibarchiveplugin.h"
#include "ark_debug.h"
#include <KPluginFactory>
K_PLUGIN_FACTORY_WITH_JSON(ReadOnlyLibarchivePluginFactory, "kerfuffle_libarchive_readonly.json", registerPlugin<ReadOnlyLibarchivePlugin>();)
ReadOnlyLibarchivePlugin::ReadOnlyLibarchivePlugin(QObject *parent, const QVariantList & args)
: LibarchivePlugin(parent, args)
{
qCDebug(ARK) << "Loaded libarchive read-only plugin";
}
ReadOnlyLibarchivePlugin::~ReadOnlyLibarchivePlugin()
{
}
#include "readonlylibarchiveplugin.moc"
| mvlabat/ark | plugins/libarchive/readonlylibarchiveplugin.cpp | C++ | gpl-2.0 | 1,989 |
<?php $atts = array_map('contact_do_shortcode', (array) $atts);
extract(shortcode_atts(array('filter' => ''), $atts));
$form_id = $GLOBALS['contact_form_id'];
$prefix = $GLOBALS['contact_form_prefix'];
$content = explode('[other]', do_shortcode($content));
if (!isset($_POST[$prefix.'submit'])) { $n = 2; }
elseif ((isset($GLOBALS['form_error'])) && ($GLOBALS['form_error'] == 'yes')) { $n = 1; }
else { $n = 0; }
if (!isset($content[$n])) { $content[$n] = ''; }
$content = contact_filter_data($filter, $content[$n]); | patricerandria/ccmgr-wp | ccmgr/wp-content/plugins/contact-manager/includes/forms/validation-content.php | PHP | gpl-2.0 | 526 |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddShortnameProjects extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('projects', function(Blueprint $table)
{
//
$table->string('shortname');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('projects', function(Blueprint $table)
{
//
$table->dropColumn('shortname');
});
}
} | elconejito/Graphics-Library | app/database/migrations/2014_03_17_173453_add_shortname_projects.php | PHP | gpl-2.0 | 547 |
<?php //$Id$
/**
* CLAROLINE
* @version 1.9 $Revision$
*
* @copyright (c) 2001-2007 Universite catholique de Louvain (UCL)
*
* @license http://www.gnu.org/copyleft/gpl.html (GPL) GENERAL PUBLIC LICENSE
*
* @package ADMIN
*
* @author Guillaume Lederer <lederer@claroline.net>
*/
$cidReset = TRUE; $gidReset = TRUE; $tidReset = TRUE;
require '../inc/claro_init_global.inc.php';
$userPerPage = get_conf('userPerPage',20); // numbers of user to display on the same page
// Security check
if ( ! claro_is_user_authenticated() ) claro_disp_auth_form();
if ( ! claro_is_platform_admin() ) claro_die(get_lang('Not allowed'));
require_once get_path('incRepositorySys') . '/lib/pager.lib.php';
require_once get_path('incRepositorySys') . '/lib/admin.lib.inc.php';
require_once get_path('incRepositorySys') . '/lib/user.lib.php';
// CHECK INCOMING DATAS
if ((isset($_REQUEST['cidToEdit'])) && ($_REQUEST['cidToEdit']=='')) {unset($_REQUEST['cidToEdit']);}
$validCmdList = array('delete');
$cmd = (isset($_REQUEST['cmd']) && in_array($_REQUEST['cmd'],$validCmdList)? $_REQUEST['cmd'] : null);
$userIdReq = (int) (isset($_REQUEST['user_id']) ? $_REQUEST['user_id']: null);
// USED SESSION VARIABLES
// clean session if needed
if (isset($_REQUEST['newsearch']) && $_REQUEST['newsearch'] == 'yes')
{
unset($_SESSION['admin_user_search' ]);
unset($_SESSION['admin_user_firstName']);
unset($_SESSION['admin_user_lastName' ]);
unset($_SESSION['admin_user_userName' ]);
unset($_SESSION['admin_user_officialCode' ]);
unset($_SESSION['admin_user_mail' ]);
unset($_SESSION['admin_user_action' ]);
unset($_SESSION['admin_order_crit' ]);
}
// deal with session variables for search criteria, it depends where we come from :
// 1 ) we must be able to get back to the list that concerned the criteria we previously used (with out re entering them)
// 2 ) we must be able to arrive with new critera for a new search.
if (isset($_REQUEST['search' ])) $_SESSION['admin_user_search' ] = trim($_REQUEST['search' ]);
if (isset($_REQUEST['firstName' ])) $_SESSION['admin_user_firstName' ] = trim($_REQUEST['firstName' ]);
if (isset($_REQUEST['lastName' ])) $_SESSION['admin_user_lastName' ] = trim($_REQUEST['lastName' ]);
if (isset($_REQUEST['userName' ])) $_SESSION['admin_user_userName' ] = trim($_REQUEST['userName' ]);
if (isset($_REQUEST['officialCode' ])) $_SESSION['admin_user_officialCode' ] = trim($_REQUEST['officialCode' ]);
if (isset($_REQUEST['mail' ])) $_SESSION['admin_user_mail' ] = trim($_REQUEST['mail' ]);
if (isset($_REQUEST['action' ])) $_SESSION['admin_user_action' ] = trim($_REQUEST['action' ]);
if (isset($_REQUEST['order_crit'])) $_SESSION['admin_user_order_crit'] = trim($_REQUEST['order_crit']);
if (isset($_REQUEST['dir' ])) $_SESSION['admin_user_dir' ] = ($_REQUEST['dir'] == 'DESC' ? 'DESC' : 'ASC' );
$addToURL = ( isset($_REQUEST['addToURL']) ? $_REQUEST['addToURL'] : '');
//TABLES
//declare needed tables
// Deal with interbredcrumps
ClaroBreadCrumbs::getInstance()->prepend( get_lang('Administration'), get_path('rootAdminWeb') );
$nameTools = get_lang('User list');
//TABLES
//------------------------------------
// Execute COMMAND section
//------------------------------------
switch ( $cmd )
{
case 'delete' :
{
$dialogBox = ( user_delete($userIdReq) ? get_lang('Deletion of the user was done sucessfully') : get_lang('You can not change your own settings!'));
} break;
}
$searchInfo = prepare_search();
$isSearched = $searchInfo['isSearched'];
$addtoAdvanced = $searchInfo['addtoAdvanced'];
if(count($searchInfo['isSearched']) )
{
$isSearched = array_map( 'strip_tags', $isSearched );
$isSearchedHTML = implode('<br />', $isSearched);
}
else
{
$isSearchedHTML = '';
}
//get the search keyword, if any
$search = (isset($_REQUEST['search']) ? $_REQUEST['search'] : '');
$sql = get_sql_filtered_user_list();
$offset = isset($_REQUEST['offset']) ? $_REQUEST['offset'] : 0 ;
$myPager = new claro_sql_pager($sql, $offset, $userPerPage);
if ( array_key_exists( 'sort', $_GET ) )
{
$dir = array_key_exists( 'dir', $_GET ) && $_GET['dir'] == SORT_DESC
? SORT_DESC
: SORT_ASC
;
$sortKey = strip_tags( $_GET['sort'] );
$myPager->add_sort_key( $sortKey, $dir );
}
$defaultSortKeyList = array ('isPlatformAdmin' => SORT_DESC,
'name' => SORT_ASC,
'firstName' => SORT_ASC);
foreach($defaultSortKeyList as $thisSortKey => $thisSortDir)
{
$myPager->add_sort_key( $thisSortKey, $thisSortDir);
}
$userList = $myPager->get_result_list();
if (is_array($userList))
{
$tbl_mdb_names = claro_sql_get_main_tbl();
foreach ($userList as $userKey => $user)
{
$sql ="SELECT count(DISTINCT code_cours) AS qty_course
FROM `" . $tbl_mdb_names['rel_course_user'] . "`
WHERE user_id = '". (int) $user['user_id'] ."'
GROUP BY user_id";
$userList[$userKey]['qty_course'] = (int) claro_sql_query_get_single_value($sql);
}
}
$userGrid = array();
if (is_array($userList))
foreach ($userList as $userKey => $user)
{
$userGrid[$userKey]['user_id'] = $user['user_id'];
$userGrid[$userKey]['name'] = $user['name'];
$userGrid[$userKey]['firstname'] = $user['firstname'];
$userEmailLabel=null;
if ( !empty($_SESSION['admin_user_search']) )
{
$bold_search = str_replace('*','.*',$_SESSION['admin_user_search']);
$userGrid[$userKey]['name'] = eregi_replace('(' . $bold_search . ')' , '<b>\\1</b>', $user['name']);
$userGrid[$userKey]['firstname'] = eregi_replace('(' . $bold_search . ')' , '<b>\\1</b>', $user['firstname']);
$userEmailLabel = eregi_replace('(' . $bold_search . ')', '<b>\\1</b>' , $user['email']);
}
$userGrid[$userKey]['officialCode'] = empty($user['officialCode']) ? ' - ' : $user['officialCode'];
$userGrid[$userKey]['email'] = claro_html_mailTo($user['email'], $userEmailLabel);
$userGrid[$userKey]['isCourseCreator'] = ( $user['isCourseCreator']?get_lang('Course creator'):get_lang('User'));
if ( $user['isPlatformAdmin'] )
{
$userGrid[$userKey]['isCourseCreator'] .= '<br /><span class="highlight">' . get_lang('Administrator').'</span>';
}
$userGrid[$userKey]['settings'] = '<a href="adminprofile.php'
. '?uidToEdit=' . $user['user_id']
. '&cfrom=ulist' . $addToURL . '">'
. '<img src="' . get_icon_url('usersetting') . '" alt="' . get_lang('User settings') . '" />'
. '</a>';
$userGrid[$userKey]['qty_course'] = '<a href="adminusercourses.php?uidToEdit=' . $user['user_id']
. '&cfrom=ulist' . $addToURL . '">' . "\n"
. get_lang('%nb course(s)', array('%nb' => $user['qty_course'])) . "\n"
. '</a>' . "\n"
;
$userGrid[$userKey]['delete'] = '<a href="' . $_SERVER['PHP_SELF']
. '?cmd=delete&user_id=' . $user['user_id']
. '&offset=' . $offset . $addToURL . '" '
. ' onclick="return confirmation(\'' . clean_str_for_javascript(' ' . $user['firstname'] . ' ' . $user['name']).'\');">' . "\n"
. '<img src="' . get_icon_url('deluser') . '" alt="' . get_lang('Delete') . '" />' . "\n"
. '</a> '."\n"
;
}
$sortUrlList = $myPager->get_sort_url_list($_SERVER['PHP_SELF']);
$userDataGrid = new claro_datagrid();
$userDataGrid->set_grid($userGrid);
$userDataGrid->set_colHead('name') ;
$userDataGrid->set_colTitleList(array (
'user_id'=>'<a href="' . $sortUrlList['user_id'] . '">' . get_lang('Numero') . '</a>'
,'name'=>'<a href="' . $sortUrlList['name'] . '">' . get_lang('Last name') . '</a>'
,'firstname'=>'<a href="' . $sortUrlList['firstname'] . '">' . get_lang('First name') . '</a>'
,'officialCode'=>'<a href="' . $sortUrlList['officialCode'] . '">' . get_lang('Administrative code') . '</a>'
,'email'=>'<a href="' . $sortUrlList['email'] . '">' . get_lang('Email') . '</a>'
,'isCourseCreator'=>'<a href="' . $sortUrlList['isCourseCreator'] . '">' . get_lang('Status') . '</a>'
,'settings'=> get_lang('User settings')
,'qty_course' => get_lang('Courses')
,'delete'=>get_lang('Delete') ));
if ( count($userGrid)==0 )
{
$userDataGrid->set_noRowMessage( '<center>'.get_lang('No user to display') . "\n"
. '<br />' . "\n"
. '<a href="advancedUserSearch.php' . $addtoAdvanced . '">' . get_lang('Search again (advanced)') . '</a></center>' . "\n"
);
}
else
{
$userDataGrid->set_colAttributeList(array ( 'user_id' => array ('align' => 'center')
, 'officialCode' => array ('align' => 'center')
, 'settings' => array ('align' => 'center')
, 'delete' => array ('align' => 'center')
));
}
//---------
// DISPLAY
//---------
//PREPARE
// javascript confirm pop up declaration
$htmlHeadXtra[] =
'<script type="text/javascript">
function confirmation (name)
{
if (confirm("'.clean_str_for_javascript(get_lang('Are you sure to delete')).'" + name + "? "))
{return true;}
else
{return false;}
}'
."\n".'</script>'."\n";
//Header
include get_path('incRepositorySys') . '/claro_init_header.inc.php';
// Display tool title
echo claro_html_tool_title($nameTools) . "\n\n";
//Display Forms or dialog box(if needed)
if( isset($dialogBox) ) echo claro_html_message_box($dialogBox);
//Display selectbox and advanced search link
//TOOL LINKS
//Display search form
if ( !empty($isSearchedHTML) )
{
echo claro_html_message_box ('<b>' . get_lang('Search on') . '</b> : <small>' . $isSearchedHTML . '</small>') ;
}
echo '<table width="100%">' . "\n"
. '<tr>' . "\n"
. '<td>' . '<a class="claroCmd" href="adminaddnewuser.php">'
. '<img src="' . get_icon_url('user') . '" alt="" />'
. get_lang('Create user')
. '</a>'
. '</td>' . "\n"
. '<td>' . ''
. '<td align="right">' . "\n"
. '<form action="' . $_SERVER['PHP_SELF'] . '">' . "\n"
. '<label for="search">' . get_lang('Make new search') . ' </label>' . "\n"
. '<input type="text" value="' . htmlspecialchars($search).'" name="search" id="search" />' . "\n"
. '<input type="submit" value=" ' . get_lang('Ok') . ' " />' . "\n"
. '<input type="hidden" name="newsearch" value="yes" />' . "\n"
. ' [<a class="claroCmd" href="advancedUserSearch.php' . $addtoAdvanced . '" >' . get_lang('Advanced') . '</a>]' . "\n"
. '</form>' . "\n"
. '</td>' . "\n"
. '</tr>' . "\n"
. '</table>' . "\n\n"
;
if ( count($userGrid) > 0 ) echo $myPager->disp_pager_tool_bar($_SERVER['PHP_SELF']);
echo $userDataGrid->render();
if ( count($userGrid) > 0 ) echo $myPager->disp_pager_tool_bar($_SERVER['PHP_SELF']);
include get_path('incRepositorySys') . '/claro_init_footer.inc.php';
/**
*
* @todo: the name would be review befor move to a lib
* @todo: eject usage in function of $_SESSION
*
* @return sql statements
*/
function get_sql_filtered_user_list()
{
if ( isset($_SESSION['admin_user_action']) )
{
switch ($_SESSION['admin_user_action'])
{
case 'plateformadmin' :
{
$filterOnStatus = 'plateformadmin';
} break;
case 'createcourse' :
{
$filterOnStatus= 'createcourse';
} break;
case 'followcourse' :
{
$filterOnStatus='followcourse';
} break;
case 'all' :
{
$filterOnStatus='';
} break;
default:
{
trigger_error('admin_user_action value unknow : '.var_export($_SESSION['admin_user_action'],1),E_USER_NOTICE);
$filterOnStatus='followcourse';
}
}
}
else $filterOnStatus='';
$tbl_mdb_names = claro_sql_get_main_tbl();
$sql = "SELECT U.user_id AS user_id,
U.nom AS name,
U.prenom AS firstname,
U.authSource AS authSource,
U.email AS email,
U.officialCode AS officialCode,
U.phoneNumber AS phoneNumber,
U.pictureUri AS pictureUri,
U.creatorId AS creator_id,
U.isCourseCreator ,
U.isPlatformAdmin AS isPlatformAdmin
FROM `" . $tbl_mdb_names['user'] . "` AS U
WHERE 1=1 ";
//deal with admin user search only
if ($filterOnStatus=='plateformadmin')
{
$sql .= " AND U.isPlatformAdmin = 1";
}
//deal with KEY WORDS classification call
if (isset($_SESSION['admin_user_search']))
{
$sql .= " AND (U.nom LIKE '%". claro_sql_escape(pr_star_replace($_SESSION['admin_user_search'])) ."%'
OR U.prenom LIKE '%".claro_sql_escape(pr_star_replace($_SESSION['admin_user_search'])) ."%' ";
$sql .= " OR U.email LIKE '%". claro_sql_escape(pr_star_replace($_SESSION['admin_user_search'])) ."%'";
$sql .= " OR U.username LIKE '". claro_sql_escape(pr_star_replace($_SESSION['admin_user_search'])) ."%'";
$sql .= " OR U.officialCode = '". claro_sql_escape(pr_star_replace($_SESSION['admin_user_search'])) ."')";
}
//deal with ADVANCED SEARCH parameters call
if ( isset($_SESSION['admin_user_firstName']) && !empty($_SESSION['admin_user_firstname']) )
{
$sql .= " AND (U.prenom LIKE '%". claro_sql_escape(pr_star_replace($_SESSION['admin_user_firstName'])) ."%') ";
}
if ( isset($_SESSION['admin_user_lastName']) && !empty($_SESSION['admin_user_lastName']) )
{
$sql .= " AND (U.nom LIKE '%". claro_sql_escape(pr_star_replace($_SESSION['admin_user_lastName']))."%') ";
}
if ( isset($_SESSION['admin_user_userName']) && !empty($_SESSION['admin_user_userName']) )
{
$sql.= " AND (U.username LIKE '%". claro_sql_escape(pr_star_replace($_SESSION['admin_user_userName'])) ."%') ";
}
if ( isset($_SESSION['admin_user_officialCode']) && !empty($_SESSION['admin_user_officialCode']) )
{
$sql.= " AND (U.officialCode LIKE '%". claro_sql_escape(pr_star_replace($_SESSION['admin_user_officialCode'])) ."%') ";
}
if ( isset($_SESSION['admin_user_mail']) && !empty($_SESSION['admin_user_mail']) )
{
$sql.= " AND (U.email LIKE '%". claro_sql_escape(pr_star_replace($_SESSION['admin_user_mail'])) ."%') ";
}
if ($filterOnStatus== 'createcourse' )
{
$sql.=" AND (U.isCourseCreator=1)";
}
elseif ($filterOnStatus=='followcourse' )
{
$sql.=" AND (U.isCourseCreator=0)";
}
return $sql;
}
function prepare_search()
{
$queryStringElementList = array();
$isSearched = array();
if ( !empty($_SESSION['admin_user_search']) )
{
$isSearched[] = $_SESSION['admin_user_search'];
}
if ( !empty($_SESSION['admin_user_firstName']) )
{
$isSearched[] = get_lang('First name') . '=' . $_SESSION['admin_user_firstName'];
$queryStringElementList [] = 'firstName=' . urlencode($_SESSION['admin_user_firstName']);
}
if ( !empty($_SESSION['admin_user_lastName']) )
{
$isSearched[] = get_lang('Last name') . '=' . $_SESSION['admin_user_lastName'];
$queryStringElementList[] = 'lastName=' . urlencode($_SESSION['admin_user_lastName']);
}
if ( !empty($_SESSION['admin_user_userName']) )
{
$isSearched[] = get_lang('Username') . '=' . $_SESSION['admin_user_userName'];
$queryStringElementList[] = 'userName=' . urlencode($_SESSION['admin_user_userName']);
}
if ( !empty($_SESSION['admin_user_officialCode']) )
{
$isSearched[] = get_lang('Official code') . '=' . $_SESSION['admin_user_officialCode'];
$queryStringElementList[] = 'userName=' . urlencode($_SESSION['admin_user_officialCode']);
}
if ( !empty($_SESSION['admin_user_mail']) )
{
$isSearched[] = get_lang('Email') . '=' . $_SESSION['admin_user_mail'];
$queryStringElementList[] = 'mail=' . urlencode($_SESSION['admin_user_mail']);
}
if ( !empty($_SESSION['admin_user_action']) && ($_SESSION['admin_user_action'] == 'followcourse'))
{
$isSearched[] = '<b>' . get_lang('Follow courses') . '</b>';
$queryStringElementList[] = 'action=' . urlencode($_SESSION['admin_user_action']);
}
elseif ( !empty($_SESSION['admin_user_action']) && ($_SESSION['admin_user_action'] == 'createcourse'))
{
$isSearched[] = '<b>' . get_lang('Course creator') . '</b>';
$queryStringElementList[] = 'action=' . urlencode($_SESSION['admin_user_action']);
}
elseif (isset($_SESSION['admin_user_action']) && ($_SESSION['admin_user_action']=='plateformadmin'))
{
$isSearched[] = '<b>' . get_lang('Platform administrator') . ' </b> ';
$queryStringElementList[] = 'action=' . urlencode($_SESSION['admin_user_action']);
}
else $queryStringElementList[] = 'action=all';
if ( count($queryStringElementList) > 0 ) $queryString = '?' . implode('&',$queryStringElementList);
else $queryString = '';
$searchInfo['isSearched'] = $isSearched;
$searchInfo['addtoAdvanced'] = $queryString;
return $searchInfo;
}
?> | yannhos115/claroline-exercice | claroline/admin/adminusers.php | PHP | gpl-2.0 | 18,212 |
//
// Copyright 2002 Sony Corporation
//
// Permission to use, copy, modify, and redistribute this software for
// non-commercial use is hereby granted.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
#include <OPENR/OPENRAPI.h>
#include <OPENR/OSyslog.h>
#include "MoNetAgentManager.h"
#include "MoNetAgent.h"
MoNetAgentManager::MoNetAgentManager() : activeMoNetAgent(0),
activeAgentCommand(),
moNetAgentList(),
effectorSubject(0)
{
for (int i = 0; i < NUM_JOINTS; i++) primitiveID[i] = oprimitiveID_UNDEF;
for (int i = 0; i < NUM_COMMAND_VECTOR; i++) commandRegions[i] = 0;
}
void
MoNetAgentManager::Init()
{
OSYSDEBUG(("MoNetAgentManager::Init()\n"));
OpenPrimitives();
NewCommandVectorData();
list<MoNetAgent*>::iterator iter = moNetAgentList.begin();
list<MoNetAgent*>::iterator last = moNetAgentList.end();
while (iter != last) {
(*iter)->Init();
++iter;
}
}
void
MoNetAgentManager::Start(OSubject* effector)
{
OSYSDEBUG(("MoNetAgentManager::Start()\n"));
effectorSubject = effector;
}
void
MoNetAgentManager::RegisterMoNetAgent(MoNetAgent* m)
{
OSYSDEBUG(("MoNetAgentManager::RegisterMoNetAgent()\n"));
moNetAgentList.push_back(m);
m->SetMoNetAgentManager(this);
}
void
MoNetAgentManager::NotifyCommand(const ONotifyEvent& event,
MoNetAgentResult* result)
{
MoNetAgentCommand* cmd = (MoNetAgentCommand*)event.Data(0);
if (activeMoNetAgent != 0) {
// BUSY
result->agent = cmd->agent;
result->index = cmd->index;
result->status = monetBUSY;
result->endPosture = monetpostureUNDEF;
return;
}
list<MoNetAgent*>::iterator iter = moNetAgentList.begin();
list<MoNetAgent*>::iterator last = moNetAgentList.end();
while (iter != last) {
if ((*iter)->AreYou(cmd->agent) == true) {
(*iter)->NotifyCommand(*cmd, result);
if (result->status != monetSUCCESS) return;
activeMoNetAgent = *iter;
activeAgentCommand = *cmd;
return;
}
++iter;
}
// INVALID_ARG
result->agent = cmd->agent;
result->index = cmd->index;
result->status = monetINVALID_ARG;
result->endPosture = monetpostureUNDEF;
}
void
MoNetAgentManager::ReadyEffector(const OReadyEvent& event,
MoNetAgentResult* result)
{
if (activeMoNetAgent == 0) {
result->agent = monetagentUNDEF;
result->index = -1;
result->status = monetSUCCESS;
result->endPosture = monetpostureUNDEF;
return;
}
activeMoNetAgent->ReadyEffector(activeAgentCommand, result);
if (result->status != monetSUCCESS) {
activeMoNetAgent = 0;
activeAgentCommand.Clear();
}
}
void
MoNetAgentManager::OpenPrimitives()
{
OSYSDEBUG(("MoNetAgentManager::OpenPrimitives()\n"));
OStatus result;
for (int i = 0; i < NUM_JOINTS; i++) {
result = OPENR::OpenPrimitive(JOINT_LOCATOR[i], &primitiveID[i]);
if (result != oSUCCESS) {
OSYSLOG1((osyslogERROR, "%s : %s %d",
"MoNetAgentManager::OpenPrimitives()",
"OPENR::OpenPrimitive() FAILED", result));
}
}
}
void
MoNetAgentManager::NewCommandVectorData()
{
OSYSDEBUG(("MoNetAgentManager::NewCommandVectorData()\n"));
OStatus result;
MemoryRegionID cmdVecDataID;
OCommandVectorData* cmdVecData;
OCommandInfo* info;
for (int i = 0; i < NUM_COMMAND_VECTOR; i++) {
result = OPENR::NewCommandVectorData(NUM_JOINTS,
&cmdVecDataID, &cmdVecData);
if (result != oSUCCESS) {
OSYSLOG1((osyslogERROR, "%s : %s %d",
"MoNetAgentManager::NewCommandVectorData()",
"OPENR::NewCommandVectorData() FAILED", result));
}
commandRegions[i] = new RCRegion(cmdVecData->vectorInfo.memRegionID,
cmdVecData->vectorInfo.offset,
(void*)cmdVecData,
cmdVecData->vectorInfo.totalSize);
cmdVecData->SetNumData(NUM_JOINTS);
for (int j = 0; j < NUM_JOINTS; j++) {
info = cmdVecData->GetInfo(j);
info->Set(odataJOINT_COMMAND2, primitiveID[j], NUM_FRAMES);
}
}
}
RCRegion*
MoNetAgentManager::FindFreeCommandRegion()
{
for (int i = 0; i < NUM_COMMAND_VECTOR; i++) {
if (commandRegions[i]->NumberOfReference() == 1) {
return commandRegions[i];
}
}
OSYSPRINT(("err\n"));
OSYSLOG1((osyslogERROR, "%s : %s %d",
"MoNetAgentManager::FindFreeCommandRegion()",
"FAILED", 0));
return 0;
}
int
MoNetAgentManager::GetIndexFromJointName( const char *jointName )
{
for ( int i = 0; i < NUM_JOINTS; i ++ ) {
if ( !strcmp( JOINT_LOCATOR[ i ], jointName ) ) {
return i;
}
}
OSYSLOG1((osyslogERROR, "%s : %s",
"MoNetAgentManager::GetIndexFromJointName()",
"invalid joint name"));
return 0;
}
void
MoNetAgentManager::NotifyPose(const ONotifyEvent& event)
{
PoseData* data = (PoseData*)event.Data(0);
list<MoNetAgent*>::iterator iter = moNetAgentList.begin();
list<MoNetAgent*>::iterator last = moNetAgentList.end();
while (iter != last) {
if ((*iter)->AreYou(monetagentANY) == true) {
(*iter)->SetPose(data);
return;
}
++iter;
}
}
| EiichiroIto/scratch-aibo | MotionAgents/MoNetAgentManager.cc | C++ | gpl-2.0 | 5,877 |
<?php
/*
Plugin Name: Калькулятор цен
Plugin URI: none
Description: Плагин загрузки цен на услуги СТО для калькулятора цен на сайте Автодоктор
Version: 3.1.5
Author: WebUniverse
Author URI: http://webuniverse.com.ua/
*/
define( 'prices_calculator_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'prices_calculator_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( str_replace(chr(92), '/', ABSPATH) . 'wp-admin/includes/file.php' );
}
require_once( str_replace(chr(92), '/', ABSPATH) . 'wp-includes/pluggable.php');
require_once('php_excel/Classes/PHPExcel.php');
function addAdminPagePricesCalculator(){
add_menu_page('Система анализа загруженного .xls файла и его разбор для Калькулятора цен',
'Калькулятор цен',
8,
'prices_calculator',
'pricesCalculatorOptionsPage');
}
function pricesCalculatorOptionsPage(){
global $wpdb;
echo '<h2>Система анализа загруженного .xls файла и его разбор для Калькулятора цен</h2>';
if($_FILES['file']){
$uploadedfile = $_FILES['file'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile && !isset( $movefile['error'] ) ) {
echo "Успешно загруженный файл, файл: ";
echo $movefile['file'] . "<br><br>";
readXLSXDocument($wpdb, $movefile['file']);
//var_dump( $movefile);
} else {
echo "Ошибка: ";
echo $movefile['error'];
}
}
if($_POST['delete']){
$results = json_decode(json_encode($wpdb->get_results( 'SELECT pc_services.* FROM pc_services
WHERE pc_services.id_service = ' . $_POST['delete'] . ' LIMIT 1; ' )),true);
$id_category = $results[0]['id_category'];
$wpdb->query(
"DELETE FROM pc_services WHERE id_service = '" . $_POST['delete'] . "'"
);
$results = json_decode(json_encode($wpdb->get_results( 'SELECT pc_services.* FROM pc_services
WHERE pc_services.id_category = ' . $id_category . ' LIMIT 1; ' )),true);
if(!$results){
$wpdb->query(
"DELETE FROM pc_categories WHERE id_category = '" . $id_category . "'"
);
}
echo "Успешно удалено!<br><br><br>";
}
echo '<h3>Загрузите Excel файл для его разбора системой:</h3><br>
<form method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "file"><br><br><br>
<input type = "submit" value = "Отправить">
</form><br><br>';
echo "<h3>Имеющиейся данные:</h3><br>";
$results = json_decode(json_encode($wpdb->get_results( 'SELECT pc_services.*, pc_categories.* FROM pc_services
INNER JOIN pc_categories
ON pc_services.id_category = pc_categories.id_category' )),true);
if($results){
echo '<table border = "1" cellspacing="2" cellpadding="10">
<tr>
<td><strong>Категория</strong></td>
<td><strong>Услуга</strong></td>
<td><strong>Стоимость</strong></td>
<td><strong>Удалить</strong></td>
</tr>';
foreach ($results as $data) {
echo '<tr>
<td>' . $data['category'] . '</td>
<td>' . $data['service'] . '</td>
<td>' . $data['price'] . '</td>
<td>
<form method = "POST">
<input type = "hidden" name = "delete" value = "' . $data['id_service'] . '">
<input type = "submit" value = "Удалить">
</form>
</td>
</tr>';
}
echo '</table>';
}
}
function readXLSXDocument($wpdb, $file_name){
$inputFileName = $file_name;
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
. '": ' . $e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
for ($row = 2; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
if($rowData[0]){
echo 'Были произведены действия:<br>';
foreach($rowData[0] as $k=>$v){
if($k == 0){
$service_category = $v;
}else if($k == 1){
$service = $v;
}else if($k == 2){
$service_price = $v;
if(addPrices($wpdb, $service_category, $service, $service_price)){
echo "Добавлено - Категория: " . $service_category . ". Услуга: " . $service . ". Стоимость = " . $service_price . "<br/>";
}else{
echo "Обновлено - Категория: " . $service_category . ". Услуга: " . $service . ". Стоимость = " . $service_price . "<br/>";
}
}
}
}
}
}
function addPrices($wpdb, $category, $service, $price){
$added = false;
$results = json_decode(json_encode($wpdb->get_results( 'SELECT * FROM pc_categories WHERE category = "' . $category . '"' )),true);
if(!$results){
$wpdb->insert(
'pc_categories',
array(
'category' => $category
)
);
$id = $wpdb->insert_id;
}else{
$id = $results[0]['id_category'];
}
$results = json_decode(json_encode($wpdb->get_results( 'SELECT * FROM pc_services WHERE id_category = "' . $id . '" AND
service = "' . $service . '"' )), true);
if(!$results){
$wpdb->insert(
'pc_services',
array(
'id_category' => $id,
'service' => $service,
'price' => $price
)
);
$added = true;
}else{
$wpdb->update(
'pc_services',
array(
'price' => $price
),
array( 'id_service' => $results[0]['id_service'] )
);
}
return $added;
}
add_action('admin_menu', 'addAdminPagePricesCalculator');
| PapaPsih/Avtodoctor | wp-content/plugins/prices_calculator/prices_calculator.php | PHP | gpl-2.0 | 6,459 |
import testlib.flowexpression.qual.FlowExp;
public class Canonicalization {
class LockExample {
protected final Object myLock = new Object();
protected @FlowExp("myLock") Object locked;
protected @FlowExp("this.myLock") Object locked2;
public @FlowExp("myLock") Object getLocked() {
return locked;
}
}
class Use {
final LockExample lockExample1 = new LockExample();
final Object myLock = new Object();
@FlowExp("lockExample1.myLock") Object o1 = lockExample1.locked;
@FlowExp("lockExample1.myLock") Object o2 = lockExample1.locked2;
@FlowExp("myLock")
//:: error: (assignment.type.incompatible)
Object o3 = lockExample1.locked;
@FlowExp("this.myLock")
//:: error: (assignment.type.incompatible)
Object o4 = lockExample1.locked2;
@FlowExp("lockExample1.myLock") Object oM1 = lockExample1.getLocked();
@FlowExp("myLock")
//:: error: (assignment.type.incompatible)
Object oM2 = lockExample1.getLocked();
@FlowExp("this.myLock")
//:: error: (assignment.type.incompatible)
Object oM3 = lockExample1.getLocked();
}
}
| CharlesZ-Chen/checker-framework | framework/tests/flowexpression/Canonicalization.java | Java | gpl-2.0 | 1,226 |
/******************************************************************************
*
* Metodología de la Programación
* Grado en Ingeniería Informática
*
* 2014 - Ernesto Serrano Collado
* ------------------------------
*
* Supongamos que para definir matrices bidimensionales dinamicas usamos una
* estructura como la que aparece en la figura 4(tipo Matriz2D-1). En los apuntes
* de clase se detalla como crear y liberar esta estructura.
* Nota: Recuerde que los modulos que procesan estructuras de este tipo necesitan
* recibir como parametros el numero de filas y columnas de la matriz.
*
* a) Construir un modulo que lea del teclado fils×cols valores y los copie en la
* matriz.
* b) Construir un modulo que muestre los valores guardados en la matriz.
* c) Construir un modulo que reciba una matriz de ese tipo, cree y devuelva una
* copia.
* d) Construir un modulo que extraiga una submatriz de una matriz bidimensional
* Matriz2D-1. Como argumento de la funcion se introduce desde que fila y
* columna y hasta que fila y columna se debe realizar la copia de la matriz
* original. La submatriz devuelta es una nueva matriz.
* e) Construir un modulo que elimine una fila de una matriz bidimensional
* Matriz2D-1. Obviamente, no se permiten “huecos” (filas vacias). El modulo
* devuelve una nueva matriz.
* f) Construir un modulo como el anterior,pero que en vez de eliminar una fila,
* elimine una columna. El modulo devuelve una nueva matriz.
* g) Construir un modulo que devuelva la traspuesta de una matriz. La matriz
* devuelta es una nueva matriz.
* h) Construir un modulo que reciba una matriz y la modifique, de tal manera
* que “invierta” las filas: la primera sera la ultima, la segunda la
* penultima, y asi sucesivamente. El modulo devuelve una nueva matriz.
*
******************************************************************************/
#include <iostream> //Inclusión de los recursos de E/S
#include <iomanip>
#include "Matriz2D_1.h"
using namespace std;
/*****************************************************************************/
//Programa Principal
int main(){
Matriz2D_1 m1; // "m1" matriz dinamicas 2D.
int filas, cols;
// Leer num. de filas y columnas
cout << "Numero de filas : ";
cin >> filas;
cout << "Numero de columnas : ";
cin >> cols;
// Crear matrices dinamicas
cout << "Creando Matriz ("<< filas << "X"<< cols << ")" << endl;
m1 = CreaMatriz2D_1 (filas, cols);
//Llena la matriz y muestra su contenido
m1 = LlenarMatriz2D_1(m1, filas, cols);
cout << endl << "Matriz Original:" << endl;
PintaMatriz2D_1 (m1, filas, cols);
//Copia la matriz y muestra su contenido
Matriz2D_1 copia_m1 = CopiaMatriz2D_1(m1, filas, cols);
cout << endl << "Copia Matriz:" << endl;
PintaMatriz2D_1 (copia_m1, filas, cols);
LiberaMatriz2D_1 (copia_m1, filas, cols);
int desde = 0, hasta = 2;
if (filas >= hasta && cols >= hasta) {
//Crea una submatriz y muestra su contenido
Matriz2D_1 sub_m1 = SubMatriz2D_1(m1, desde, desde, hasta, hasta);
cout << endl << "Sub Matriz:" << endl;
PintaMatriz2D_1 (sub_m1, hasta - desde, hasta - desde);
LiberaMatriz2D_1 (sub_m1, hasta - desde, hasta - desde);
}
//Elimina una fila de la matriz y muestra su contenido
Matriz2D_1 delf_m1 = EliminaFilaMatriz2D_1(m1, filas, cols, 0);
cout << endl << "Matriz con fila eliminada:" << endl;
PintaMatriz2D_1 (delf_m1, filas - 1, cols);
LiberaMatriz2D_1 (delf_m1, filas - 1, cols);
//Elimina una columna de la matriz y muestra su contenido
Matriz2D_1 delc_m1 = EliminaColumnaMatriz2D_1(m1, filas, cols, 0);
cout << endl << "Matriz con columna eliminada:" << endl;
PintaMatriz2D_1 (delc_m1, filas, cols - 1);
LiberaMatriz2D_1 (delc_m1, filas, cols - 1);
//Obtiene la traspuesta de la matriz y muestra su contenido
Matriz2D_1 tras_m1 = TraspuestaMatriz2D_1(m1, filas, cols);
cout << endl << "Traspuesta Matriz:" << endl;
PintaMatriz2D_1 (tras_m1, cols, filas);
LiberaMatriz2D_1 (tras_m1, cols, filas);
//Obtiene la inversa de la matriz y muestra su contenido
Matriz2D_1 inv_m1 = InvierteMatriz2D_1(m1, filas, cols);
cout << endl << "Matriz invertida:" << endl;
PintaMatriz2D_1 (inv_m1, filas, cols);
LiberaMatriz2D_1 (inv_m1, filas, cols);
// Liberar la memoria ocupada
cout << endl << "Liberando matriz" << endl;
LiberaMatriz2D_1 (m1, filas, cols);
return (0);
} | erseco/ugr_metodologia_programacion | Practica_5/src/ejercicio8.cpp | C++ | gpl-2.0 | 4,558 |
# -*- coding: utf-8 -*-
#
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.conf import settings
from django.utils.translation import gettext_lazy as _
def jumpserver_processor(request):
# Setting default pk
context = {
'DEFAULT_PK': '00000000-0000-0000-0000-000000000000',
'LOGO_URL': static('img/logo.png'),
'LOGO_TEXT_URL': static('img/logo_text.png'),
'LOGIN_IMAGE_URL': static('img/login_image.png'),
'FAVICON_URL': static('img/facio.ico'),
'JMS_TITLE': 'Jumpserver',
'VERSION': settings.VERSION,
'COPYRIGHT': 'FIT2CLOUD 飞致云' + ' © 2014-2019',
'SECURITY_COMMAND_EXECUTION': settings.SECURITY_COMMAND_EXECUTION,
'SECURITY_MFA_VERIFY_TTL': settings.SECURITY_MFA_VERIFY_TTL,
}
return context
| eli261/jumpserver | apps/jumpserver/context_processor.py | Python | gpl-2.0 | 835 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using AnimationExample;
namespace ProjectSneakyGame
{
/// <summary>
/// Extension of the DrawableGameComponent class.
/// Includes set-up and functions for 3D matrix movement of DrawableGameComponent types.
/// </summary>
public class DrawableMovableComponent : DrawableGameComponent
{
protected float _speed;
protected Vector3 _pos;
protected Matrix _trans, _rot, _scale, _main;
protected Game1 _game;
protected MovableBoundingBox _bBox;
public float Speed { get { return _speed; } set { _speed = value; } }
public Vector3 Pos { get { return _pos; } set { _pos = value; } }
public Matrix TranslationM { get { return _trans; } set { _trans = value; } }
public Matrix RotationM { get { return _trans; } set { _trans = value; } }
public Matrix ScaleM { get { return _scale; } set { _scale = value; } }
public Matrix TransformationM { get { return _main; } }
public MovableBoundingBox BoundingBox { get { return _bBox; } set { _bBox = value; } }
public DrawableMovableComponent(Game1 game):base(game)
{
_pos = Vector3.One;
_main = Matrix.Identity;
_trans = Matrix.Identity;
_rot = Matrix.Identity;
_scale = Matrix.Identity;
_game = game;
_speed = 0;
}
public DrawableMovableComponent(Game1 game, Vector3 pos)
: base(game)
{
_pos = pos;
//_trans.Translation = _pos;
_trans = Matrix.CreateTranslation(pos);
_rot = Matrix.Identity;
_scale = Matrix.Identity;
_main = Matrix.Identity;
_speed = 0;
_game = game;
}
public DrawableMovableComponent(Game1 game, Vector3 pos, float speed)
: base(game)
{
_pos = pos;
//_trans.Translation = _pos;
_trans = Matrix.CreateTranslation(pos);
_rot = Matrix.Identity;
_scale = Matrix.Identity;
_main = Matrix.Identity;
_speed = speed;
_game = game;
}
public virtual void Translate(Vector3 vec, GameTime g)
{
_trans *= Matrix.CreateTranslation(vec * (float)g.ElapsedGameTime.TotalSeconds);
_pos += vec * (float)g.ElapsedGameTime.TotalSeconds;
}
public virtual void Translate(Vector3 vec)
{
_trans *= Matrix.CreateTranslation(vec);
_pos += vec;
}
public virtual void Translate(float x, float y, float z, GameTime g)
{
Vector3 temp = new Vector3(x,y,z);
_trans *= Matrix.CreateTranslation(temp * (float)g.ElapsedGameTime.TotalSeconds);
_pos += temp * (float)g.ElapsedGameTime.TotalSeconds;
}
public virtual void Translate(float x, float y, float z)
{
Vector3 temp = new Vector3(x, y, z);
_trans *= Matrix.CreateTranslation(temp);
_pos += temp;
}
public virtual void RotateX(float rot, GameTime g)
{
_rot *= Matrix.CreateRotationX(rot * (float)g.ElapsedGameTime.TotalSeconds);
_pos += _rot.Translation;
}
public virtual void RotateX(float rot)
{
_rot *= Matrix.CreateRotationX(rot);
_pos += _rot.Translation;
}
public virtual void RotateY(float rot, GameTime g)
{
_rot *= Matrix.CreateRotationY(rot * (float)g.ElapsedGameTime.TotalSeconds);
_pos += _rot.Translation;
}
public virtual void RotateY(float rot)
{
_rot *= Matrix.CreateRotationY(rot);
_pos += _rot.Translation;
}
public virtual void RotateZ(float rot, GameTime g)
{
_rot *= Matrix.CreateRotationZ(rot * (float)g.ElapsedGameTime.TotalSeconds);
_pos += _rot.Translation;
}
public virtual void RotateZ(float rot)
{
_rot *= Matrix.CreateRotationZ(rot);
_pos += _rot.Translation;
}
public virtual void RotateOnAxis(Vector3 axis, float rot, GameTime g)
{
_rot *= Matrix.CreateFromAxisAngle(axis, rot * (float)g.ElapsedGameTime.TotalSeconds);
_pos += _rot.Translation;
}
public virtual void RotateOnAxis(Vector3 axis, float rot)
{
_rot *= Matrix.CreateFromAxisAngle(axis, rot);
_pos += _rot.Translation;
}
public virtual void Scale(float scale, GameTime g)
{
_scale *= Matrix.CreateScale(scale * (float)g.ElapsedGameTime.TotalSeconds);
}
public virtual void Scale(float scale)
{
_scale *= Matrix.CreateScale(scale);
}
public virtual void Scale(float x, float y, float z, GameTime g)
{
Vector3 temp = new Vector3(x, y, z);
temp *= (float)g.ElapsedGameTime.TotalSeconds;
_scale *= Matrix.CreateScale(temp);
}
public virtual void Scale(float x, float y, float z)
{
_scale *= Matrix.CreateScale(x, y, z);
}
public virtual void Scale(Vector3 vec, GameTime g)
{
_scale *= Matrix.CreateScale(vec * (float)g.ElapsedGameTime.TotalSeconds);
}
public virtual void Scale(Vector3 vec)
{
_scale *= Matrix.CreateScale(vec);
}
public virtual void MoveForward(GameTime g)
{
Translate(Vector3.Forward * _speed, g);
}
public virtual void MoveBackward(GameTime g)
{
Translate(Vector3.Backward * _speed, g);
}
public virtual void MoveUp(GameTime g)
{
Translate(Vector3.Up * _speed, g);
}
public virtual void MoveDown(GameTime g)
{
Translate(Vector3.Down * _speed, g);
}
public virtual void MoveLeft(GameTime g)
{
Translate(Vector3.Left * _speed, g);
}
public virtual void MoveRight(GameTime g)
{
Translate(Vector3.Right * _speed, g);
}
public virtual void Move(GameTime g, Vector3 dir)
{
Translate(dir * _speed, g);
}
/// <summary>
/// Resets the GraphicsDevice states so that they are able to draw 3D objects.
/// </summary>
protected void SetGraphicsStatesFor3D()
{
_game.GraphicsDevice.RasterizerState = GraphicsDeviceStates.Rasterizer3DNormal;
_game.GraphicsDevice.BlendState = GraphicsDeviceStates.Blend3DNormal;
_game.GraphicsDevice.DepthStencilState = GraphicsDeviceStates.DepthStencil3DNormal;
_game.GraphicsDevice.SamplerStates[0] = GraphicsDeviceStates.Sampler3DNormal;
}
public override void Update(GameTime gameTime)
{
_main = _scale * _rot * _trans;
if (_bBox != null)
_bBox.Transform(_trans.Translation);
base.Update(gameTime);
}
static public implicit operator BoundingBox(DrawableMovableComponent obj)
{
return obj._bBox;
}
}
}
| JoshuaKlaser/ANSKLibrary | AnimationExample/AnimationExample/DrawableMovableComponent.cs | C# | gpl-2.0 | 7,452 |
<?php
/**
* Sources English lexicon topic
*
* @language en
* @package modx
* @subpackage lexicon
*/
$_lang['access'] = 'Åtkomsträttigheter';
$_lang['base_path'] = 'Bassökväg';
$_lang['base_path_relative'] = 'Relativ bassökväg?';
$_lang['base_url'] = 'Bas-URL';
$_lang['base_url_relative'] = 'Relativ bas-URL?';
$_lang['minimum_role'] = 'Minimiroll';
$_lang['path_options'] = 'Sökvägsalternativ';
$_lang['policy'] = 'Policy';
$_lang['source'] = 'Mediakälla';
$_lang['source_access_add'] = 'Lägg till användargrupp';
$_lang['source_access_remove'] = 'Ta bort tillgång';
$_lang['source_access_remove_confirm'] = 'Är du säker på att du vill ta bort tillgång till denna källa för denna användargrupp?';
$_lang['source_access_update'] = 'Uppdatera tillgång';
$_lang['source_create'] = 'Skapa ny mediakälla';
$_lang['source_description_desc'] = 'En kort beskrivning av mediakällan.';
$_lang['source_duplicate'] = 'Duplicera mediakälla';
$_lang['source_err_ae_name'] = 'Det finns redan en mediakälla med det namnet! Ange ett annat namn.';
$_lang['source_err_nf'] = 'Mediakällan kunde inte hittas!';
$_lang['source_err_nfs'] = 'Kan inte hitta mediakällan med id: [[+id]].';
$_lang['source_err_ns'] = 'Ange mediakällan.';
$_lang['source_err_ns_name'] = 'Ange ett namn för mediakällan.';
$_lang['source_name_desc'] = 'Mediakällans namn';
$_lang['source_properties.intro_msg'] = 'Hantera egenskaperna för denna källa nedan.';
$_lang['source_remove'] = 'Ta bort mediakälla';
$_lang['source_remove_confirm'] = 'Är du säker på att du vill ta bort denna mediakälla? Detta kan ha sönder mallvariabler som du har tilldelat till denna källa.';
$_lang['source_remove_multiple'] = 'Ta bort flera mediakällor';
$_lang['source_remove_multiple_confirm'] = 'Är du säker på att du vill ta bort dessa mediakällor? Detta kan ha sönder mallvariabler som du har tilldelat till dessa källor.';
$_lang['source_update'] = 'Uppdatera mediakälla';
$_lang['source_type'] = 'Källtyp';
$_lang['source_type_desc'] = 'Mediakällans typ eller drivrutin. Källan kommer att använda denna drivrutin för att ansluta när den hämtar sin data. Till exempel: Filsystem hämtar filer från filsystemet. S3 hämtar filer från en S3-hink.';
$_lang['source_type.file'] = 'Filsystem';
$_lang['source_type.file_desc'] = 'En filsystembaserad källa som navigerar bland din servers filer.';
$_lang['source_type.s3'] = 'Amazon S3';
$_lang['source_type.s3_desc'] = 'Navigerar en Amazon S3-hink.';
$_lang['source_types'] = 'Källtyper';
$_lang['source_types.intro_msg'] = 'Det här är en lista med alla de installerade typer av mediakällor som du har i denna MODX-instans.';
$_lang['source.access.intro_msg'] = 'Här kan du begränsa en mediakälla till specifika användargrupper och ange policyer för dessa användargrupper. En mediakälla som inte är ihopkopplad med några användargrupper är tillgänglig för alla användare av hanteraren.';
$_lang['sources'] = 'Mediakällor';
$_lang['sources.intro_msg'] = 'Hantera alla dina mediakällor här.';
$_lang['user_group'] = 'Användargrupp';
/* file source type */
$_lang['prop_file.allowedFileTypes_desc'] = 'Om denna aktiveras så kommer den att begränsa de filer som visas till endast de filsuffix som anges här. Skriv som en kommaseparerad lista utan punkter.';
$_lang['prop_file.basePath_desc'] = 'Den filsökväg som källan ska pekas mot.';
$_lang['prop_file.basePathRelative_desc'] = 'Om bassökvägen ovan inte är relativ till installationssökvägen för MODX, så sätter du den här till Nej.';
$_lang['prop_file.baseUrl_desc'] = 'Den URL som denna källa kan kommas åt från.';
$_lang['prop_file.baseUrlPrependCheckSlash_desc'] = 'Om denna sätts till "Ja" kommer MODX bara att lägga till baseURL i början av sökvägen om inget snedstreck (/) finns i början av URL:en när en mallvariabel ska visas. Det här är användbart om du vill ange ett värde på en mallvariabel som ligger utanför baseURL.';
$_lang['prop_file.baseUrlRelative_desc'] = 'Om inställningen för rot-URL ovan inte är relativ till MODX installations-URL sätter du denna till "Nej".';
$_lang['prop_file.imageExtensions_desc'] = 'En kommaseparerad lista med de filsuffix som ska användas som bilder. MODX kommer att försöka göra tumnaglar av filer med dessa suffix.';
$_lang['prop_file.skipFiles_desc'] = 'En kommaseparerad lista. MODX kommer att hoppa över och gömma filer och mappar som matchar någon av dessa.';
$_lang['prop_file.thumbnailQuality_desc'] = 'Kvalitén på de renderade tumnaglarna på en skala från 0-100.';
$_lang['prop_file.thumbnailType_desc'] = 'Den bildtyp som tumnaglarna ska renderas som.';
/* s3 source type */
$_lang['bucket'] = 'Hink';
$_lang['prop_s3.bucket_desc'] = 'Den S3-hink som din data ska laddas från.';
$_lang['prop_s3.key_desc'] = 'Amazons nyckel som ska användas för autentisering till hinken.';
$_lang['prop_s3.imageExtensions_desc'] = 'En kommaseparerad lista med de filsuffix som ska användas som bilder. MODX kommer att försöka göra tumnaglar av filer med dessa suffix.';
$_lang['prop_s3.secret_key_desc'] = 'Amazons hemliga nyckel som ska användas för autentisering till hinken.';
$_lang['prop_s3.skipFiles_desc'] = 'En kommaseparerad lista. MODX kommer att hoppa över och gömma filer och mappar som matchar någon av dessa.';
$_lang['prop_s3.thumbnailQuality_desc'] = 'Kvalitén på de renderade tumnaglarna på en skala från 0-100.';
$_lang['prop_s3.thumbnailType_desc'] = 'Den bildtyp som tumnaglarna ska renderas som.';
$_lang['prop_s3.url_desc'] = 'URL:en för Amazon S3-instansen.';
$_lang['s3_no_move_folder'] = 'S3-drivrutinen stödjer än så länge inte flyttning av mappar.'; | svyatoslavteterin/belton.by | core/lexicon/sv/source.inc.php | PHP | gpl-2.0 | 5,705 |
/*
* Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Blades_Edge_Mountains
SD%Complete: 90
SDComment: Quest support: 10503, 10504, 10556, 10609, 10682, 10821, 10980. Ogri'la->Skettis Flight. (npc_daranelle needs bit more work before consider complete)
SDCategory: Blade's Edge Mountains
EndScriptData */
/* ContentData
mobs_bladespire_ogre
mobs_nether_drake
npc_daranelle
npc_overseer_nuaar
npc_saikkal_the_elder
go_legion_obelisk
EndContentData */
#include "ScriptPCH.h"
//Support for quest: You're Fired! (10821)
bool obelisk_one, obelisk_two, obelisk_three, obelisk_four, obelisk_five;
#define LEGION_OBELISK_ONE 185193
#define LEGION_OBELISK_TWO 185195
#define LEGION_OBELISK_THREE 185196
#define LEGION_OBELISK_FOUR 185197
#define LEGION_OBELISK_FIVE 185198
/*######
## mobs_bladespire_ogre
######*/
//TODO: add support for quest 10512 + Creature abilities
class mobs_bladespire_ogre : public CreatureScript
{
public:
mobs_bladespire_ogre() : CreatureScript("mobs_bladespire_ogre") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new mobs_bladespire_ogreAI (pCreature);
}
struct mobs_bladespire_ogreAI : public ScriptedAI
{
mobs_bladespire_ogreAI(Creature *c) : ScriptedAI(c) {}
void Reset() { }
void UpdateAI(const uint32 /*uiDiff*/)
{
if (!UpdateVictim())
return;
DoMeleeAttackIfReady();
}
};
};
/*######
## mobs_nether_drake
######*/
enum eNetherdrake
{
SAY_NIHIL_1 = -1000169, //signed for 5955
SAY_NIHIL_2 = -1000170, //signed for 5955
SAY_NIHIL_3 = -1000171, //signed for 5955
SAY_NIHIL_4 = -1000172, //signed for 20021, used by 20021, 21817, 21820, 21821, 21823
SAY_NIHIL_INTERRUPT = -1000173, //signed for 20021, used by 20021, 21817, 21820, 21821, 21823
ENTRY_WHELP = 20021,
ENTRY_PROTO = 21821,
ENTRY_ADOLE = 21817,
ENTRY_MATUR = 21820,
ENTRY_NIHIL = 21823,
SPELL_T_PHASE_MODULATOR = 37573,
SPELL_ARCANE_BLAST = 38881,
SPELL_MANA_BURN = 38884,
SPELL_INTANGIBLE_PRESENCE = 36513
};
class mobs_nether_drake : public CreatureScript
{
public:
mobs_nether_drake() : CreatureScript("mobs_nether_drake") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new mobs_nether_drakeAI (pCreature);
}
struct mobs_nether_drakeAI : public ScriptedAI
{
mobs_nether_drakeAI(Creature *c) : ScriptedAI(c) {}
bool IsNihil;
uint32 NihilSpeech_Timer;
uint32 NihilSpeech_Phase;
uint32 ArcaneBlast_Timer;
uint32 ManaBurn_Timer;
uint32 IntangiblePresence_Timer;
void Reset()
{
IsNihil = false;
NihilSpeech_Timer = 3000;
NihilSpeech_Phase = 0;
ArcaneBlast_Timer = 7500;
ManaBurn_Timer = 10000;
IntangiblePresence_Timer = 15000;
}
void EnterCombat(Unit* /*who*/) {}
void MoveInLineOfSight(Unit *who)
{
if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE))
return;
ScriptedAI::MoveInLineOfSight(who);
}
//in case Creature was not summoned (not expected)
void MovementInform(uint32 type, uint32 id)
{
if (type != POINT_MOTION_TYPE)
return;
if (id == 0)
{
me->setDeathState(JUST_DIED);
me->RemoveCorpse();
me->SetHealth(0);
}
}
void SpellHit(Unit *caster, const SpellEntry *spell)
{
if (spell->Id == SPELL_T_PHASE_MODULATOR && caster->GetTypeId() == TYPEID_PLAYER)
{
const uint32 entry_list[4] = {ENTRY_PROTO, ENTRY_ADOLE, ENTRY_MATUR, ENTRY_NIHIL};
int cid = rand()%(4-1);
if (entry_list[cid] == me->GetEntry())
++cid;
//we are nihil, so say before transform
if (me->GetEntry() == ENTRY_NIHIL)
{
DoScriptText(SAY_NIHIL_INTERRUPT, me);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
IsNihil = false;
}
if (me->UpdateEntry(entry_list[cid]))
{
if (entry_list[cid] == ENTRY_NIHIL)
{
EnterEvadeMode();
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
IsNihil = true;
} else
AttackStart(caster);
}
}
}
void UpdateAI(uint32 const diff)
{
if (IsNihil)
{
if (NihilSpeech_Timer <= diff)
{
switch(NihilSpeech_Phase)
{
case 0:
DoScriptText(SAY_NIHIL_1, me);
++NihilSpeech_Phase;
break;
case 1:
DoScriptText(SAY_NIHIL_2, me);
++NihilSpeech_Phase;
break;
case 2:
DoScriptText(SAY_NIHIL_3, me);
++NihilSpeech_Phase;
break;
case 3:
DoScriptText(SAY_NIHIL_4, me);
++NihilSpeech_Phase;
break;
case 4:
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
//take off to location above
me->GetMotionMaster()->MovePoint(0, me->GetPositionX()+50.0f, me->GetPositionY(), me->GetPositionZ()+50.0f);
++NihilSpeech_Phase;
break;
}
NihilSpeech_Timer = 5000;
} else NihilSpeech_Timer -=diff;
//anything below here is not interesting for Nihil, so skip it
return;
}
if (!UpdateVictim())
return;
if (IntangiblePresence_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_INTANGIBLE_PRESENCE);
IntangiblePresence_Timer = 15000+rand()%15000;
} else IntangiblePresence_Timer -= diff;
if (ManaBurn_Timer <= diff)
{
Unit *pTarget = me->getVictim();
if (pTarget && pTarget->getPowerType() == POWER_MANA)
DoCast(pTarget, SPELL_MANA_BURN);
ManaBurn_Timer = 8000+rand()%8000;
} else ManaBurn_Timer -= diff;
if (ArcaneBlast_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_ARCANE_BLAST);
ArcaneBlast_Timer = 2500+rand()%5000;
} else ArcaneBlast_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
/*######
## npc_daranelle
######*/
enum eDaranelle
{
SAY_SPELL_INFLUENCE = -1000174,
SPELL_LASHHAN_CHANNEL = 36904
};
class npc_daranelle : public CreatureScript
{
public:
npc_daranelle() : CreatureScript("npc_daranelle") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new npc_daranelleAI (pCreature);
}
struct npc_daranelleAI : public ScriptedAI
{
npc_daranelleAI(Creature *c) : ScriptedAI(c) {}
void Reset() { }
void EnterCombat(Unit* /*who*/) {}
void MoveInLineOfSight(Unit *who)
{
if (who->GetTypeId() == TYPEID_PLAYER)
{
if (who->HasAura(SPELL_LASHHAN_CHANNEL) && me->IsWithinDistInMap(who, 10.0f))
{
DoScriptText(SAY_SPELL_INFLUENCE, me, who);
//TODO: Move the below to updateAI and run if this statement == true
DoCast(who, 37028, true);
}
}
ScriptedAI::MoveInLineOfSight(who);
}
};
};
/*######
## npc_overseer_nuaar
######*/
#define GOSSIP_HELLO_ON "Overseer, I am here to negotiate on behalf of the Cenarion Expedition."
class npc_overseer_nuaar : public CreatureScript
{
public:
npc_overseer_nuaar() : CreatureScript("npc_overseer_nuaar") { }
bool OnGossipSelect(Player* pPlayer, Creature* pCreature, uint32 /*uiSender*/, uint32 uiAction)
{
pPlayer->PlayerTalkClass->ClearMenus();
if (uiAction == GOSSIP_ACTION_INFO_DEF+1)
{
pPlayer->SEND_GOSSIP_MENU(10533, pCreature->GetGUID());
pPlayer->AreaExploredOrEventHappens(10682);
}
return true;
}
bool OnGossipHello(Player* pPlayer, Creature* pCreature)
{
if (pPlayer->GetQuestStatus(10682) == QUEST_STATUS_INCOMPLETE)
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HELLO_ON, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
pPlayer->SEND_GOSSIP_MENU(10532, pCreature->GetGUID());
return true;
}
};
/*######
## npc_saikkal_the_elder
######*/
#define GOSSIP_HELLO_STE "Yes... yes, it's me."
#define GOSSIP_SELECT_STE "Yes elder. Tell me more of the book."
class npc_saikkal_the_elder : public CreatureScript
{
public:
npc_saikkal_the_elder() : CreatureScript("npc_saikkal_the_elder") { }
bool OnGossipSelect(Player* pPlayer, Creature* pCreature, uint32 /*uiSender*/, uint32 uiAction)
{
pPlayer->PlayerTalkClass->ClearMenus();
switch (uiAction)
{
case GOSSIP_ACTION_INFO_DEF+1:
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_STE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2);
pPlayer->SEND_GOSSIP_MENU(10795, pCreature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+2:
pPlayer->TalkedToCreature(pCreature->GetEntry(), pCreature->GetGUID());
pPlayer->SEND_GOSSIP_MENU(10796, pCreature->GetGUID());
break;
}
return true;
}
bool OnGossipHello(Player* pPlayer, Creature* pCreature)
{
if (pPlayer->GetQuestStatus(10980) == QUEST_STATUS_INCOMPLETE)
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HELLO_STE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
pPlayer->SEND_GOSSIP_MENU(10794, pCreature->GetGUID());
return true;
}
};
/*######
## go_legion_obelisk
######*/
class go_legion_obelisk : public GameObjectScript
{
public:
go_legion_obelisk() : GameObjectScript("go_legion_obelisk") { }
bool OnGossipHello(Player* pPlayer, GameObject* pGo)
{
if (pPlayer->GetQuestStatus(10821) == QUEST_STATUS_INCOMPLETE)
{
switch(pGo->GetEntry())
{
case LEGION_OBELISK_ONE:
obelisk_one = true;
break;
case LEGION_OBELISK_TWO:
obelisk_two = true;
break;
case LEGION_OBELISK_THREE:
obelisk_three = true;
break;
case LEGION_OBELISK_FOUR:
obelisk_four = true;
break;
case LEGION_OBELISK_FIVE:
obelisk_five = true;
break;
}
if (obelisk_one == true && obelisk_two == true && obelisk_three == true && obelisk_four == true && obelisk_five == true)
{
pGo->SummonCreature(19963, 2943.40f, 4778.20f, 284.49f, 0.94f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 120000);
//reset global var
obelisk_one = false;
obelisk_two = false;
obelisk_three = false;
obelisk_four = false;
obelisk_five = false;
}
}
return true;
}
};
/*######
## npc_bloodmaul_brutebane
######*/
enum eBloodmaul
{
NPC_OGRE_BRUTE = 19995,
NPC_QUEST_CREDIT = 21241,
GO_KEG = 184315,
QUEST_GETTING_THE_BLADESPIRE_TANKED = 10512,
QUEST_BLADESPIRE_KEGGER = 10545,
};
class npc_bloodmaul_brutebane : public CreatureScript
{
public:
npc_bloodmaul_brutebane() : CreatureScript("npc_bloodmaul_brutebane") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_bloodmaul_brutebaneAI(creature);
}
struct npc_bloodmaul_brutebaneAI : public ScriptedAI
{
npc_bloodmaul_brutebaneAI(Creature* creature) : ScriptedAI(creature)
{
if(Creature* Ogre = me->FindNearestCreature(NPC_OGRE_BRUTE, 50, true))
{
Ogre->SetReactState(REACT_DEFENSIVE);
Ogre->GetMotionMaster()->MovePoint(1, me->GetPositionX()-1, me->GetPositionY()+1, me->GetPositionZ());
}
}
uint64 OgreGUID;
void Reset()
{
OgreGUID = 0;
}
void UpdateAI(const uint32 /*uiDiff*/) {}
};
};
/*######
## npc_ogre_brute
######*/
class npc_ogre_brute : public CreatureScript
{
public:
npc_ogre_brute() : CreatureScript("npc_ogre_brute") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_ogre_bruteAI(creature);
}
struct npc_ogre_bruteAI : public ScriptedAI
{
npc_ogre_bruteAI(Creature* creature) : ScriptedAI(creature) {}
uint64 PlayerGUID;
void Reset()
{
PlayerGUID = 0;
}
void MoveInLineOfSight(Unit* who)
{
if (!who || (!who->isAlive())) return;
if (me->IsWithinDistInMap(who, 50.0f))
{
if (who->GetTypeId() == TYPEID_PLAYER)
if (who->ToPlayer()->GetQuestStatus(QUEST_GETTING_THE_BLADESPIRE_TANKED || QUEST_BLADESPIRE_KEGGER) == QUEST_STATUS_INCOMPLETE)
PlayerGUID = who->GetGUID();
}
}
void MovementInform(uint32 /*type*/, uint32 id)
{
Player* pPlayer = Unit::GetPlayer(*me, PlayerGUID);
if (id == 1)
{
GameObject* Keg = me->FindNearestGameObject(GO_KEG, 20);
if (Keg)
Keg->Delete();
me->HandleEmoteCommand(7);
me->SetReactState(REACT_AGGRESSIVE);
me->GetMotionMaster()->MoveTargetedHome();
Creature* Credit = me->FindNearestCreature(NPC_QUEST_CREDIT, 50, true);
if (pPlayer && Credit)
pPlayer->KilledMonster(Credit->GetCreatureInfo(), Credit->GetGUID());
}
}
void UpdateAI(const uint32 /*diff*/)
{
if (!UpdateVictim())
return;
DoMeleeAttackIfReady();
}
};
};
/*######
## AddSC
######*/
void AddSC_blades_edge_mountains()
{
new mobs_bladespire_ogre();
new mobs_nether_drake();
new npc_daranelle();
new npc_overseer_nuaar();
new npc_saikkal_the_elder();
new go_legion_obelisk();
new npc_bloodmaul_brutebane();
new npc_ogre_brute();
}
| SeTM/MythCore | src/server/scripts/Outland/blades_edge_mountains.cpp | C++ | gpl-2.0 | 16,406 |
package geeksforgeeks.divide.conquer;
/*
* http://chuansongme.com/n/122759
*
* This is actually dutch national flag problem. See SortList.java.
*
* Check the above link for another solution
*/
public class Sort123 {
} | sindhujapr/ms_prep | companies/geeksforgeeks/divide/conquer/Sort123.java | Java | gpl-2.0 | 227 |
/*
* Copyright (C) 2011-2021 Project SkyFire <https://www.projectskyfire.org/>
* Copyright (C) 2008-2021 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2021 MaNGOS <https://www.getmangos.eu/>
* Copyright (C) 2006-2014 ScriptDev2 <https://github.com/scriptdev2/scriptdev2/>
*
* 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/>.
*/
/* ScriptData
SDName: Instance_Razorfen_Kraul
SD%Complete:
SDComment:
SDCategory: Razorfen Kraul
EndScriptData */
#include "ScriptMgr.h"
#include "InstanceScript.h"
#include "razorfen_kraul.h"
#include "Player.h"
#define WARD_KEEPERS_NR 2
class instance_razorfen_kraul : public InstanceMapScript
{
public:
instance_razorfen_kraul() : InstanceMapScript("instance_razorfen_kraul", 47) { }
InstanceScript* GetInstanceScript(InstanceMap* map) const OVERRIDE
{
return new instance_razorfen_kraul_InstanceMapScript(map);
}
struct instance_razorfen_kraul_InstanceMapScript : public InstanceScript
{
instance_razorfen_kraul_InstanceMapScript(Map* map) : InstanceScript(map) { }
uint64 DoorWardGUID;
int WardKeeperDeath;
void Initialize() OVERRIDE
{
WardKeeperDeath = 0;
DoorWardGUID = 0;
}
Player* GetPlayerInMap()
{
Map::PlayerList const& players = instance->GetPlayers();
if (!players.isEmpty())
{
for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
{
if (Player* player = itr->GetSource())
return player;
}
}
SF_LOG_DEBUG("scripts", "Instance Razorfen Kraul: GetPlayerInMap, but PlayerList is empty!");
return NULL;
}
void OnGameObjectCreate(GameObject* go) OVERRIDE
{
switch (go->GetEntry())
{
case 21099: DoorWardGUID = go->GetGUID(); break;
case 20920: go->SetUInt32Value(GAMEOBJECT_FIELD_FACTION_TEMPLATE, 0); break; // big fat fugly hack
}
}
void Update(uint32 /*diff*/) OVERRIDE
{
if (WardKeeperDeath == WARD_KEEPERS_NR)
if (GameObject* go = instance->GetGameObject(DoorWardGUID))
{
go->SetUInt32Value(GAMEOBJECT_FIELD_FLAGS, 33);
go->SetGoState(GOState::GO_STATE_ACTIVE);
}
}
void SetData(uint32 type, uint32 /*data*/) OVERRIDE
{
switch (type)
{
case EVENT_WARD_KEEPER: WardKeeperDeath++; break;
}
}
};
};
void AddSC_instance_razorfen_kraul()
{
new instance_razorfen_kraul();
}
| ProjectSkyfire/SkyFire.548 | src/server/scripts/Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp | C++ | gpl-2.0 | 3,367 |
/**
* @author Stefan Brandle
* @author Jonathan Geisler
* @date September, 2014
*
*/
#ifndef PLAYERV2_CPP // Double inclusion protection
#define PLAYERV2_CPP
#include <iostream>
#include "PlayerV2.h"
/**
* @brief Constructor: initializes any game-long data structures.
*
* The player should reinitialize any inter-round data structures that will be used
* for the entire game.
* I.e., any intra-round learning data structures should be initialized in the here,
* while inter-round data structures need to be initialized in newRound().
*/
PlayerV2::PlayerV2( int boardSize ) {
// Set boardsize
this->boardSize = boardSize;
}
#endif
| BoringCode/BattleshipAI | PlayerV2.cpp | C++ | gpl-2.0 | 658 |
<?php
/*
*---------------------------------------------------------
*
* CartET - Open Source Shopping Cart Software
* http://www.cartet.org
*
*---------------------------------------------------------
*/
define('MODULE_PAYMENT_PLATON_TEXT_TITLE', 'Platon.ua');
define('MODULE_PAYMENT_PLATON_TEXT_DESCRIPTION', 'Platon: Система электронных платежей.');
define('MODULE_PAYMENT_PLATON_STATUS_TITLE', 'Разрешить модуль Platon.ua');
define('MODULE_PAYMENT_PLATON_STATUS_DESC', '');
define('MODULE_PAYMENT_PLATON_ALLOWED_TITLE', 'Разрешённые страны');
define('MODULE_PAYMENT_PLATON_ALLOWED_DESC', 'Укажите коды стран, для которых будет доступен данный модуль (например RU,DE (оставьте поле пустым, если хотите что б модуль был доступен покупателям из любых стран))');
define('MODULE_PAYMENT_PLATON_KEY_TITLE', 'Ключ');
define('MODULE_PAYMENT_PLATON_KEY_DESC', 'Ключ');
define('MODULE_PAYMENT_PLATON_PASSWORD_TITLE', 'Пароль');
define('MODULE_PAYMENT_PLATON_PASSWORD_DESC', 'Пароль');
define('MODULE_PAYMENT_PLATON_SORT_ORDER_TITLE', 'Порядок сортировки');
define('MODULE_PAYMENT_PLATON_SORT_ORDER_DESC', 'Порядок сортировки модуля.');
define('MODULE_PAYMENT_PLATON_ORDER_STATUS_TITLE', 'Статус оплаченного заказа');
define('MODULE_PAYMENT_PLATON_ORDER_STATUS_DESC', 'Статус, устанавливаемый заказу после успешной оплаты');
?> | OSC-CMS/Shopping-Cart | modules/payment/platon/ru.php | PHP | gpl-2.0 | 1,645 |
// La generación de código T4 está habilitada para el modelo 'C:\Proyectos SVN\PRESTLAN\Models\PrestlanModel.edmx'.
// Para habilitar la generación de código heredada, cambie el valor de la propiedad del diseñador 'Estrategia de generación de código'
// por 'ObjectContext heredado'. Esta propiedad está disponible en la ventana Propiedades cuando se abre
// el modelo en el diseñador.
// Si no se ha generado ninguna clase de contexto y de entidad, puede que haya creado un modelo vacío pero
// no haya elegido todavía la versión de Entity Framework que se va a usar. Para generar una clase de contexto y clases de entidad
// para el modelo, abra el modelo en el diseñador, haga clic con el botón secundario en la superficie del diseñador y
// seleccione 'Actualizar modelo desde base de datos...', 'Generar base de datos desde modelo...' o 'Agregar elemento de generación
// de código...'. | alfre/Prestlan | Models/PrestlanModel.Designer.cs | C# | gpl-2.0 | 914 |
<?php
// No direct access
defined('_JEXEC') or die;
jimport('joomla.application.component.view');
class PropertyViewAgent extends JView
{
protected $form;
protected $item;
protected $state;
public function display($tpl = null)
{
// Initialiase variables.
$this->form = $this->get('Form');
$this->item = $this->get('Item');
$this->state = $this->get('State');
// Check for errors.
if (count($errors = $this->get('Errors'))) {
JError::raiseError(500, implode("\n", $errors));
return false;
}
$this->addToolbar();
parent::display($tpl);
}
protected function addToolbar()
{
JRequest::setVar('hidemainmenu', true);
$user = JFactory::getUser();
$isNew = ($this->item->id == 0);
$checkedOut = !($this->item->checked_out == 0 || $this->item->checked_out == $user->get('id'));
//$canDo = PropertyHelper::getActions($this->state->get('filter.category_id'));
$canDo = PropertyMenuHelper::getActions();
JToolBarHelper::title($isNew ? JText::_('Add Agent') : JText::_('Edit Agent'), 'banners.png');
// If not checked out, can save the item.
if (!$checkedOut && ($canDo->get('core.edit')||$canDo->get('core.create'))) {
JToolBarHelper::apply('agent.apply', 'JTOOLBAR_APPLY');
JToolBarHelper::save('agent.save', 'JTOOLBAR_SAVE');
}
if (!$checkedOut && $canDo->get('core.create')) {
JToolBarHelper::custom('agent.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false);
}
// If an existing item, can save to a copy.
if (!$isNew && $canDo->get('core.create')) {
JToolBarHelper::custom('agent.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false);
}
if (empty($this->item->id))
JToolBarHelper::cancel('agent.cancel','JTOOLBAR_CANCEL');
else
JToolBarHelper::cancel('agent.cancel', 'JTOOLBAR_CLOSE');
JToolBarHelper::divider();
JToolBarHelper::help('Agent');
}
}
| djoudi/cambodian-property-today | administrator/components/com_property/views/agent/view.html.php | PHP | gpl-2.0 | 2,164 |
package com.savanto.correspondencechess;
import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
/**
* Extension of the View class to allow easy creation and manipulation
* of views containing chess pieces.
*/
public class PieceView extends View
{
public PieceView(Context context)
{
super(context);
}
/**
* Produces graphic chess PieceView from given Piece.
* @param context
* @param resid - the resource id of the Drawable to use for this PieceView.
* @param size - the size to make the graphical PieceView.
* @param coords - rank and file Coordinates of the piece on the board.
*/
public PieceView(Context context, int resid, final int size, final Coordinates coords)
{
super(context);
// Set background to Drawable
setBackgroundResource(resid);
// Set position
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(size, size);
lp.leftMargin = coords.x * size;
lp.topMargin = coords.y * size;
setLayoutParams(lp);
// OnTouchListener listens for user interaction with the PieceView
setOnTouchListener(new OnTouchListener()
{
// Initial position of the PieceView, prior to move.
private int leftMargin, topMargin;
@Override
public boolean onTouch(View view, MotionEvent event)
{
// Get the PieceView being touched, and its LayoutParams for position updating.
PieceView pieceView = (PieceView) view;
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) pieceView.getLayoutParams();
// Which touch event is occuring
switch (event.getAction())
{
// The touch has just started
case MotionEvent.ACTION_DOWN:
// PieceView has been touched. Bring it
// in front of all other views.
pieceView.bringToFront();
// Get the PieceView's parent and ask it to redraw itself.
RelativeLayout parent = (RelativeLayout) pieceView.getParent();
parent.requestLayout();
parent.invalidate();
// TODO
// Record PieceView's initial coordinates
leftMargin = lp.leftMargin;
topMargin = lp.topMargin;
break;
// The touch event continues
case MotionEvent.ACTION_MOVE:
// The PieceView is being moved. Update
// its raw coordinates.
lp.leftMargin = (int) event.getRawX() - size / 2;
lp.topMargin = (int) event.getRawY() - size * 2;
pieceView.setLayoutParams(lp);
break;
// The touch event ends
case MotionEvent.ACTION_UP:
// The PieceView is released. Calculate its
// final position and set it down squarely.
// TODO check for legality, captures, special moves (en passant, castle, promotion)
if (false)
{
lp.leftMargin = leftMargin;
lp.topMargin = topMargin;
}
else
{
// TODO record completed moves, allow step-by-step undo
lp.leftMargin = (int) event.getRawX() / size * size;
lp.topMargin = ((int) event.getRawY() / size - 1) * size;
}
pieceView.setLayoutParams(lp);
break;
}
return true;
}
});
}
}
| savanto/CorrespondenceChess-Android | src/com/savanto/correspondencechess/PieceView.java | Java | gpl-2.0 | 3,118 |
/**
*
*/
package fr.hervedarritchon.soe.soebackend.exception;
/**
* @author Hervé Darritchon (@hervDarritchon)
*
*/
public class CannotCreateUserException extends Exception {
public CannotCreateUserException(final String message) {
super(message);
}
/**
*
*/
private static final long serialVersionUID = -1655114199335112310L;
}
| herveDarritchon/soebackend | src/main/java/fr/hervedarritchon/soe/soebackend/exception/CannotCreateUserException.java | Java | gpl-2.0 | 349 |
#include "skewnessfeature.h"
using Romeo::Model::Core::Feature::SkewnessFeature;
using Romeo::Model::Core::Feature::StandardDeviationFeature;
using Romeo::Model::Core::Feature::FirstOrderFeature;
using Romeo::Model::Core::InternalData;
using Romeo::Model::Core::InternalData2D;
using Romeo::Model::Core::InternalData3D;
using Romeo::Model::Core::Feature::MeanFeature;
using Romeo::Model::Core::RGBImage2D;
using Romeo::Model::Core::RGBImage3D;
SkewnessFeature::SkewnessFeature(int idFeat) : FirstOrderFeature(Utils::FEATURE_SKEWNESS, idFeat){
}
SkewnessFeature::SkewnessFeature(const QStringList& parameters, int idFeat)
: FirstOrderFeature(Utils::FEATURE_SKEWNESS, parameters, idFeat)
{
}
InternalData2D* SkewnessFeature::singleChannelEXecution2D(InternalData2D* channel)
{
InternalData2D::ImageType::Pointer image = channel->getImage();
MeanFeature meanFeature(getParameters());
InternalData2D::ImageType::Pointer meanImg = meanFeature.singleChannelEXecution2D(channel)->getImage();
StandardDeviationFeature stdDeviation(getParameters());
InternalData2D::ImageType::Pointer stdImg = stdDeviation.singleChannelEXecution2D(channel)->getImage();
InternalData2D* output = new InternalData2D(channel->getXSize(), channel->getYSize());
InternalData2D::ImageType::Pointer outputImg = output->getImage();
InternalData2D::NeighborhoodIteratorInternalType::RadiusType radius;
radius.Fill(getWindowSize()/2);
InternalData2D::NeighborhoodIteratorInternalType it(radius, image, image->GetRequestedRegion());
InternalData2D::RegionIteratorInternalType outIt(outputImg, outputImg->GetRequestedRegion());
InternalData2D::RegionIteratorInternalType meanIt(meanImg, meanImg->GetRequestedRegion());
InternalData2D::RegionIteratorInternalType stdIt(stdImg, stdImg->GetRequestedRegion());
int size = pow(getWindowSize(),2.0);
for(it.GoToBegin(), outIt.GoToBegin(), meanIt.GoToBegin(), stdIt.GoToBegin();
!it.IsAtEnd(); ++it, ++outIt, ++meanIt,++stdIt)
{
// skewness
float sum3 = 0;
for(int i=0; i<size; ++i){
float meanValue = meanIt.Value();
float x = it.GetPixel(i) - meanValue;
float y = pow(x,3.0);
sum3 += y;
}
float stdValue = stdIt.Value();
float val3 = sum3 / size;
float stdValueAllaTerza = pow(stdValue,3.0);
outIt.Set(val3/stdValueAllaTerza);
}
//delete channel;
return output;
}
InternalData3D* SkewnessFeature::singleChannelEXecution3D(InternalData3D* channel)
{
InternalData3D::ImageType::Pointer image = channel->getImage();
MeanFeature meanFeature(getParameters());
InternalData3D::ImageType::Pointer meanImg = meanFeature.singleChannelEXecution3D(channel)->getImage();
StandardDeviationFeature stdDeviation(getParameters());
InternalData3D::ImageType::Pointer stdImg = stdDeviation.singleChannelEXecution3D(channel)->getImage();
InternalData3D* output = new InternalData3D(channel->getXSize(), channel->getYSize(), channel->getZSize());
InternalData3D::ImageType::Pointer outputImg = output->getImage();
InternalData3D::NeighborhoodIteratorInternalType::RadiusType radius;
radius.Fill(getWindowSize()/2);
InternalData3D::NeighborhoodIteratorInternalType it(radius, image, image->GetRequestedRegion());
InternalData3D::RegionIteratorInternalType outIt(outputImg, outputImg->GetRequestedRegion());
InternalData3D::RegionIteratorInternalType meanIt(meanImg, meanImg->GetRequestedRegion());
InternalData3D::RegionIteratorInternalType stdIt(stdImg, stdImg->GetRequestedRegion());
int size = pow(getWindowSize(),3.0);
for(it.GoToBegin(), outIt.GoToBegin(), meanIt.GoToBegin(), stdIt.GoToBegin();
!it.IsAtEnd(); ++it, ++outIt, ++meanIt,++stdIt)
{
// skewness
float sum3 = 0;
for(int i=0; i<size; ++i){
float meanValue = meanIt.Value();
float x = it.GetPixel(i) - meanValue;
float y = pow(x,3.0);
sum3 += y;
}
float stdValue = stdIt.Value();
float val3 = sum3 / size;
float stdValueAllaTerza = pow(stdValue,3.0);
outIt.Set(val3/stdValueAllaTerza);
}
//delete channel;
return output;
}
SkewnessFeature::~SkewnessFeature()
{
}
| NicolaMagnabosco/Romeo | RomeoCode/model/core/feature/skewnessfeature.cpp | C++ | gpl-2.0 | 4,479 |
#include <iostream>
#include <ctime>
#include <QString>
#include <QInputDialog>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "solution.hpp"
MainWindow::MainWindow(QWidget* parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
results = new ResultsModel();
ui->resultsView->setModel(results);
ui->resultsView->verticalHeader()->hide();
}
MainWindow::~MainWindow()
{
delete ui;
delete results;
}
void MainWindow::on_actionRun_test_Solution_triggered()
{
// std::cout << "0\t60\t3600\t3600000\t143412" << std::endl;
// std::cout << Solution::TimeToString(0) << std::endl;
// std::cout << Solution::TimeToString(3600) << std::endl;
// std::cout << Solution::TimeToString(3600000) << std::endl;
// std::cout << Solution::TimeToString(143412) << std::endl;
}
void MainWindow::on_actionRun_test_ResultsModel_triggered()
{
Solution s(time(NULL), time(NULL) + 12454, "asdasd", "");
results->addSolution(s);
s.setStart(s.getEnd() + 1000);
s.setEnd(s.getStart() + 10000);
results->addSolution(s);
results->addSolution(Solution(time(NULL) + 1400, time(NULL) + 5000));
results->addSolution(Solution(time(NULL) + 1700, time(NULL) + 8500));
results->addSolution(Solution(time(NULL) + 5000, time(NULL) + 10544));
}
void MainWindow::on_actionAdd_time_triggered()
{
QString t = QInputDialog::getText(NULL, "ASD", "asd");
long int tm = atoi(t.toStdString().c_str());
results->addSolution(Solution(time(NULL) - tm, time(NULL)));
}
| trombipeti/qbtimer | mainwindow.cpp | C++ | gpl-2.0 | 1,568 |
package com.aifeng.ws.wx;
import java.util.Map;
/**
* Created by pro on 17-4-17.
*/
public class RequestBody {
private String touser;
private String msgtype;
private int agentid;
private Map<String,Object> text;
private int safe;
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
public String getMsgtype() {
return msgtype;
}
public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}
public int getAgentid() {
return agentid;
}
public void setAgentid(int agentid) {
this.agentid = agentid;
}
public Map<String, Object> getText() {
return text;
}
public void setText(Map<String, Object> text) {
this.text = text;
}
public int getSafe() {
return safe;
}
public void setSafe(int safe) {
this.safe = safe;
}
}
| dunyuling/cxh | src/main/java/com/aifeng/ws/wx/RequestBody.java | Java | gpl-2.0 | 974 |
/*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui.Cells;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.R;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.Switch;
public class NotificationsCheckCell extends FrameLayout {
private TextView textView;
private TextView valueTextView;
@SuppressWarnings("FieldCanBeLocal")
private ImageView moveImageView;
private Switch checkBox;
private boolean needDivider;
private boolean drawLine = true;
private boolean isMultiline;
private int currentHeight;
public NotificationsCheckCell(Context context) {
this(context, 21, 70, false);
}
public NotificationsCheckCell(Context context, int padding, int height, boolean reorder) {
super(context);
setWillNotDraw(false);
currentHeight = height;
if (reorder) {
moveImageView = new ImageView(context);
moveImageView.setFocusable(false);
moveImageView.setScaleType(ImageView.ScaleType.CENTER);
moveImageView.setImageResource(R.drawable.poll_reorder);
moveImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteGrayIcon), PorterDuff.Mode.MULTIPLY));
addView(moveImageView, LayoutHelper.createFrame(48, 48, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, 6, 0, 6, 0));
}
textView = new TextView(context);
textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
textView.setLines(1);
textView.setMaxLines(1);
textView.setSingleLine(true);
textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
textView.setEllipsize(TextUtils.TruncateAt.END);
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 80 : (reorder ? 64 : 23), 13 + (currentHeight - 70) / 2, LocaleController.isRTL ? (reorder ? 64 : 23) : 80, 0));
valueTextView = new TextView(context);
valueTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2));
valueTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
valueTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
valueTextView.setLines(1);
valueTextView.setMaxLines(1);
valueTextView.setSingleLine(true);
valueTextView.setPadding(0, 0, 0, 0);
valueTextView.setEllipsize(TextUtils.TruncateAt.END);
addView(valueTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 80 : (reorder ? 64 : 23), 38 + (currentHeight - 70) / 2, LocaleController.isRTL ? (reorder ? 64 : 23) : 80, 0));
checkBox = new Switch(context);
checkBox.setColors(Theme.key_switchTrack, Theme.key_switchTrackChecked, Theme.key_windowBackgroundWhite, Theme.key_windowBackgroundWhite);
addView(checkBox, LayoutHelper.createFrame(37, 40, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.CENTER_VERTICAL, 21, 0, 21, 0));
checkBox.setFocusable(true);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (isMultiline) {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
} else {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(currentHeight), MeasureSpec.EXACTLY));
}
}
public void setTextAndValueAndCheck(String text, CharSequence value, boolean checked, boolean divider) {
setTextAndValueAndCheck(text, value, checked, 0, false, divider);
}
public void setTextAndValueAndCheck(String text, CharSequence value, boolean checked, int iconType, boolean divider) {
setTextAndValueAndCheck(text, value, checked, iconType, false, divider);
}
public void setTextAndValueAndCheck(String text, CharSequence value, boolean checked, int iconType, boolean multiline, boolean divider) {
textView.setText(text);
valueTextView.setText(value);
checkBox.setChecked(checked, iconType, false);
valueTextView.setVisibility(VISIBLE);
needDivider = divider;
isMultiline = multiline;
if (multiline) {
valueTextView.setLines(0);
valueTextView.setMaxLines(0);
valueTextView.setSingleLine(false);
valueTextView.setEllipsize(null);
valueTextView.setPadding(0, 0, 0, AndroidUtilities.dp(14));
} else {
valueTextView.setLines(1);
valueTextView.setMaxLines(1);
valueTextView.setSingleLine(true);
valueTextView.setEllipsize(TextUtils.TruncateAt.END);
valueTextView.setPadding(0, 0, 0, 0);
}
checkBox.setContentDescription(text);
}
public void setDrawLine(boolean value) {
drawLine = value;
}
public void setChecked(boolean checked) {
checkBox.setChecked(checked, true);
}
public void setChecked(boolean checked, int iconType) {
checkBox.setChecked(checked, iconType, true);
}
public boolean isChecked() {
return checkBox.isChecked();
}
@Override
protected void onDraw(Canvas canvas) {
if (needDivider) {
canvas.drawLine(LocaleController.isRTL ? 0 : AndroidUtilities.dp(20), getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? AndroidUtilities.dp(20) : 0), getMeasuredHeight() - 1, Theme.dividerPaint);
}
if (drawLine) {
int x = LocaleController.isRTL ? AndroidUtilities.dp(76) : getMeasuredWidth() - AndroidUtilities.dp(76) - 1;
int y = (getMeasuredHeight() - AndroidUtilities.dp(22)) / 2;
canvas.drawRect(x, y, x + 2, y + AndroidUtilities.dp(22), Theme.dividerPaint);
}
}
}
| CzBiX/Telegram | TMessagesProj/src/main/java/org/telegram/ui/Cells/NotificationsCheckCell.java | Java | gpl-2.0 | 7,049 |
jQuery(document).ready( function($) {
$('#bp-forum-notifier-toggle-subscription').live('click', function(e) {
e.preventDefault();
var subscribe_or_unsubscribe = $(this).data('action');
var nonce = $(this).data('nonce');
var group_id = $(this).data('group_id');
$.ajax({
type: "POST",
url: ajaxurl,
data: {
action: 'bp_forum_notifier_toggle_subscription',
nonce: nonce,
group_id: group_id,
subscribe_or_unsubscribe: subscribe_or_unsubscribe,
},
success: function(response) {
if ( response[0] != '-' ) {
$('#bp-forum-notifier-wrapper').html(response);
}
}
},"JSON");
});
// since this plugin handles the mailsubscriptions, lets remove the checkbox from the form.
$('#bbp_topic_subscription').remove();
$("label[for='bbp_topic_subscription']").remove();
}); | klandestino/bp-forum-notifier | js/bp-forum-notifier.js | JavaScript | gpl-2.0 | 821 |
// Copyright 2015 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "VideoCommon/VertexLoaderARM64.h"
#include "Common/CommonTypes.h"
#include "VideoCommon/DataReader.h"
#include "VideoCommon/VertexLoaderManager.h"
using namespace Arm64Gen;
constexpr ARM64Reg src_reg = X0;
constexpr ARM64Reg dst_reg = X1;
constexpr ARM64Reg count_reg = W2;
constexpr ARM64Reg skipped_reg = W17;
constexpr ARM64Reg scratch1_reg = W16;
constexpr ARM64Reg scratch2_reg = W15;
constexpr ARM64Reg scratch3_reg = W14;
constexpr ARM64Reg saved_count = W12;
constexpr ARM64Reg stride_reg = X11;
constexpr ARM64Reg arraybase_reg = X10;
constexpr ARM64Reg scale_reg = X9;
alignas(16) static const float scale_factors[] = {
1.0 / (1ULL << 0), 1.0 / (1ULL << 1), 1.0 / (1ULL << 2), 1.0 / (1ULL << 3),
1.0 / (1ULL << 4), 1.0 / (1ULL << 5), 1.0 / (1ULL << 6), 1.0 / (1ULL << 7),
1.0 / (1ULL << 8), 1.0 / (1ULL << 9), 1.0 / (1ULL << 10), 1.0 / (1ULL << 11),
1.0 / (1ULL << 12), 1.0 / (1ULL << 13), 1.0 / (1ULL << 14), 1.0 / (1ULL << 15),
1.0 / (1ULL << 16), 1.0 / (1ULL << 17), 1.0 / (1ULL << 18), 1.0 / (1ULL << 19),
1.0 / (1ULL << 20), 1.0 / (1ULL << 21), 1.0 / (1ULL << 22), 1.0 / (1ULL << 23),
1.0 / (1ULL << 24), 1.0 / (1ULL << 25), 1.0 / (1ULL << 26), 1.0 / (1ULL << 27),
1.0 / (1ULL << 28), 1.0 / (1ULL << 29), 1.0 / (1ULL << 30), 1.0 / (1ULL << 31),
};
VertexLoaderARM64::VertexLoaderARM64(const TVtxDesc& vtx_desc, const VAT& vtx_att)
: VertexLoaderBase(vtx_desc, vtx_att), m_float_emit(this)
{
if (!IsInitialized())
return;
AllocCodeSpace(4096);
ClearCodeSpace();
GenerateVertexLoader();
WriteProtect();
}
void VertexLoaderARM64::GetVertexAddr(int array, u64 attribute, ARM64Reg reg)
{
if (attribute & MASK_INDEXED)
{
if (attribute == INDEX8)
{
if (m_src_ofs < 4096)
{
LDRB(IndexType::Unsigned, scratch1_reg, src_reg, m_src_ofs);
}
else
{
ADD(reg, src_reg, m_src_ofs);
LDRB(IndexType::Unsigned, scratch1_reg, reg, 0);
}
m_src_ofs += 1;
}
else
{
if (m_src_ofs < 256)
{
LDURH(scratch1_reg, src_reg, m_src_ofs);
}
else if (m_src_ofs <= 8190 && !(m_src_ofs & 1))
{
LDRH(IndexType::Unsigned, scratch1_reg, src_reg, m_src_ofs);
}
else
{
ADD(reg, src_reg, m_src_ofs);
LDRH(IndexType::Unsigned, scratch1_reg, reg, 0);
}
m_src_ofs += 2;
REV16(scratch1_reg, scratch1_reg);
}
if (array == ARRAY_POSITION)
{
EOR(scratch2_reg, scratch1_reg, 0, attribute == INDEX8 ? 7 : 15); // 0xFF : 0xFFFF
m_skip_vertex = CBZ(scratch2_reg);
}
LDR(IndexType::Unsigned, scratch2_reg, stride_reg, array * 4);
MUL(scratch1_reg, scratch1_reg, scratch2_reg);
LDR(IndexType::Unsigned, EncodeRegTo64(scratch2_reg), arraybase_reg, array * 8);
ADD(EncodeRegTo64(reg), EncodeRegTo64(scratch1_reg), EncodeRegTo64(scratch2_reg));
}
else
ADD(reg, src_reg, m_src_ofs);
}
s32 VertexLoaderARM64::GetAddressImm(int array, u64 attribute, Arm64Gen::ARM64Reg reg, u32 align)
{
if (attribute & MASK_INDEXED || (m_src_ofs > 255 && (m_src_ofs & (align - 1))))
GetVertexAddr(array, attribute, reg);
else
return m_src_ofs;
return -1;
}
int VertexLoaderARM64::ReadVertex(u64 attribute, int format, int count_in, int count_out,
bool dequantize, u8 scaling_exponent,
AttributeFormat* native_format, s32 offset)
{
ARM64Reg coords = count_in == 3 ? Q31 : D31;
ARM64Reg scale = count_in == 3 ? Q30 : D30;
int elem_size = 1 << (format / 2);
int load_bytes = elem_size * count_in;
int load_size =
load_bytes == 1 ? 1 : load_bytes <= 2 ? 2 : load_bytes <= 4 ? 4 : load_bytes <= 8 ? 8 : 16;
load_size <<= 3;
elem_size <<= 3;
if (offset == -1)
{
if (count_in == 1)
m_float_emit.LDR(elem_size, IndexType::Unsigned, coords, EncodeRegTo64(scratch1_reg), 0);
else
m_float_emit.LD1(elem_size, 1, coords, EncodeRegTo64(scratch1_reg));
}
else if (offset & (load_size - 1)) // Not aligned - unscaled
{
m_float_emit.LDUR(load_size, coords, src_reg, offset);
}
else
{
m_float_emit.LDR(load_size, IndexType::Unsigned, coords, src_reg, offset);
}
if (format != FORMAT_FLOAT)
{
// Extend and convert to float
switch (format)
{
case FORMAT_UBYTE:
m_float_emit.UXTL(8, EncodeRegToDouble(coords), EncodeRegToDouble(coords));
m_float_emit.UXTL(16, EncodeRegToDouble(coords), EncodeRegToDouble(coords));
break;
case FORMAT_BYTE:
m_float_emit.SXTL(8, EncodeRegToDouble(coords), EncodeRegToDouble(coords));
m_float_emit.SXTL(16, EncodeRegToDouble(coords), EncodeRegToDouble(coords));
break;
case FORMAT_USHORT:
m_float_emit.REV16(8, EncodeRegToDouble(coords), EncodeRegToDouble(coords));
m_float_emit.UXTL(16, EncodeRegToDouble(coords), EncodeRegToDouble(coords));
break;
case FORMAT_SHORT:
m_float_emit.REV16(8, EncodeRegToDouble(coords), EncodeRegToDouble(coords));
m_float_emit.SXTL(16, EncodeRegToDouble(coords), EncodeRegToDouble(coords));
break;
}
m_float_emit.SCVTF(32, coords, coords);
if (dequantize && scaling_exponent)
{
m_float_emit.LDR(32, IndexType::Unsigned, scale, scale_reg, scaling_exponent * 4);
m_float_emit.FMUL(32, coords, coords, scale, 0);
}
}
else
{
m_float_emit.REV32(8, coords, coords);
}
const u32 write_size = count_out == 3 ? 128 : count_out * 32;
const u32 mask = count_out == 3 ? 0xF : count_out == 2 ? 0x7 : 0x3;
if (m_dst_ofs < 256)
{
m_float_emit.STUR(write_size, coords, dst_reg, m_dst_ofs);
}
else if (!(m_dst_ofs & mask))
{
m_float_emit.STR(write_size, IndexType::Unsigned, coords, dst_reg, m_dst_ofs);
}
else
{
ADD(EncodeRegTo64(scratch2_reg), dst_reg, m_dst_ofs);
m_float_emit.ST1(32, 1, coords, EncodeRegTo64(scratch2_reg));
}
// Z-Freeze
if (native_format == &m_native_vtx_decl.position)
{
CMP(count_reg, 3);
FixupBranch dont_store = B(CC_GT);
MOVP2R(EncodeRegTo64(scratch2_reg), VertexLoaderManager::position_cache);
ADD(EncodeRegTo64(scratch1_reg), EncodeRegTo64(scratch2_reg), EncodeRegTo64(count_reg),
ArithOption(EncodeRegTo64(count_reg), ShiftType::LSL, 4));
m_float_emit.STUR(write_size, coords, EncodeRegTo64(scratch1_reg), -16);
SetJumpTarget(dont_store);
}
native_format->components = count_out;
native_format->enable = true;
native_format->offset = m_dst_ofs;
native_format->type = VAR_FLOAT;
native_format->integer = false;
m_dst_ofs += sizeof(float) * count_out;
if (attribute == DIRECT)
m_src_ofs += load_bytes;
return load_bytes;
}
void VertexLoaderARM64::ReadColor(u64 attribute, int format, s32 offset)
{
int load_bytes = 0;
switch (format)
{
case FORMAT_24B_888:
case FORMAT_32B_888x:
case FORMAT_32B_8888:
if (offset == -1)
LDR(IndexType::Unsigned, scratch2_reg, EncodeRegTo64(scratch1_reg), 0);
else if (offset & 3) // Not aligned - unscaled
LDUR(scratch2_reg, src_reg, offset);
else
LDR(IndexType::Unsigned, scratch2_reg, src_reg, offset);
if (format != FORMAT_32B_8888)
ORRI2R(scratch2_reg, scratch2_reg, 0xFF000000);
STR(IndexType::Unsigned, scratch2_reg, dst_reg, m_dst_ofs);
load_bytes = 3 + (format != FORMAT_24B_888);
break;
case FORMAT_16B_565:
// RRRRRGGG GGGBBBBB
// AAAAAAAA BBBBBBBB GGGGGGGG RRRRRRRR
if (offset == -1)
LDRH(IndexType::Unsigned, scratch3_reg, EncodeRegTo64(scratch1_reg), 0);
else if (offset & 1) // Not aligned - unscaled
LDURH(scratch3_reg, src_reg, offset);
else
LDRH(IndexType::Unsigned, scratch3_reg, src_reg, offset);
REV16(scratch3_reg, scratch3_reg);
// B
AND(scratch2_reg, scratch3_reg, 32, 4);
ORR(scratch2_reg, WSP, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 3));
ORR(scratch2_reg, scratch2_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSR, 5));
ORR(scratch1_reg, WSP, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 16));
// G
UBFM(scratch2_reg, scratch3_reg, 5, 10);
ORR(scratch2_reg, WSP, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 2));
ORR(scratch2_reg, scratch2_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSR, 6));
ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 8));
// R
UBFM(scratch2_reg, scratch3_reg, 11, 15);
ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 3));
ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSR, 2));
// A
ORRI2R(scratch1_reg, scratch1_reg, 0xFF000000);
STR(IndexType::Unsigned, scratch1_reg, dst_reg, m_dst_ofs);
load_bytes = 2;
break;
case FORMAT_16B_4444:
// BBBBAAAA RRRRGGGG
// REV16 - RRRRGGGG BBBBAAAA
// AAAAAAAA BBBBBBBB GGGGGGGG RRRRRRRR
if (offset == -1)
LDRH(IndexType::Unsigned, scratch3_reg, EncodeRegTo64(scratch1_reg), 0);
else if (offset & 1) // Not aligned - unscaled
LDURH(scratch3_reg, src_reg, offset);
else
LDRH(IndexType::Unsigned, scratch3_reg, src_reg, offset);
// R
UBFM(scratch1_reg, scratch3_reg, 4, 7);
// G
AND(scratch2_reg, scratch3_reg, 32, 3);
ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 8));
// B
UBFM(scratch2_reg, scratch3_reg, 12, 15);
ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 16));
// A
UBFM(scratch2_reg, scratch3_reg, 8, 11);
ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 24));
// Final duplication
ORR(scratch1_reg, scratch1_reg, scratch1_reg, ArithOption(scratch1_reg, ShiftType::LSL, 4));
STR(IndexType::Unsigned, scratch1_reg, dst_reg, m_dst_ofs);
load_bytes = 2;
break;
case FORMAT_24B_6666:
// RRRRRRGG GGGGBBBB BBAAAAAA
// AAAAAAAA BBBBBBBB GGGGGGGG RRRRRRRR
if (offset == -1)
{
LDUR(scratch3_reg, EncodeRegTo64(scratch1_reg), -1);
}
else
{
offset -= 1;
if (offset & 3) // Not aligned - unscaled
LDUR(scratch3_reg, src_reg, offset);
else
LDR(IndexType::Unsigned, scratch3_reg, src_reg, offset);
}
REV32(scratch3_reg, scratch3_reg);
// A
UBFM(scratch2_reg, scratch3_reg, 0, 5);
ORR(scratch2_reg, WSP, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 2));
ORR(scratch2_reg, scratch2_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSR, 6));
ORR(scratch1_reg, WSP, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 24));
// B
UBFM(scratch2_reg, scratch3_reg, 6, 11);
ORR(scratch2_reg, WSP, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 2));
ORR(scratch2_reg, scratch2_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSR, 6));
ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 16));
// G
UBFM(scratch2_reg, scratch3_reg, 12, 17);
ORR(scratch2_reg, WSP, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 2));
ORR(scratch2_reg, scratch2_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSR, 6));
ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 8));
// R
UBFM(scratch2_reg, scratch3_reg, 18, 23);
ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 2));
ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSR, 4));
STR(IndexType::Unsigned, scratch1_reg, dst_reg, m_dst_ofs);
load_bytes = 3;
break;
}
if (attribute == DIRECT)
m_src_ofs += load_bytes;
}
void VertexLoaderARM64::GenerateVertexLoader()
{
// R0 - Source pointer
// R1 - Destination pointer
// R2 - Count
// R30 - LR
//
// R0 return how many
//
// Registers we don't have to worry about saving
// R9-R17 are caller saved temporaries
// R18 is a temporary or platform specific register(iOS)
//
// VFP registers
// We can touch all except v8-v15
// If we need to use those, we need to retain the lower 64bits(!) of the register
const u64 tc[8] = {
m_VtxDesc.Tex0Coord, m_VtxDesc.Tex1Coord, m_VtxDesc.Tex2Coord, m_VtxDesc.Tex3Coord,
m_VtxDesc.Tex4Coord, m_VtxDesc.Tex5Coord, m_VtxDesc.Tex6Coord, m_VtxDesc.Tex7Coord,
};
bool has_tc = false;
bool has_tc_scale = false;
for (int i = 0; i < 8; i++)
{
has_tc |= tc[i] != 0;
has_tc_scale |= !!m_VtxAttr.texCoord[i].Frac;
}
bool need_scale =
(m_VtxAttr.ByteDequant && m_VtxAttr.PosFrac) || (has_tc && has_tc_scale) || m_VtxDesc.Normal;
AlignCode16();
if (m_VtxDesc.Position & MASK_INDEXED)
MOV(skipped_reg, WZR);
MOV(saved_count, count_reg);
MOVP2R(stride_reg, g_main_cp_state.array_strides);
MOVP2R(arraybase_reg, VertexLoaderManager::cached_arraybases);
if (need_scale)
MOVP2R(scale_reg, scale_factors);
const u8* loop_start = GetCodePtr();
if (m_VtxDesc.PosMatIdx)
{
LDRB(IndexType::Unsigned, scratch1_reg, src_reg, m_src_ofs);
AND(scratch1_reg, scratch1_reg, 0, 5);
STR(IndexType::Unsigned, scratch1_reg, dst_reg, m_dst_ofs);
// Z-Freeze
CMP(count_reg, 3);
FixupBranch dont_store = B(CC_GT);
MOVP2R(EncodeRegTo64(scratch2_reg), VertexLoaderManager::position_matrix_index);
STR(IndexType::Unsigned, scratch1_reg, EncodeRegTo64(scratch2_reg), 0);
SetJumpTarget(dont_store);
m_native_components |= VB_HAS_POSMTXIDX;
m_native_vtx_decl.posmtx.components = 4;
m_native_vtx_decl.posmtx.enable = true;
m_native_vtx_decl.posmtx.offset = m_dst_ofs;
m_native_vtx_decl.posmtx.type = VAR_UNSIGNED_BYTE;
m_native_vtx_decl.posmtx.integer = true;
m_src_ofs += sizeof(u8);
m_dst_ofs += sizeof(u32);
}
u32 texmatidx_ofs[8];
const u64 tm[8] = {
m_VtxDesc.Tex0MatIdx, m_VtxDesc.Tex1MatIdx, m_VtxDesc.Tex2MatIdx, m_VtxDesc.Tex3MatIdx,
m_VtxDesc.Tex4MatIdx, m_VtxDesc.Tex5MatIdx, m_VtxDesc.Tex6MatIdx, m_VtxDesc.Tex7MatIdx,
};
for (int i = 0; i < 8; i++)
{
if (tm[i])
texmatidx_ofs[i] = m_src_ofs++;
}
// Position
{
int elem_size = 1 << (m_VtxAttr.PosFormat / 2);
int load_bytes = elem_size * (m_VtxAttr.PosElements + 2);
int load_size =
load_bytes == 1 ? 1 : load_bytes <= 2 ? 2 : load_bytes <= 4 ? 4 : load_bytes <= 8 ? 8 : 16;
load_size <<= 3;
s32 offset =
GetAddressImm(ARRAY_POSITION, m_VtxDesc.Position, EncodeRegTo64(scratch1_reg), load_size);
int pos_elements = m_VtxAttr.PosElements + 2;
ReadVertex(m_VtxDesc.Position, m_VtxAttr.PosFormat, pos_elements, pos_elements,
m_VtxAttr.ByteDequant, m_VtxAttr.PosFrac, &m_native_vtx_decl.position, offset);
}
if (m_VtxDesc.Normal)
{
static const u8 map[8] = {7, 6, 15, 14};
u8 scaling_exponent = map[m_VtxAttr.NormalFormat];
s32 offset = -1;
for (int i = 0; i < (m_VtxAttr.NormalElements ? 3 : 1); i++)
{
if (!i || m_VtxAttr.NormalIndex3)
{
int elem_size = 1 << (m_VtxAttr.NormalFormat / 2);
int load_bytes = elem_size * 3;
int load_size = load_bytes == 1 ?
1 :
load_bytes <= 2 ? 2 : load_bytes <= 4 ? 4 : load_bytes <= 8 ? 8 : 16;
offset = GetAddressImm(ARRAY_NORMAL, m_VtxDesc.Normal, EncodeRegTo64(scratch1_reg),
load_size << 3);
if (offset == -1)
ADD(EncodeRegTo64(scratch1_reg), EncodeRegTo64(scratch1_reg), i * elem_size * 3);
else
offset += i * elem_size * 3;
}
int bytes_read = ReadVertex(m_VtxDesc.Normal, m_VtxAttr.NormalFormat, 3, 3, true,
scaling_exponent, &m_native_vtx_decl.normals[i], offset);
if (offset == -1)
ADD(EncodeRegTo64(scratch1_reg), EncodeRegTo64(scratch1_reg), bytes_read);
else
offset += bytes_read;
}
m_native_components |= VB_HAS_NRM0;
if (m_VtxAttr.NormalElements)
m_native_components |= VB_HAS_NRM1 | VB_HAS_NRM2;
}
const u64 col[2] = {m_VtxDesc.Color0, m_VtxDesc.Color1};
for (int i = 0; i < 2; i++)
{
m_native_vtx_decl.colors[i].components = 4;
m_native_vtx_decl.colors[i].type = VAR_UNSIGNED_BYTE;
m_native_vtx_decl.colors[i].integer = false;
if (col[i])
{
u32 align = 4;
if (m_VtxAttr.color[i].Comp == FORMAT_16B_565 || m_VtxAttr.color[i].Comp == FORMAT_16B_4444)
align = 2;
s32 offset = GetAddressImm(ARRAY_COLOR + i, col[i], EncodeRegTo64(scratch1_reg), align);
ReadColor(col[i], m_VtxAttr.color[i].Comp, offset);
m_native_components |= VB_HAS_COL0 << i;
m_native_vtx_decl.colors[i].components = 4;
m_native_vtx_decl.colors[i].enable = true;
m_native_vtx_decl.colors[i].offset = m_dst_ofs;
m_native_vtx_decl.colors[i].type = VAR_UNSIGNED_BYTE;
m_native_vtx_decl.colors[i].integer = false;
m_dst_ofs += 4;
}
}
for (int i = 0; i < 8; i++)
{
m_native_vtx_decl.texcoords[i].offset = m_dst_ofs;
m_native_vtx_decl.texcoords[i].type = VAR_FLOAT;
m_native_vtx_decl.texcoords[i].integer = false;
int elements = m_VtxAttr.texCoord[i].Elements + 1;
if (tc[i])
{
m_native_components |= VB_HAS_UV0 << i;
int elem_size = 1 << (m_VtxAttr.texCoord[i].Format / 2);
int load_bytes = elem_size * (elements + 2);
int load_size = load_bytes == 1 ?
1 :
load_bytes <= 2 ? 2 : load_bytes <= 4 ? 4 : load_bytes <= 8 ? 8 : 16;
load_size <<= 3;
s32 offset =
GetAddressImm(ARRAY_TEXCOORD0 + i, tc[i], EncodeRegTo64(scratch1_reg), load_size);
u8 scaling_exponent = m_VtxAttr.texCoord[i].Frac;
ReadVertex(tc[i], m_VtxAttr.texCoord[i].Format, elements, tm[i] ? 2 : elements,
m_VtxAttr.ByteDequant, scaling_exponent, &m_native_vtx_decl.texcoords[i], offset);
}
if (tm[i])
{
m_native_components |= VB_HAS_TEXMTXIDX0 << i;
m_native_vtx_decl.texcoords[i].components = 3;
m_native_vtx_decl.texcoords[i].enable = true;
m_native_vtx_decl.texcoords[i].type = VAR_FLOAT;
m_native_vtx_decl.texcoords[i].integer = false;
LDRB(IndexType::Unsigned, scratch2_reg, src_reg, texmatidx_ofs[i]);
m_float_emit.UCVTF(S31, scratch2_reg);
if (tc[i])
{
m_float_emit.STR(32, IndexType::Unsigned, D31, dst_reg, m_dst_ofs);
m_dst_ofs += sizeof(float);
}
else
{
m_native_vtx_decl.texcoords[i].offset = m_dst_ofs;
if (m_dst_ofs < 256)
{
STUR(SP, dst_reg, m_dst_ofs);
}
else if (!(m_dst_ofs & 7))
{
// If m_dst_ofs isn't 8byte aligned we can't store an 8byte zero register
// So store two 4byte zero registers
// The destination is always 4byte aligned
STR(IndexType::Unsigned, WSP, dst_reg, m_dst_ofs);
STR(IndexType::Unsigned, WSP, dst_reg, m_dst_ofs + 4);
}
else
{
STR(IndexType::Unsigned, SP, dst_reg, m_dst_ofs);
}
m_float_emit.STR(32, IndexType::Unsigned, D31, dst_reg, m_dst_ofs + 8);
m_dst_ofs += sizeof(float) * 3;
}
}
}
// Prepare for the next vertex.
ADD(dst_reg, dst_reg, m_dst_ofs);
const u8* cont = GetCodePtr();
ADD(src_reg, src_reg, m_src_ofs);
SUB(count_reg, count_reg, 1);
CBNZ(count_reg, loop_start);
if (m_VtxDesc.Position & MASK_INDEXED)
{
SUB(W0, saved_count, skipped_reg);
RET(X30);
SetJumpTarget(m_skip_vertex);
ADD(skipped_reg, skipped_reg, 1);
B(cont);
}
else
{
MOV(W0, saved_count);
RET(X30);
}
FlushIcache();
m_VertexSize = m_src_ofs;
m_native_vtx_decl.stride = m_dst_ofs;
}
int VertexLoaderARM64::RunVertices(DataReader src, DataReader dst, int count)
{
m_numLoadedVertices += count;
return ((int (*)(u8 * src, u8 * dst, int count)) region)(src.GetPointer(), dst.GetPointer(),
count);
}
| Ebola16/dolphin | Source/Core/VideoCommon/VertexLoaderARM64.cpp | C++ | gpl-2.0 | 20,467 |
<?php
/**
*
* Template for the shopping cart
*
* @package VirtueMart
* @subpackage Cart
* @author Max Milbers
*
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*/
?>
<?php
echo "<h3>".JText::_('COM_VIRTUEMART_CART_ORDERDONE_THANK_YOU')."</h3>";
echo $this->html;
?> | kenbabu/emproj | components/com_virtuemart/views/cart/tmpl/order_done.php | PHP | gpl-2.0 | 699 |
//stlÌṩÁËÁ½ÖÖÈÝÆ÷£ºÐòÁУ¨vector¡¢list¡¢deque£©ºÍ¹ØÁªÈÝÆ÷£¨map¡¢mutilmap¡¢set¡¢mutilset£©
//¶ø stackºÍqueueÊÇ×÷Ϊ»ù±¾ÈÝÆ÷µÄÊÊÅäÆ÷¡£
////-----------------------------------Ðò ÁÐ--------------------------------
////-----------------------------------ÊÊÅäÆ÷--------------------------------
//ÊÊÅäÆ÷ÌṩµÄÊÂÔÀ´ÈÝÆ÷µÄÒ»¸öÊÜÏ޵ĽçÃæ£¬ÌرðÊÇÈÝÆ÷²»Ìṩµü´úÆ÷
//±ÈÈ磺stackĬÈÏʹÓÃÒ»¸ödeque±£´æ×Ô¼ºµÄÔªËØ£¬µ«Ò²¿ÉÒÔ²ÉÓÃÈκÎÌṩÁËback()¡¢push_back()ºÍpop_back()µÄÐòÁÐ
// ÀýÈ磺 stack<int> s1; //ÓÃdeque<int>±£´æÊý¾Ý
// stack<int,vector<int> > s2;////ÓÃvector<int>±£´æÊý¾Ý
// queueĬÈÏʹÓÃÒ»¸ödeque±£´æ×Ô¼ºµÄÔªËØ£¬µ«Ò²¿ÉÒÔ²ÉÓÃÈκÎÌṩÁËfront()¡¢back()¡¢push_back()ºÍpop_front()µÄÐòÁÐ
// µ«vectorûÓÐÌṩpop_front()²Ù×÷£¬ËùÒÔvector²»ÄÜÓÃ×÷queueµÄ»ù´¡ÈÝÆ÷
// priority_queue ĬÈÏʹÓÃÒ»¸övector±£´æ×Ô¼ºµÄÔªËØ£¬µ«Ò²¿ÉÒÔ²ÉÓÃÈκÎÌṩÁËfront()¡¢push_back()ºÍpop_back()µÄÐòÁÐ
// Æä±¾ÉíÒ²ÊÇÒ»ÖÖ¶ÓÁУ¬ÆäÖеÄÿһ¸öÔªËØ±»¸ø¶¨ÁËÒ»¸öÓÅÏȼ¶£¬ÒÔ´ËÀ´¿ØÖÆÔªËص½´ïtop£¨£©µÄ˳Ðò
////---------------------------------¹ØÁªÈÝÆ÷--------------------------------
//set, multiset, map, multimap ÊÇÒ»ÖÖ·ÇÏßÐÔµÄÊ÷½á¹¹£¬¾ßÌåµÄ˵²ÉÓõÄÊÇÒ»ÖֱȽϸßЧµÄÌØÊâµÄƽºâ¼ìË÷¶þ²æÊ÷¡ª¡ª ºìºÚÊ÷½á¹¹
//set ÓֳƼ¯ºÏ£¬Êµ¼ÊÉϾÍÊÇÒ»×éÔªËØµÄ¼¯ºÏ£¬µ«ÆäÖÐËù°üº¬µÄÔªËØµÄÖµÊÇΨһµÄ£¬ÇÒÊǰ´Ò»¶¨Ë³ÐòÅÅÁе쬼¯ºÏÖеÄÿ¸öÔªËØ±»³Æ×÷
// ¼¯ºÏÖеÄʵÀý¡£ÒòΪÆäÄÚ²¿ÊÇͨ¹ýÁ´±íµÄ·½Ê½À´×éÖ¯£¬ËùÒÔÔÚ²åÈëµÄʱºò±Èvector ¿ì£¬µ«ÔÚ²éÕÒºÍĩβÌí¼ÓÉϱÈvectorÂý¡£
//multiset ÊǶàÖØ¼¯ºÏ£¬ÆäʵÏÖ·½Ê½ºÍset ÊÇÏàËÆµÄ£¬Ö»ÊÇËü²»ÒªÇ󼯺ÏÖеÄÔªËØÊÇΨһµÄ£¬Ò²¾ÍÊÇ˵¼¯ºÏÖеÄͬһ¸öÔªËØ¿ÉÒÔ³öÏÖ¶à´Î¡£
//map ÌṩһÖÖ¡°¼ü- Öµ¡±¹ØÏµµÄÒ»¶ÔÒ»µÄÊý¾Ý´æ´¢ÄÜÁ¦¡£Æä¡°¼ü¡±ÔÚÈÝÆ÷Öв»¿ÉÖØ¸´£¬ÇÒ°´Ò»¶¨Ë³ÐòÅÅÁУ¨ÆäʵÎÒÃÇ¿ÉÒÔ½«set Ò²¿´³ÉÊÇ
// Ò»ÖÖ¼ü- Öµ¹ØÏµµÄ´æ´¢£¬Ö»ÊÇËüÖ»ÓмüûÓÐÖµ¡£ËüÊÇmap µÄÒ»ÖÖÌØÊâÐÎʽ£©¡£ÓÉÓÚÆäÊǰ´Á´±íµÄ·½Ê½´æ´¢£¬ËüÒ²¼Ì³ÐÁËÁ´±íµÄÓÅȱµã¡£
//multimap ºÍmap µÄÔÀí»ù±¾ÏàËÆ£¬ËüÔÊÐí¡°¼ü¡±ÔÚÈÝÆ÷ÖпÉÒÔ²»Î¨Ò»¡£
//vector¡¢list¡¢dequeÑ¡Ôñ¹æÔò
// 1¡¢Èç¹ûÐèÒª¸ßЧµÄËæ¼´´æÈ¡£¬¶ø²»ÔÚºõ²åÈëºÍɾ³ýµÄЧÂÊ£¬Ê¹ÓÃvector
// 2¡¢Èç¹ûÐèÒª´óÁ¿µÄ²åÈëºÍɾ³ý£¬¶ø²»¹ØÐÄËæ¼´´æÈ¡£¬ÔòӦʹÓÃlist
// 3¡¢Èç¹ûÐèÒªËæ¼´´æÈ¡£¬¶øÇÒ¹ØÐÄÁ½¶ËÊý¾ÝµÄ²åÈëºÍɾ³ý£¬ÔòӦʹÓÃdeque¡£
//map¡¢mutilmap¡¢set¡¢mutilsetÑ¡Ôñ¹æÔò
//stackÄ£°åÀàµÄ¶¨ÒåÔÚ<stack>Í·ÎļþÖÐ
// stackÄ£°åÀàÐèÒªÁ½¸öÄ£°å²ÎÊý£¬Ò»¸öÊÇÔªËØÀàÐÍ£¬Ò»¸öÈÝÆ÷ÀàÐÍ£¬µ«Ö»ÓÐÔªËØÀàÐÍÊDZØÒªµÄ£¬ÔÚ²»Ö¸¶¨ÈÝÆ÷ÀàÐÍʱ£¬Ä¬ÈϵÄÈÝÆ÷ÀàÐÍΪdeque¡£
//
// ¶¨Òåstack¶ÔÏóµÄʾÀý´úÂëÈçÏ£º
// stack<int> s1;
// stack<string> s2;
//
//stackµÄ»ù±¾²Ù×÷ÓУº
// ÈëÕ»£¬ÈçÀý£ºs.push(x);
// ³öÕ»£¬ÈçÀý£ºs.pop();×¢Ò⣬³öÕ»²Ù×÷Ö»ÊÇɾ³ýÕ»¶¥ÔªËØ£¬²¢²»·µ»Ø¸ÃÔªËØ¡£
// ·ÃÎÊÕ»¶¥£¬ÈçÀý£ºs.top()
// ÅжÏÕ»¿Õ£¬ÈçÀý£ºs.empty()£¬µ±Õ»¿Õʱ£¬·µ»Øtrue¡£
// ·ÃÎÊÕ»ÖеÄÔªËØ¸öÊý£¬ÈçÀý£ºs.size()
#include <iostream>
#include <ostream>
#include <stack>
#include <vector>
#include <algorithm>
#include <iterator>
#include <numeric>
using namespace std;
int main ()
{
vector<int> v1(5), v2(5), v3(5);
iota(v1.begin(), v1.end(), 0);
iota(v2.begin(), v2.end(), 5);
iota(v3.begin(), v3.end(), 10);
stack<vector<int> > s;
s.push(v1);
s.push(v2);
s.push(v3);
cout << "size of stack 's' = "
<< s.size() << endl;
if ( v3 != v2 )
s.pop();
cout << "size of stack 's' = "
<< s.size() << endl;
vector<int> top = s.top();
cout << "Contents of v2 : ";
copy(top.begin(),top.end(), ostream_iterator<int>(cout," "));
cout << endl;
while ( !s.empty() )
s.pop();
cout << "Stack 's' is " << (s.empty() ? "" : "not ") << "empty" << endl;
system("pause");
return 0;
} | lizhenghn123/CppLanguagePrograms | STL/stackDemo/stackDemo.cpp | C++ | gpl-2.0 | 3,385 |
package io.github.yannici.bedwars.Game;
import io.github.yannici.bedwars.Main;
import io.github.yannici.bedwars.Utils;
import io.github.yannici.bedwars.Events.BedwarsOpenTeamSelectionEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.potion.PotionEffect;
public class PlayerStorage {
private Player player = null;
private ItemStack[] inventory = null;
private ItemStack[] armor = null;
private float xp = 0.0F;
private Collection<PotionEffect> effects = null;
private GameMode mode = null;
private Location left = null;
private int level = 0;
private String displayName = null;
private String listName = null;
private int foodLevel = 0;
public PlayerStorage(Player p) {
super();
this.player = p;
}
public void store() {
this.inventory = this.player.getInventory().getContents();
this.armor = this.player.getInventory().getArmorContents();
this.xp = Float.valueOf(this.player.getExp());
this.effects = this.player.getActivePotionEffects();
this.mode = this.player.getGameMode();
this.left = this.player.getLocation();
this.level = this.player.getLevel();
this.listName = this.player.getPlayerListName();
this.displayName = this.player.getDisplayName();
this.foodLevel = this.player.getFoodLevel();
}
public void clean() {
PlayerInventory inv = this.player.getInventory();
inv.setArmorContents(new ItemStack[4]);
inv.setContents(new ItemStack[] {});
this.player.setAllowFlight(false);
this.player.setFlying(false);
this.player.setExp(0.0F);
this.player.setLevel(0);
this.player.setSneaking(false);
this.player.setSprinting(false);
this.player.setFoodLevel(20);
this.player.setMaxHealth(20.0D);
this.player.setHealth(20.0D);
this.player.setFireTicks(0);
this.player.setGameMode(GameMode.SURVIVAL);
boolean teamnameOnTab = Main.getInstance().getBooleanConfig("teamname-on-tab", true);
boolean overwriteNames = Main.getInstance().getBooleanConfig("overwrite-names", false);
if(overwriteNames) {
Game game = Main.getInstance().getGameManager().getGameOfPlayer(this.player);
if(game != null) {
Team team = game.getPlayerTeam(this.player);
if(team != null) {
this.player.setDisplayName(team.getChatColor() + ChatColor.stripColor(this.player.getName()));
} else {
this.player.setDisplayName(ChatColor.stripColor(this.player.getName()));
}
}
}
if(teamnameOnTab && Utils.isSupportingTitles()) {
Game game = Main.getInstance().getGameManager().getGameOfPlayer(this.player);
if(game != null) {
Team team = game.getPlayerTeam(this.player);
if(team != null) {
this.player.setPlayerListName(team.getChatColor() + team.getName() + ChatColor.WHITE
+ " | " + team.getChatColor() + ChatColor.stripColor(this.player.getDisplayName()));
} else {
this.player.setPlayerListName(ChatColor.stripColor(this.player.getDisplayName()));
}
}
}
if (this.player.isInsideVehicle()) {
this.player.leaveVehicle();
}
for (PotionEffect e : this.player.getActivePotionEffects()) {
this.player.removePotionEffect(e.getType());
}
this.player.updateInventory();
}
public void restore() {
this.player.getInventory().setContents(this.inventory);
this.player.getInventory().setArmorContents(this.armor);
this.player.setGameMode(this.mode);
if (this.mode == GameMode.CREATIVE) {
this.player.setAllowFlight(true);
}
this.player.addPotionEffects(this.effects);
this.player.setLevel(this.level);
this.player.setExp(this.xp);
this.player.setPlayerListName(this.listName);
this.player.setDisplayName(this.displayName);
this.player.setFoodLevel(this.foodLevel);
for (PotionEffect e : this.player.getActivePotionEffects()) {
this.player.removePotionEffect(e.getType());
}
this.player.addPotionEffects(this.effects);
this.player.updateInventory();
}
public Location getLeft() {
return this.left;
}
@SuppressWarnings("deprecation")
public void loadLobbyInventory(Game game) {
ItemMeta im = null;
// choose team only when autobalance is disabled
if(!game.isAutobalanceEnabled()) {
// Choose team (Wool)
ItemStack teamSelection = new ItemStack(Material.BED, 1);
im = teamSelection.getItemMeta();
im.setDisplayName(Main._l("lobby.chooseteam"));
teamSelection.setItemMeta(im);
this.player.getInventory().addItem(teamSelection);
}
// Leave Game (Slimeball)
ItemStack leaveGame = new ItemStack(Material.SLIME_BALL, 1);
im = leaveGame.getItemMeta();
im.setDisplayName(Main._l("lobby.leavegame"));
leaveGame.setItemMeta(im);
this.player.getInventory().setItem(8, leaveGame);
Team team = game.getPlayerTeam(this.player);
if(team != null) {
ItemStack chestplate = new ItemStack(Material.LEATHER_CHESTPLATE, 1);
LeatherArmorMeta meta = (LeatherArmorMeta) chestplate.getItemMeta();
meta.setDisplayName(team.getChatColor() + team.getDisplayName());
meta.setColor(team.getColor().getColor());
chestplate.setItemMeta(meta);
this.player.getInventory().setItem(7, chestplate);
team.equipPlayerWithLeather(this.player);
}
if (this.player.hasPermission("bw.setup") || this.player.isOp()
|| this.player.hasPermission("bw.vip.forcestart")) {
// Force start game (Diamond)
ItemStack startGame = new ItemStack(Material.DIAMOND, 1);
im = startGame.getItemMeta();
im.setDisplayName(Main._l("lobby.startgame"));
startGame.setItemMeta(im);
this.player.getInventory().addItem(startGame);
}
// lobby gamemode
GameMode mode = GameMode.SURVIVAL;
try {
mode = GameMode.getByValue(Main.getInstance().getIntConfig("lobby-gamemode", 0));
} catch(Exception ex) {
// not valid gamemode
}
if(mode == null) {
mode = GameMode.SURVIVAL;
}
this.player.setGameMode(mode);
this.player.updateInventory();
}
@SuppressWarnings("deprecation")
public void openTeamSelection(Game game) {
BedwarsOpenTeamSelectionEvent openEvent = new BedwarsOpenTeamSelectionEvent(
game, this.player);
Main.getInstance().getServer().getPluginManager().callEvent(openEvent);
if (openEvent.isCancelled()) {
return;
}
HashMap<String, Team> teams = game.getTeams();
int nom = (teams.size() % 9 == 0) ? 9 : (teams.size() % 9);
Inventory inv = Bukkit.createInventory(this.player,
teams.size() + (9 - nom),
Main._l("lobby.chooseteam"));
for (Team team : teams.values()) {
List<Player> players = team.getPlayers();
if (players.size() >= team.getMaxPlayers()) {
continue;
}
ItemStack is = new ItemStack(Material.WOOL, 1, team.getColor()
.getDyeColor().getData());
ItemMeta im = is.getItemMeta();
im.setDisplayName(team.getChatColor() + team.getName());
ArrayList<String> teamplayers = new ArrayList<>();
int teamPlayerSize = team.getPlayers().size();
int maxPlayers = team.getMaxPlayers();
String current = "0";
if (teamPlayerSize >= maxPlayers) {
current = ChatColor.RED + String.valueOf(teamPlayerSize);
} else {
current = ChatColor.YELLOW + String.valueOf(teamPlayerSize);
}
teamplayers.add(ChatColor.GRAY + "(" + current + ChatColor.GRAY
+ "/" + ChatColor.YELLOW + String.valueOf(maxPlayers)
+ ChatColor.GRAY + ")");
teamplayers.add(ChatColor.WHITE + "---------");
for (Player teamPlayer : players) {
teamplayers.add(team.getChatColor() + ChatColor.stripColor(teamPlayer.getDisplayName()));
}
im.setLore(teamplayers);
is.setItemMeta(im);
inv.addItem(is);
}
this.player.openInventory(inv);
}
}
| homedog21/bedwars-reloaded | src/io/github/yannici/bedwars/Game/PlayerStorage.java | Java | gpl-2.0 | 9,378 |
<?php
/* --------------------------------------------------------------
blacklist.php 2008-08-10 gambio
Gambio OHG
http://www.gambio.de
Copyright (c) 2008 Gambio OHG
Released under the GNU General Public License (Version 2)
[http://www.gnu.org/licenses/gpl-2.0.html]
--------------------------------------------------------------
$Id: blacklist.php 899 2005-04-29 02:40:57Z hhgag $
XTC-CC - Contribution for XT-Commerce http://www.xt-commerce.com
modified by http://www.netz-designer.de
Copyright (c) 2003 netz-designer
-----------------------------------------------------------------------------
based on:
$Id: blacklist.php.php,v 1.00
Copyright (c) 2003 BMC
http://www.mainframes.co.uk
Released under the GNU General Public License
------------------------------------------------------------------------------*/
define('HEADING_TITLE', 'Kreditkarten-Blackliste');
// BOF GM_MOD
define('HEADING_SUB_TITLE', 'Hilfsprogramme');
// EOF GM_MOD
define('TABLE_HEADING_BLACKLIST', 'Kreditkarten-Blackliste');
define('TABLE_HEADING_ACTION', 'Aktion');
define('TEXT_MARKED_ELEMENTS','Markiertes Element');
define('TEXT_HEADING_NEW_BLACKLIST_CARD', 'Neue Karte');
define('TEXT_HEADING_EDIT_BLACKLIST_CARD', 'Karte bearbeiten');
define('TEXT_HEADING_DELETE_BLACKLIST_CARD', 'Karte löschen');
define('TEXT_DISPLAY_NUMBER_OF_BLACKLIST_CARDS', 'Karten anzeigen');
define('TEXT_DATE_ADDED', 'Hinzugefügt am:');
define('TEXT_LAST_MODIFIED', 'Zuletzt geändert:');
define('TEXT_NEW_INTRO', 'Tragen Sie die Kreditkartennummer ein, die gesperrt werden soll.');
define('TEXT_EDIT_INTRO', 'Bitte führen Sie die notwendigen Änderungen durch.');
define('TEXT_BLACKLIST_CARD_NUMBER', 'Kartennummer:');
define('TEXT_DELETE_INTRO', 'Sind Sie sicher, dass Sie diese Karte löschen wollen?');
?>
| pobbes/gambio | lang/german/admin/blacklist.php | PHP | gpl-2.0 | 1,844 |
<?php
/**
* com_simplecalendar - a simple calendar component for Joomla
* Copyright (C) 2008-2009 Fabrizio Albonico
*
* 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/>.
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.view');
JHTML::stylesheet('simplecal_front.css','components/com_simplecalendar/assets/css/');
class SimpleCalendarViewCalendar extends JView {
function display($tmpl = null) {
global $option, $mainframe;
$document = & JFactory::getDocument();
$catid = '';
$options = '';
$user =& JFactory::getUser();
$categoryName = '';
$component = JComponentHelper::getComponent( 'com_simplecalendar' );
$params = '';
$config = SCOutput::config();
// ---
$menus =& JSite::getMenu();
$menu = $menus->getActive();
$params =& $mainframe->getParams();
$isPrint = false;
$isPdf = false;
$lists = array();
$pagination = '';
$lists['document'] =& JFactory::getDocument();
$lists['pathway'] =& $mainframe->getPathWay();
$menuitemid = JRequest::getInt( 'Itemid' );
$lists['search'] = $mainframe->getUserStateFromRequest( $option.'search', 'search', '', 'string' );
$lists['search'] = JString::strtolower( $lists['search'] );
$lists['mainframe'] = $mainframe;
$lists['categoryName'] = '';
$lists['isPrint'] = false;
$lists['isPdf'] = false;
// check if entries are available, else print a "no events available" line
$lists['hasEntries'] =& $this->get('Total');
// Check whether we're dealing with an iCal/vCal request
$vcal = JRequest::getBool('vcal');
if ($vcal) {
// $document->setMetaData('robots', 'noindex, nofollow');
$tmpl = 'vcal';
if ($lists['hasEntries'] > 0) {
$items =& $this->get('Data');
$this->assignRef('items', $items);
$this->assignRef('params', $params);
parent::display($tmpl);
}
}
$catidValue = JRequest::getString('catid');
$catid = explode(':', $catidValue);
if ( $catid[0] != 0 ) {
$lists['catid'] = $catid[0];
$lists['categoryName'] =& $this->get('CategoryName');
} else if ( $params->get('catid') != 0 ) {
$lists['catid'] = $params->get('catid');
$lists['categoryName'] =& $this->get('CategoryName');
} else {
$lists['catid'] = 0;
}
$lists['calendarTitle'] = '';
if ( is_object($menu) ) {
$menu_params = new JParameter( $menu->params );
if ( !$menu_params->get( 'page_title') ) {
$params->set('page_title', JText::_('Calendar'));
}
} else {
$params->set('page_title', JText::_('Calendar'));
}
if ( $params->get('page_title') != '' && $lists['categoryName'] != '' ){
$params->set('page_title', $params->get('page_title') . ' / ' . $lists['categoryName']);
}
// Check whether we are dealing with PDF or print version of the calendar
if (JRequest::getVar('format') == 'pdf') {
$lists['isPdf'] = TRUE;
}
if (JRequest::getBool('print')) {
$lists['isPrint'] = TRUE;
}
//TODO: add metadata from Joomla site
// $metadata = 'Calendar, SimpleCalendar, List';
// $lists['document']->setMetadata('keywords', $metadata );
//http://forum.joomla.org/viewtopic.php?p=1679517
@ini_set("pcre.backtrack_limit", -1);
$items =& $this->get('Data');
if ( $config->show_search_bar && !$lists['isPrint'] ) {
$pagination =& $this->get('Pagination');
}
//feed management
if ( $params->get('linkToRSS', '1') ) {
$link = 'index.php?view=calendar&format=feed';
$attribs = array('type' => 'application/rss+xml', 'title' => 'RSS 2.0');
$document->addHeadLink(JRoute::_($link.'&type=rss'), 'alternate', 'rel', $attribs);
$attribs = array('type' => 'application/atom+xml', 'title' => 'Atom 1.0');
$document->addHeadLink(JRoute::_($link.'&type=atom'), 'alternate', 'rel', $attribs);
}
$this->assignRef('items', $items);
$this->assignRef('params', $params);
$this->assignRef('config', $config);
$this->assignRef('lists', $lists);
$this->assignRef('user', $user);
$this->assignRef('pagination', $pagination);
$this->assignRef('document', $document);
parent::display($tmpl);
}
}
?> | mchalupar/Union-Leopoldschlag | tmp/install_50dda12248b2d/component/views/calendar/view.html.php | PHP | gpl-2.0 | 4,869 |
/*global require,__dirname*/
var connect = require('connect');
connect.createServer(
connect.static(__dirname)
).listen(8080); | kurthalex/BRGM-BdCavite-cesium | cesium/Build/server.js | JavaScript | gpl-2.0 | 127 |
class TreatmentAreas::PatientsController < ApplicationController
before_filter :authenticate_user!
before_filter :find_treatment_area
def index
@patients_table = PatientsTable.new
@patient_search = @patients_table.search(params)
end
def radiology
@patient = Patient.find(params[:id])
if dexis? || kodak?
app_config["dexis_paths"].each do |root_path|
path = [root_path, "passtodex", current_user.x_ray_station_id, ".dat"].join
@patient.export_to_dexis(path)
end
end
respond_to do |format|
format.html do
@patient.check_out(TreatmentArea.radiology)
redirect_to treatment_area_patient_procedures_path(TreatmentArea.radiology, @patient.id)
end
end
rescue => e
flash[:error] = e.message
redirect_to :action => :index
end
private
def find_treatment_area
@treatment_area = TreatmentArea.find(params[:treatment_area_id])
end
end
| mission-of-mercy/georgia | app/controllers/treatment_areas/patients_controller.rb | Ruby | gpl-2.0 | 945 |
# replaces the '%' symbol with '+', leaving the return values of actions usable for other things, such as type information,
# and leaving whitespace intact.
from dparser import Parser
# turn a tree of strings into a single string (slowly):
def stringify(s):
if not isinstance(s, str):
return ''.join(map(stringify, s))
return s
def d_add1(t, s):
"add : add '%' exp"
s[1] = '+ ' # replace the % with +
def d_add2(t, s):
"add : exp"
def d_exp(t):
'exp : "[0-9]+" '
# if the start action specifies the 's' argument, then parser
# will contain a member, s,
parser = Parser()
parsedmessage = parser.parse('1 % 2 % 3')
if stringify(parsedmessage.getStringLeft()) != '1 + 2 + 3':
print 'error'
| charlesDGY/coflo | coflo-0.0.4/third_party/d/python/tests/test6.py | Python | gpl-2.0 | 743 |
package pub.infoclass.pushservice;
public class ACK {
private int p = h_protocol_pusher.ACK;
private String UserID;
private String PushID;
public ACK(String userID, String pushID) {
super();
UserID = userID;
PushID = pushID;
}
public int getP() {
return p;
}
public void setP(int p) {
this.p = p;
}
public String getUserID() {
return UserID;
}
public void setUserID(String userID) {
UserID = userID;
}
public String getPushID() {
return PushID;
}
public void setPushID(String pushID) {
PushID = pushID;
}
}
| 282857484/LocationBaseServiceSocialNetworking | src/pub/infoclass/pushservice/ACK.java | Java | gpl-2.0 | 551 |
<?php
/*
*
* Ampoliros Application Server
*
* http://www.ampoliros.com
*
*
*
* Copyright (C) 2000-2004 Solarix
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
// $Id: DBLayer_mysql.php,v 1.7 2004-07-08 15:04:26 alex Exp $
package('com.solarix.ampoliros.db.drivers.mysql');
import('com.solarix.ampoliros.db.DBLayer');
import('carthag.db.DataAccessFactory');
/*!
@class dblayer_mysql
@abstract DbLayer for MySql.
*/
class DBLayer_mysql extends DBLayer {
public $layer = 'mysql';
public $fmtquote = "''";
public $fmttrue = 't';
public $fmtfalse = 'f';
//public $suppautoinc = true;
//public $suppblob = true;
private $lastquery = false;
public function dblayer_mysql($params) {
$this -> support['affrows'] = true;
$this -> support['transactions'] = false;
return $this -> dblayer($params);
}
function _CreateDB($params) {
$result = false;
if (!empty($params['dbname'])) {
$tmplink = @ mysql_connect($params['dbhost'], $params['dbuser'], $params['dbpass']);
if ($tmplink) {
if (mysql_query('CREATE DATABASE '.$params['dbname'], $tmplink))
$result = true;
else
$this -> mLastError = @ mysql_error($tmplink);
}
//@mysql_close( $tmplink );
}
return $result;
}
function _DropDB($params) {
$result = false;
if (!empty($params['dbname']))
$result = @ mysql_query('DROP DATABASE '.$params['dbname'], $this -> dbhandler);
return $result;
}
function _Connect() {
$result = @ mysql_connect($this -> dbhost, $this -> dbuser, $this -> dbpass);
if ($result != false) {
$this -> dbhandler = $result;
if (!@ mysql_select_db($this -> dbname, $this -> dbhandler))
$result = false;
}
return $result;
}
function _PConnect($params) {
$result = @ mysql_pconnect($this -> dbhost, $this -> dbuser, $this -> dbpass);
if ($result != false) {
$this -> dbhandler = $result;
if (!@ mysql_select_db($this -> dbname, $this -> dbhandler))
$result = false;
}
return $result;
}
function _Close() {
return true;
//return @mysql_close( $this->dbhandler );
}
function _Query($query) {
@ mysql_select_db($this -> dbname, $this -> dbhandler);
$this -> lastquery = @ mysql_query($query, $this -> dbhandler);
//if ( defined( 'DEBUG' ) and !$this->lastquery ) echo mysql_error();
if (@ mysql_error($this -> dbhandler)) {
import('com.solarix.ampoliros.io.log.Logger');
$this -> log = new Logger($this -> dblog);
$this -> log -> logevent('ampoliros.dblayer_mysql_library.dblayer_mysql_class._query', 'Error: '.@ mysql_error($this -> dbhandler), LOGGER_ERROR);
}
return $this -> lastquery;
}
function _AffectedRows($params) {
$result = false;
if ($this -> lastquery != false) {
$result = @ mysql_affected_rows($this -> dbhandler);
}
return $result;
}
function _DropTable($params) {
$result = false;
if (!empty($params['tablename']) and $this -> opened)
$result = $this -> _query('DROP TABLE '.$params['tablename']);
return $result;
}
function _AddColumn($params) {
$result = FALSE;
if (!empty($params['tablename']) and !empty($params['columnformat']) and $this -> opened)
$result = $this -> _query('ALTER TABLE '.$params['tablename'].' ADD COLUMN '.$params['columnformat']);
return $result;
}
function _RemoveColumn($params) {
$result = FALSE;
if (!empty($params['tablename']) and !empty($params['column']) and $this -> opened)
$result = $this -> _query('ALTER TABLE '.$params['tablename'].' DROP COLUMN '.$params['column']);
return $result;
}
function _CreateSeq($params) {
$result = false;
if (!empty($params['name']) and !empty($params['start']) and $this -> opened) {
$result = $this -> Execute('CREATE TABLE _sequence_'.$params['name'].' (sequence INT DEFAULT 0 NOT NULL AUTO_INCREMENT, PRIMARY KEY (sequence))');
if ($result and ($params['start'] > 0))
$this -> Execute('INSERT INTO _sequence_'.$params['name'].' (sequence) VALUES ('. ($params['start'] - 1).')');
}
return $result;
}
function _CreateSeqQuery($params) {
$result = false;
if (!empty($params['name']) and !empty($params['start'])) {
$query = 'CREATE TABLE _sequence_'.$params['name'].' (sequence INT DEFAULT 0 NOT NULL AUTO_INCREMENT, PRIMARY KEY (sequence));';
if ($params['start'] > 0)
$query.= 'INSERT INTO _sequence_'.$params['name'].' (sequence) VALUES ('. ($params['start'] - 1).');';
return $query;
}
return $result;
}
function _DropSeq($params) {
if (!empty($params['name']))
return $this -> _query('DROP TABLE _sequence_'.$params['name']);
else
return false;
}
function _DropSeqQuery($params) {
if (!empty($params['name']))
return 'DROP TABLE _sequence_'.$params['name'].';';
else
return false;
}
function _CurrSeqValue($name) {
if (!empty($name)) {
$result = $this -> _query('SELECT MAX(sequence) FROM _sequence_'.$name);
return @ mysql_result($result, 0, 0);
} else
return false;
}
function _CurrSeqValueQuery($name) {
$result = false;
if (!empty($name)) {
$result = 'SELECT MAX(sequence) FROM _sequence_'.$name.';';
}
return $result;
}
function _NextSeqValue($name) {
if (!empty($name)) {
if ($this -> _query('INSERT INTO _sequence_'.$name.' (sequence) VALUES (NULL)')) {
$value = intval(mysql_insert_id($this -> dbhandler));
$this -> _query('DELETE FROM _sequence_'.$name.' WHERE sequence<'.$value);
}
return $value;
} else
return false;
}
// ----------------------------------------------------
//
// ----------------------------------------------------
Function GetTextFieldTypeDeclaration($name, & $field) {
return (((IsSet($field['length']) and ($field['length'] <= 255)) ? "$name VARCHAR (".$field["length"].")" : "$name TEXT"). (IsSet($field["default"]) ? " DEFAULT '".$field["default"]."'" : ""). (IsSet($field["notnull"]) ? " NOT NULL" : ""));
}
Function GetTextFieldValue($value) {
return ("'".AddSlashes($value)."'");
}
Function GetDateFieldTypeDeclaration($name, & $field) {
return ($name." DATE". (IsSet($field["default"]) ? " DEFAULT '".$field["default"]."'" : ""). (IsSet($field["notnull"]) ? " NOT NULL" : ""));
}
Function GetTimeFieldTypeDeclaration($name, & $field) {
return ($name." TIME". (IsSet($field["default"]) ? " DEFAULT '".$field["default"]."'" : ""). (IsSet($field["notnull"]) ? " NOT NULL" : ""));
}
Function GetFloatFieldTypeDeclaration($name, & $field) {
return ("$name FLOAT8 ". (IsSet($field["default"]) ? " DEFAULT ".$this -> GetFloatFieldValue($field["default"]) : ""). (IsSet($field["notnull"]) ? " NOT NULL" : ""));
}
Function GetDecimalFieldTypeDeclaration($name, & $field) {
return ("$name DECIMAL ". (IsSet($field["length"]) ? " (".$field["length"].") " : ""). (IsSet($field["default"]) ? " DEFAULT ".$this -> GetDecimalFieldValue($field["default"]) : ""). (IsSet($field["notnull"]) ? " NOT NULL" : ""));
}
Function GetFloatFieldValue($value) {
return (!strcmp($value, "NULL") ? "NULL" : "$value");
}
Function GetDecimalFieldValue($value) {
return (!strcmp($value, "NULL") ? "NULL" : strval(intval($value * $this -> decimal_factor)));
}
}
?> | alexpagnoni/ampoliros | var/classes/com/solarix/ampoliros/db/drivers/mysql/DBLayer_mysql.php | PHP | gpl-2.0 | 7,888 |
/*
* This file is part of the KDE project
*
* Copyright (c) 2005 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 "kis_dropshadow_plugin.h"
#include <klocale.h>
#include <kiconloader.h>
#include <kcomponentdata.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kis_debug.h>
#include <kpluginfactory.h>
#include <kactioncollection.h>
#include "kis_view2.h"
#include "kis_types.h"
#include "kis_image.h"
#include "kis_paint_device.h"
#include "kis_layer.h"
#include "kis_statusbar.h"
#include "widgets/kis_progress_widget.h"
#include <KoColorSpace.h>
#include <KoProgressUpdater.h>
#include <KoUpdater.h>
#include "kis_dropshadow.h"
#include "dlg_dropshadow.h"
K_PLUGIN_FACTORY(KisDropshadowPluginFactory, registerPlugin<KisDropshadowPlugin>();)
K_EXPORT_PLUGIN(KisDropshadowPluginFactory("krita"))
KisDropshadowPlugin::KisDropshadowPlugin(QObject *parent, const QVariantList &)
: KParts::Plugin(parent)
{
if (parent->inherits("KisView2")) {
setXMLFile(KStandardDirs::locate("data", "kritaplugins/dropshadow.rc"), true);
m_view = (KisView2*) parent;
KAction *action = new KAction(i18n("Add Drop Shadow..."), this);
actionCollection()->addAction("dropshadow", action);
connect(action, SIGNAL(triggered()), this, SLOT(slotDropshadow()));
}
}
KisDropshadowPlugin::~KisDropshadowPlugin()
{
}
void KisDropshadowPlugin::slotDropshadow()
{
KisImageWSP image = m_view->image();
if (!image) return;
KisLayerSP layer = m_view->activeLayer();
if (!layer) return;
DlgDropshadow * dlgDropshadow = new DlgDropshadow(layer->colorSpace()->name(),
image->colorSpace()->name(),
m_view, "Dropshadow");
Q_CHECK_PTR(dlgDropshadow);
dlgDropshadow->setCaption(i18n("Drop Shadow"));
if (dlgDropshadow->exec() == QDialog::Accepted) {
KisDropshadow dropshadow(m_view);
KoProgressUpdater* updater = m_view->createProgressUpdater();
updater->start();
QPointer<KoUpdater> u = updater->startSubtask();
dropshadow.dropshadow(u,
dlgDropshadow->getXOffset(),
dlgDropshadow->getYOffset(),
dlgDropshadow->getBlurRadius(),
dlgDropshadow->getShadowColor(),
dlgDropshadow->getShadowOpacity(),
dlgDropshadow->allowResizingChecked());
updater->deleteLater();
}
delete dlgDropshadow;
}
#include "kis_dropshadow_plugin.moc"
| wyuka/calligra | krita/plugins/extensions/dropshadow/kis_dropshadow_plugin.cc | C++ | gpl-2.0 | 3,316 |
/*
* 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 cn.edu.hfut.dmic.webcollectorcluster.generator;
import cn.edu.hfut.dmic.webcollectorcluster.model.CrawlDatum;
import java.io.IOException;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.RecordReader;
/**
*
* @author hu
*/
public class RecordGenerator implements Generator{
public RecordGenerator(RecordReader<Text, CrawlDatum> reader) {
this.reader = reader;
}
RecordReader<Text, CrawlDatum> reader;
@Override
public CrawlDatum next() {
Text text=new Text();
CrawlDatum datum=new CrawlDatum();
boolean hasMore;
try {
hasMore = reader.next(text, datum);
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
if(hasMore)
return datum;
else
return null;
}
}
| CrawlScript/WebCollectorCluster-Dev | WebCollectorCluster/src/main/java/cn/edu/hfut/dmic/webcollectorcluster/generator/RecordGenerator.java | Java | gpl-2.0 | 1,060 |
/*
* NimBLERemoteDescriptor.cpp
*
* Created: on Jan 27 2020
* Author H2zero
*
* Originally:
*
* BLERemoteDescriptor.cpp
*
* Created on: Jul 8, 2017
* Author: kolban
*/
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED)
#include "nimconfig.h"
#if defined( CONFIG_BT_NIMBLE_ROLE_CENTRAL)
#include "NimBLERemoteDescriptor.h"
#include "NimBLEUtils.h"
#include "NimBLELog.h"
static const char* LOG_TAG = "NimBLERemoteDescriptor";
/**
* @brief Remote descriptor constructor.
* @param [in] pRemoteCharacteristic A pointer to the Characteristic that this belongs to.
* @param [in] dsc A pointer to the struct that contains the descriptor information.
*/
NimBLERemoteDescriptor::NimBLERemoteDescriptor(NimBLERemoteCharacteristic* pRemoteCharacteristic,
const struct ble_gatt_dsc *dsc)
{
NIMBLE_LOGD(LOG_TAG, ">> NimBLERemoteDescriptor()");
switch (dsc->uuid.u.type) {
case BLE_UUID_TYPE_16:
m_uuid = NimBLEUUID(dsc->uuid.u16.value);
break;
case BLE_UUID_TYPE_32:
m_uuid = NimBLEUUID(dsc->uuid.u32.value);
break;
case BLE_UUID_TYPE_128:
m_uuid = NimBLEUUID(const_cast<ble_uuid128_t*>(&dsc->uuid.u128));
break;
default:
break;
}
m_handle = dsc->handle;
m_pRemoteCharacteristic = pRemoteCharacteristic;
NIMBLE_LOGD(LOG_TAG, "<< NimBLERemoteDescriptor(): %s", m_uuid.toString().c_str());
}
/**
* @brief Retrieve the handle associated with this remote descriptor.
* @return The handle associated with this remote descriptor.
*/
uint16_t NimBLERemoteDescriptor::getHandle() {
return m_handle;
} // getHandle
/**
* @brief Get the characteristic that owns this descriptor.
* @return The characteristic that owns this descriptor.
*/
NimBLERemoteCharacteristic* NimBLERemoteDescriptor::getRemoteCharacteristic() {
return m_pRemoteCharacteristic;
} // getRemoteCharacteristic
/**
* @brief Retrieve the UUID associated this remote descriptor.
* @return The UUID associated this remote descriptor.
*/
NimBLEUUID NimBLERemoteDescriptor::getUUID() {
return m_uuid;
} // getUUID
/**
* @brief Read a byte value
* @return The value as a byte
* @deprecated Use readValue<uint8_t>().
*/
uint8_t NimBLERemoteDescriptor::readUInt8() {
std::string value = readValue();
if (value.length() >= 1) {
return (uint8_t) value[0];
}
return 0;
} // readUInt8
/**
* @brief Read an unsigned 16 bit value
* @return The unsigned 16 bit value.
* @deprecated Use readValue<uint16_t>().
*/
uint16_t NimBLERemoteDescriptor::readUInt16() {
std::string value = readValue();
if (value.length() >= 2) {
return *(uint16_t*) value.data();
}
return 0;
} // readUInt16
/**
* @brief Read an unsigned 32 bit value.
* @return the unsigned 32 bit value.
* @deprecated Use readValue<uint32_t>().
*/
uint32_t NimBLERemoteDescriptor::readUInt32() {
std::string value = readValue();
if (value.length() >= 4) {
return *(uint32_t*) value.data();
}
return 0;
} // readUInt32
/**
* @brief Read the value of the remote descriptor.
* @return The value of the remote descriptor.
*/
std::string NimBLERemoteDescriptor::readValue() {
NIMBLE_LOGD(LOG_TAG, ">> Descriptor readValue: %s", toString().c_str());
NimBLEClient* pClient = getRemoteCharacteristic()->getRemoteService()->getClient();
std::string value;
if (!pClient->isConnected()) {
NIMBLE_LOGE(LOG_TAG, "Disconnected");
return value;
}
int rc = 0;
int retryCount = 1;
ble_task_data_t taskData = {this, xTaskGetCurrentTaskHandle(),0, &value};
do {
rc = ble_gattc_read_long(pClient->getConnId(), m_handle, 0,
NimBLERemoteDescriptor::onReadCB,
&taskData);
if (rc != 0) {
NIMBLE_LOGE(LOG_TAG, "Error: Failed to read descriptor; rc=%d, %s",
rc, NimBLEUtils::returnCodeToString(rc));
return value;
}
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
rc = taskData.rc;
switch(rc){
case 0:
case BLE_HS_EDONE:
rc = 0;
break;
// Descriptor is not long-readable, return with what we have.
case BLE_HS_ATT_ERR(BLE_ATT_ERR_ATTR_NOT_LONG):
NIMBLE_LOGI(LOG_TAG, "Attribute not long");
rc = 0;
break;
case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHEN):
case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHOR):
case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_ENC):
if (retryCount && pClient->secureConnection())
break;
/* Else falls through. */
default:
return value;
}
} while(rc != 0 && retryCount--);
NIMBLE_LOGD(LOG_TAG, "<< Descriptor readValue(): length: %d rc=%d", value.length(), rc);
return value;
} // readValue
/**
* @brief Callback for Descriptor read operation.
* @return success == 0 or error code.
*/
int NimBLERemoteDescriptor::onReadCB(uint16_t conn_handle,
const struct ble_gatt_error *error,
struct ble_gatt_attr *attr, void *arg)
{
ble_task_data_t *pTaskData = (ble_task_data_t*)arg;
NimBLERemoteDescriptor* desc = (NimBLERemoteDescriptor*)pTaskData->pATT;
uint16_t conn_id = desc->getRemoteCharacteristic()->getRemoteService()->getClient()->getConnId();
if(conn_id != conn_handle){
return 0;
}
NIMBLE_LOGD(LOG_TAG, "Read complete; status=%d conn_handle=%d", error->status, conn_handle);
std::string *strBuf = (std::string*)pTaskData->buf;
int rc = error->status;
if(rc == 0) {
if(attr) {
if(((*strBuf).length() + attr->om->om_len) > BLE_ATT_ATTR_MAX_LEN) {
rc = BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
} else {
NIMBLE_LOGD(LOG_TAG, "Got %d bytes", attr->om->om_len);
(*strBuf) += std::string((char*) attr->om->om_data, attr->om->om_len);
return 0;
}
}
}
pTaskData->rc = rc;
xTaskNotifyGive(pTaskData->task);
return rc;
}
/**
* @brief Return a string representation of this Remote Descriptor.
* @return A string representation of this Remote Descriptor.
*/
std::string NimBLERemoteDescriptor::toString() {
std::string res = "Descriptor: uuid: " + getUUID().toString();
char val[6];
res += ", handle: ";
snprintf(val, sizeof(val), "%d", getHandle());
res += val;
return res;
} // toString
/**
* @brief Callback for descriptor write operation.
* @return success == 0 or error code.
*/
int NimBLERemoteDescriptor::onWriteCB(uint16_t conn_handle,
const struct ble_gatt_error *error,
struct ble_gatt_attr *attr, void *arg)
{
ble_task_data_t *pTaskData = (ble_task_data_t*)arg;
NimBLERemoteDescriptor* descriptor = (NimBLERemoteDescriptor*)pTaskData->pATT;
if(descriptor->getRemoteCharacteristic()->getRemoteService()->getClient()->getConnId() != conn_handle){
return 0;
}
NIMBLE_LOGI(LOG_TAG, "Write complete; status=%d conn_handle=%d", error->status, conn_handle);
pTaskData->rc = error->status;
xTaskNotifyGive(pTaskData->task);
return 0;
}
/**
* @brief Write data to the BLE Remote Descriptor.
* @param [in] data The data to send to the remote descriptor.
* @param [in] length The length of the data to send.
* @param [in] response True if we expect a write response.
* @return True if successful
*/
bool NimBLERemoteDescriptor::writeValue(const uint8_t* data, size_t length, bool response) {
NIMBLE_LOGD(LOG_TAG, ">> Descriptor writeValue: %s", toString().c_str());
NimBLEClient* pClient = getRemoteCharacteristic()->getRemoteService()->getClient();
// Check to see that we are connected.
if (!pClient->isConnected()) {
NIMBLE_LOGE(LOG_TAG, "Disconnected");
return false;
}
int rc = 0;
int retryCount = 1;
uint16_t mtu = ble_att_mtu(pClient->getConnId()) - 3;
// Check if the data length is longer than we can write in 1 connection event.
// If so we must do a long write which requires a response.
if(length <= mtu && !response) {
rc = ble_gattc_write_no_rsp_flat(pClient->getConnId(), m_handle, data, length);
return (rc == 0);
}
ble_task_data_t taskData = {this, xTaskGetCurrentTaskHandle(), 0, nullptr};
do {
if(length > mtu) {
NIMBLE_LOGI(LOG_TAG,"long write %d bytes", length);
os_mbuf *om = ble_hs_mbuf_from_flat(data, length);
rc = ble_gattc_write_long(pClient->getConnId(), m_handle, 0, om,
NimBLERemoteDescriptor::onWriteCB,
&taskData);
} else {
rc = ble_gattc_write_flat(pClient->getConnId(), m_handle,
data, length,
NimBLERemoteDescriptor::onWriteCB,
&taskData);
}
if (rc != 0) {
NIMBLE_LOGE(LOG_TAG, "Error: Failed to write descriptor; rc=%d", rc);
return false;
}
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
rc = taskData.rc;
switch(rc) {
case 0:
case BLE_HS_EDONE:
rc = 0;
break;
case BLE_HS_ATT_ERR(BLE_ATT_ERR_ATTR_NOT_LONG):
NIMBLE_LOGE(LOG_TAG, "Long write not supported by peer; Truncating length to %d", mtu);
retryCount++;
length = mtu;
break;
case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHEN):
case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHOR):
case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_ENC):
if (retryCount && pClient->secureConnection())
break;
/* Else falls through. */
default:
return false;
}
} while(rc != 0 && retryCount--);
NIMBLE_LOGD(LOG_TAG, "<< Descriptor writeValue, rc: %d",rc);
return (rc == 0);
} // writeValue
/**
* @brief Write data represented as a string to the BLE Remote Descriptor.
* @param [in] newValue The data to send to the remote descriptor.
* @param [in] response True if we expect a response.
* @return True if successful
*/
bool NimBLERemoteDescriptor::writeValue(const std::string &newValue, bool response) {
return writeValue((uint8_t*) newValue.data(), newValue.length(), response);
} // writeValue
#endif // #if defined( CONFIG_BT_NIMBLE_ROLE_CENTRAL)
#endif /* CONFIG_BT_ENABLED */
| ramalhais/code | arduino/libraries/NimBLE-Arduino/src/NimBLERemoteDescriptor.cpp | C++ | gpl-2.0 | 10,911 |
<?php
/* core/themes/stable/templates/admin/admin-block.html.twig */
class __TwigTemplate_73d94355d598b4dfa4b4ca02e16e4343556a0d714799515056c444f65791e3fc 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())
{
$tags = array("if" => 16);
$filters = array();
$functions = array();
try {
$this->env->getExtension('sandbox')->checkSecurity(
array('if'),
array(),
array()
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setTemplateFile($this->getTemplateName());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 15
echo "<div class=\"panel\">
";
// line 16
if ($this->getAttribute((isset($context["block"]) ? $context["block"] : null), "title", array())) {
// line 17
echo " <h3 class=\"panel__title\">";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["block"]) ? $context["block"] : null), "title", array()), "html", null, true));
echo "</h3>
";
}
// line 19
echo " ";
if ($this->getAttribute((isset($context["block"]) ? $context["block"] : null), "content", array())) {
// line 20
echo " <div class=\"panel__content\">";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["block"]) ? $context["block"] : null), "content", array()), "html", null, true));
echo "</div>
";
} elseif ($this->getAttribute( // line 21
(isset($context["block"]) ? $context["block"] : null), "description", array())) {
// line 22
echo " <div class=\"panel__description\">";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["block"]) ? $context["block"] : null), "description", array()), "html", null, true));
echo "</div>
";
}
// line 24
echo "</div>
";
}
public function getTemplateName()
{
return "core/themes/stable/templates/admin/admin-block.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 70 => 24, 64 => 22, 62 => 21, 57 => 20, 54 => 19, 48 => 17, 46 => 16, 43 => 15,);
}
}
/* {#*/
/* /***/
/* * @file*/
/* * Theme override for an administrative block.*/
/* **/
/* * Available variables:*/
/* * - block: An array of information about the block, including:*/
/* * - show: A flag indicating if the block should be displayed.*/
/* * - title: The block title.*/
/* * - content: (optional) The content of the block.*/
/* * - description: (optional) A description of the block.*/
/* * (Description should only be output if content is not available).*/
/* *//* */
/* #}*/
/* <div class="panel">*/
/* {% if block.title %}*/
/* <h3 class="panel__title">{{ block.title }}</h3>*/
/* {% endif %}*/
/* {% if block.content %}*/
/* <div class="panel__content">{{ block.content }}</div>*/
/* {% elseif block.description %}*/
/* <div class="panel__description">{{ block.description }}</div>*/
/* {% endif %}*/
/* </div>*/
/* */
| neetumorwani/dcon | sites/default/files/php/twig/e7e9cf99_admin-block.html.twig_b440e57db9efed76852fc563c6827050f943bfd78965a8b1ecb3a02c71db4383/d60b7a51460832b200c45935652984dcb99b21f7bda17e389af5047f446ab118.php | PHP | gpl-2.0 | 4,309 |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 4);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Url", function() { return Url; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Http", function() { return Http; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Resource", function() { return Resource; });
/*!
* vue-resource v1.3.4
* https://github.com/pagekit/vue-resource
* Released under the MIT License.
*/
/**
* Promises/A+ polyfill v1.1.4 (https://github.com/bramstein/promis)
*/
var RESOLVED = 0;
var REJECTED = 1;
var PENDING = 2;
function Promise$1(executor) {
this.state = PENDING;
this.value = undefined;
this.deferred = [];
var promise = this;
try {
executor(function (x) {
promise.resolve(x);
}, function (r) {
promise.reject(r);
});
} catch (e) {
promise.reject(e);
}
}
Promise$1.reject = function (r) {
return new Promise$1(function (resolve, reject) {
reject(r);
});
};
Promise$1.resolve = function (x) {
return new Promise$1(function (resolve, reject) {
resolve(x);
});
};
Promise$1.all = function all(iterable) {
return new Promise$1(function (resolve, reject) {
var count = 0, result = [];
if (iterable.length === 0) {
resolve(result);
}
function resolver(i) {
return function (x) {
result[i] = x;
count += 1;
if (count === iterable.length) {
resolve(result);
}
};
}
for (var i = 0; i < iterable.length; i += 1) {
Promise$1.resolve(iterable[i]).then(resolver(i), reject);
}
});
};
Promise$1.race = function race(iterable) {
return new Promise$1(function (resolve, reject) {
for (var i = 0; i < iterable.length; i += 1) {
Promise$1.resolve(iterable[i]).then(resolve, reject);
}
});
};
var p$1 = Promise$1.prototype;
p$1.resolve = function resolve(x) {
var promise = this;
if (promise.state === PENDING) {
if (x === promise) {
throw new TypeError('Promise settled with itself.');
}
var called = false;
try {
var then = x && x['then'];
if (x !== null && typeof x === 'object' && typeof then === 'function') {
then.call(x, function (x) {
if (!called) {
promise.resolve(x);
}
called = true;
}, function (r) {
if (!called) {
promise.reject(r);
}
called = true;
});
return;
}
} catch (e) {
if (!called) {
promise.reject(e);
}
return;
}
promise.state = RESOLVED;
promise.value = x;
promise.notify();
}
};
p$1.reject = function reject(reason) {
var promise = this;
if (promise.state === PENDING) {
if (reason === promise) {
throw new TypeError('Promise settled with itself.');
}
promise.state = REJECTED;
promise.value = reason;
promise.notify();
}
};
p$1.notify = function notify() {
var promise = this;
nextTick(function () {
if (promise.state !== PENDING) {
while (promise.deferred.length) {
var deferred = promise.deferred.shift(),
onResolved = deferred[0],
onRejected = deferred[1],
resolve = deferred[2],
reject = deferred[3];
try {
if (promise.state === RESOLVED) {
if (typeof onResolved === 'function') {
resolve(onResolved.call(undefined, promise.value));
} else {
resolve(promise.value);
}
} else if (promise.state === REJECTED) {
if (typeof onRejected === 'function') {
resolve(onRejected.call(undefined, promise.value));
} else {
reject(promise.value);
}
}
} catch (e) {
reject(e);
}
}
}
});
};
p$1.then = function then(onResolved, onRejected) {
var promise = this;
return new Promise$1(function (resolve, reject) {
promise.deferred.push([onResolved, onRejected, resolve, reject]);
promise.notify();
});
};
p$1.catch = function (onRejected) {
return this.then(undefined, onRejected);
};
/**
* Promise adapter.
*/
if (typeof Promise === 'undefined') {
window.Promise = Promise$1;
}
function PromiseObj(executor, context) {
if (executor instanceof Promise) {
this.promise = executor;
} else {
this.promise = new Promise(executor.bind(context));
}
this.context = context;
}
PromiseObj.all = function (iterable, context) {
return new PromiseObj(Promise.all(iterable), context);
};
PromiseObj.resolve = function (value, context) {
return new PromiseObj(Promise.resolve(value), context);
};
PromiseObj.reject = function (reason, context) {
return new PromiseObj(Promise.reject(reason), context);
};
PromiseObj.race = function (iterable, context) {
return new PromiseObj(Promise.race(iterable), context);
};
var p = PromiseObj.prototype;
p.bind = function (context) {
this.context = context;
return this;
};
p.then = function (fulfilled, rejected) {
if (fulfilled && fulfilled.bind && this.context) {
fulfilled = fulfilled.bind(this.context);
}
if (rejected && rejected.bind && this.context) {
rejected = rejected.bind(this.context);
}
return new PromiseObj(this.promise.then(fulfilled, rejected), this.context);
};
p.catch = function (rejected) {
if (rejected && rejected.bind && this.context) {
rejected = rejected.bind(this.context);
}
return new PromiseObj(this.promise.catch(rejected), this.context);
};
p.finally = function (callback) {
return this.then(function (value) {
callback.call(this);
return value;
}, function (reason) {
callback.call(this);
return Promise.reject(reason);
}
);
};
/**
* Utility functions.
*/
var ref = {};
var hasOwnProperty = ref.hasOwnProperty;
var ref$1 = [];
var slice = ref$1.slice;
var debug = false;
var ntick;
var inBrowser = typeof window !== 'undefined';
var Util = function (ref) {
var config = ref.config;
var nextTick = ref.nextTick;
ntick = nextTick;
debug = config.debug || !config.silent;
};
function warn(msg) {
if (typeof console !== 'undefined' && debug) {
console.warn('[VueResource warn]: ' + msg);
}
}
function error(msg) {
if (typeof console !== 'undefined') {
console.error(msg);
}
}
function nextTick(cb, ctx) {
return ntick(cb, ctx);
}
function trim(str) {
return str ? str.replace(/^\s*|\s*$/g, '') : '';
}
function trimEnd(str, chars) {
if (str && chars === undefined) {
return str.replace(/\s+$/, '');
}
if (!str || !chars) {
return str;
}
return str.replace(new RegExp(("[" + chars + "]+$")), '');
}
function toLower(str) {
return str ? str.toLowerCase() : '';
}
function toUpper(str) {
return str ? str.toUpperCase() : '';
}
var isArray = Array.isArray;
function isString(val) {
return typeof val === 'string';
}
function isFunction(val) {
return typeof val === 'function';
}
function isObject(obj) {
return obj !== null && typeof obj === 'object';
}
function isPlainObject(obj) {
return isObject(obj) && Object.getPrototypeOf(obj) == Object.prototype;
}
function isBlob(obj) {
return typeof Blob !== 'undefined' && obj instanceof Blob;
}
function isFormData(obj) {
return typeof FormData !== 'undefined' && obj instanceof FormData;
}
function when(value, fulfilled, rejected) {
var promise = PromiseObj.resolve(value);
if (arguments.length < 2) {
return promise;
}
return promise.then(fulfilled, rejected);
}
function options(fn, obj, opts) {
opts = opts || {};
if (isFunction(opts)) {
opts = opts.call(obj);
}
return merge(fn.bind({$vm: obj, $options: opts}), fn, {$options: opts});
}
function each(obj, iterator) {
var i, key;
if (isArray(obj)) {
for (i = 0; i < obj.length; i++) {
iterator.call(obj[i], obj[i], i);
}
} else if (isObject(obj)) {
for (key in obj) {
if (hasOwnProperty.call(obj, key)) {
iterator.call(obj[key], obj[key], key);
}
}
}
return obj;
}
var assign = Object.assign || _assign;
function merge(target) {
var args = slice.call(arguments, 1);
args.forEach(function (source) {
_merge(target, source, true);
});
return target;
}
function defaults(target) {
var args = slice.call(arguments, 1);
args.forEach(function (source) {
for (var key in source) {
if (target[key] === undefined) {
target[key] = source[key];
}
}
});
return target;
}
function _assign(target) {
var args = slice.call(arguments, 1);
args.forEach(function (source) {
_merge(target, source);
});
return target;
}
function _merge(target, source, deep) {
for (var key in source) {
if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
target[key] = {};
}
if (isArray(source[key]) && !isArray(target[key])) {
target[key] = [];
}
_merge(target[key], source[key], deep);
} else if (source[key] !== undefined) {
target[key] = source[key];
}
}
}
/**
* Root Prefix Transform.
*/
var root = function (options$$1, next) {
var url = next(options$$1);
if (isString(options$$1.root) && !/^(https?:)?\//.test(url)) {
url = trimEnd(options$$1.root, '/') + '/' + url;
}
return url;
};
/**
* Query Parameter Transform.
*/
var query = function (options$$1, next) {
var urlParams = Object.keys(Url.options.params), query = {}, url = next(options$$1);
each(options$$1.params, function (value, key) {
if (urlParams.indexOf(key) === -1) {
query[key] = value;
}
});
query = Url.params(query);
if (query) {
url += (url.indexOf('?') == -1 ? '?' : '&') + query;
}
return url;
};
/**
* URL Template v2.0.6 (https://github.com/bramstein/url-template)
*/
function expand(url, params, variables) {
var tmpl = parse(url), expanded = tmpl.expand(params);
if (variables) {
variables.push.apply(variables, tmpl.vars);
}
return expanded;
}
function parse(template) {
var operators = ['+', '#', '.', '/', ';', '?', '&'], variables = [];
return {
vars: variables,
expand: function expand(context) {
return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
if (expression) {
var operator = null, values = [];
if (operators.indexOf(expression.charAt(0)) !== -1) {
operator = expression.charAt(0);
expression = expression.substr(1);
}
expression.split(/,/g).forEach(function (variable) {
var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
values.push.apply(values, getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
variables.push(tmp[1]);
});
if (operator && operator !== '+') {
var separator = ',';
if (operator === '?') {
separator = '&';
} else if (operator !== '#') {
separator = operator;
}
return (values.length !== 0 ? operator : '') + values.join(separator);
} else {
return values.join(',');
}
} else {
return encodeReserved(literal);
}
});
}
};
}
function getValues(context, operator, key, modifier) {
var value = context[key], result = [];
if (isDefined(value) && value !== '') {
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
value = value.toString();
if (modifier && modifier !== '*') {
value = value.substring(0, parseInt(modifier, 10));
}
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null));
} else {
if (modifier === '*') {
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null));
});
} else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
result.push(encodeValue(operator, value[k], k));
}
});
}
} else {
var tmp = [];
if (Array.isArray(value)) {
value.filter(isDefined).forEach(function (value) {
tmp.push(encodeValue(operator, value));
});
} else {
Object.keys(value).forEach(function (k) {
if (isDefined(value[k])) {
tmp.push(encodeURIComponent(k));
tmp.push(encodeValue(operator, value[k].toString()));
}
});
}
if (isKeyOperator(operator)) {
result.push(encodeURIComponent(key) + '=' + tmp.join(','));
} else if (tmp.length !== 0) {
result.push(tmp.join(','));
}
}
}
} else {
if (operator === ';') {
result.push(encodeURIComponent(key));
} else if (value === '' && (operator === '&' || operator === '?')) {
result.push(encodeURIComponent(key) + '=');
} else if (value === '') {
result.push('');
}
}
return result;
}
function isDefined(value) {
return value !== undefined && value !== null;
}
function isKeyOperator(operator) {
return operator === ';' || operator === '&' || operator === '?';
}
function encodeValue(operator, value, key) {
value = (operator === '+' || operator === '#') ? encodeReserved(value) : encodeURIComponent(value);
if (key) {
return encodeURIComponent(key) + '=' + value;
} else {
return value;
}
}
function encodeReserved(str) {
return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
if (!/%[0-9A-Fa-f]/.test(part)) {
part = encodeURI(part);
}
return part;
}).join('');
}
/**
* URL Template (RFC 6570) Transform.
*/
var template = function (options) {
var variables = [], url = expand(options.url, options.params, variables);
variables.forEach(function (key) {
delete options.params[key];
});
return url;
};
/**
* Service for URL templating.
*/
function Url(url, params) {
var self = this || {}, options$$1 = url, transform;
if (isString(url)) {
options$$1 = {url: url, params: params};
}
options$$1 = merge({}, Url.options, self.$options, options$$1);
Url.transforms.forEach(function (handler) {
if (isString(handler)) {
handler = Url.transform[handler];
}
if (isFunction(handler)) {
transform = factory(handler, transform, self.$vm);
}
});
return transform(options$$1);
}
/**
* Url options.
*/
Url.options = {
url: '',
root: null,
params: {}
};
/**
* Url transforms.
*/
Url.transform = {template: template, query: query, root: root};
Url.transforms = ['template', 'query', 'root'];
/**
* Encodes a Url parameter string.
*
* @param {Object} obj
*/
Url.params = function (obj) {
var params = [], escape = encodeURIComponent;
params.add = function (key, value) {
if (isFunction(value)) {
value = value();
}
if (value === null) {
value = '';
}
this.push(escape(key) + '=' + escape(value));
};
serialize(params, obj);
return params.join('&').replace(/%20/g, '+');
};
/**
* Parse a URL and return its components.
*
* @param {String} url
*/
Url.parse = function (url) {
var el = document.createElement('a');
if (document.documentMode) {
el.href = url;
url = el.href;
}
el.href = url;
return {
href: el.href,
protocol: el.protocol ? el.protocol.replace(/:$/, '') : '',
port: el.port,
host: el.host,
hostname: el.hostname,
pathname: el.pathname.charAt(0) === '/' ? el.pathname : '/' + el.pathname,
search: el.search ? el.search.replace(/^\?/, '') : '',
hash: el.hash ? el.hash.replace(/^#/, '') : ''
};
};
function factory(handler, next, vm) {
return function (options$$1) {
return handler.call(vm, options$$1, next);
};
}
function serialize(params, obj, scope) {
var array = isArray(obj), plain = isPlainObject(obj), hash;
each(obj, function (value, key) {
hash = isObject(value) || isArray(value);
if (scope) {
key = scope + '[' + (plain || hash ? key : '') + ']';
}
if (!scope && array) {
params.add(value.name, value.value);
} else if (hash) {
serialize(params, value, key);
} else {
params.add(key, value);
}
});
}
/**
* XDomain client (Internet Explorer).
*/
var xdrClient = function (request) {
return new PromiseObj(function (resolve) {
var xdr = new XDomainRequest(), handler = function (ref) {
var type = ref.type;
var status = 0;
if (type === 'load') {
status = 200;
} else if (type === 'error') {
status = 500;
}
resolve(request.respondWith(xdr.responseText, {status: status}));
};
request.abort = function () { return xdr.abort(); };
xdr.open(request.method, request.getUrl());
if (request.timeout) {
xdr.timeout = request.timeout;
}
xdr.onload = handler;
xdr.onabort = handler;
xdr.onerror = handler;
xdr.ontimeout = handler;
xdr.onprogress = function () {};
xdr.send(request.getBody());
});
};
/**
* CORS Interceptor.
*/
var SUPPORTS_CORS = inBrowser && 'withCredentials' in new XMLHttpRequest();
var cors = function (request, next) {
if (inBrowser) {
var orgUrl = Url.parse(location.href);
var reqUrl = Url.parse(request.getUrl());
if (reqUrl.protocol !== orgUrl.protocol || reqUrl.host !== orgUrl.host) {
request.crossOrigin = true;
request.emulateHTTP = false;
if (!SUPPORTS_CORS) {
request.client = xdrClient;
}
}
}
next();
};
/**
* Form data Interceptor.
*/
var form = function (request, next) {
if (isFormData(request.body)) {
request.headers.delete('Content-Type');
} else if (isObject(request.body) && request.emulateJSON) {
request.body = Url.params(request.body);
request.headers.set('Content-Type', 'application/x-www-form-urlencoded');
}
next();
};
/**
* JSON Interceptor.
*/
var json = function (request, next) {
var type = request.headers.get('Content-Type') || '';
if (isObject(request.body) && type.indexOf('application/json') === 0) {
request.body = JSON.stringify(request.body);
}
next(function (response) {
return response.bodyText ? when(response.text(), function (text) {
type = response.headers.get('Content-Type') || '';
if (type.indexOf('application/json') === 0 || isJson(text)) {
try {
response.body = JSON.parse(text);
} catch (e) {
response.body = null;
}
} else {
response.body = text;
}
return response;
}) : response;
});
};
function isJson(str) {
var start = str.match(/^\[|^\{(?!\{)/), end = {'[': /]$/, '{': /}$/};
return start && end[start[0]].test(str);
}
/**
* JSONP client (Browser).
*/
var jsonpClient = function (request) {
return new PromiseObj(function (resolve) {
var name = request.jsonp || 'callback', callback = request.jsonpCallback || '_jsonp' + Math.random().toString(36).substr(2), body = null, handler, script;
handler = function (ref) {
var type = ref.type;
var status = 0;
if (type === 'load' && body !== null) {
status = 200;
} else if (type === 'error') {
status = 500;
}
if (status && window[callback]) {
delete window[callback];
document.body.removeChild(script);
}
resolve(request.respondWith(body, {status: status}));
};
window[callback] = function (result) {
body = JSON.stringify(result);
};
request.abort = function () {
handler({type: 'abort'});
};
request.params[name] = callback;
if (request.timeout) {
setTimeout(request.abort, request.timeout);
}
script = document.createElement('script');
script.src = request.getUrl();
script.type = 'text/javascript';
script.async = true;
script.onload = handler;
script.onerror = handler;
document.body.appendChild(script);
});
};
/**
* JSONP Interceptor.
*/
var jsonp = function (request, next) {
if (request.method == 'JSONP') {
request.client = jsonpClient;
}
next();
};
/**
* Before Interceptor.
*/
var before = function (request, next) {
if (isFunction(request.before)) {
request.before.call(this, request);
}
next();
};
/**
* HTTP method override Interceptor.
*/
var method = function (request, next) {
if (request.emulateHTTP && /^(PUT|PATCH|DELETE)$/i.test(request.method)) {
request.headers.set('X-HTTP-Method-Override', request.method);
request.method = 'POST';
}
next();
};
/**
* Header Interceptor.
*/
var header = function (request, next) {
var headers = assign({}, Http.headers.common,
!request.crossOrigin ? Http.headers.custom : {},
Http.headers[toLower(request.method)]
);
each(headers, function (value, name) {
if (!request.headers.has(name)) {
request.headers.set(name, value);
}
});
next();
};
/**
* XMLHttp client (Browser).
*/
var xhrClient = function (request) {
return new PromiseObj(function (resolve) {
var xhr = new XMLHttpRequest(), handler = function (event) {
var response = request.respondWith(
'response' in xhr ? xhr.response : xhr.responseText, {
status: xhr.status === 1223 ? 204 : xhr.status, // IE9 status bug
statusText: xhr.status === 1223 ? 'No Content' : trim(xhr.statusText)
}
);
each(trim(xhr.getAllResponseHeaders()).split('\n'), function (row) {
response.headers.append(row.slice(0, row.indexOf(':')), row.slice(row.indexOf(':') + 1));
});
resolve(response);
};
request.abort = function () { return xhr.abort(); };
if (request.progress) {
if (request.method === 'GET') {
xhr.addEventListener('progress', request.progress);
} else if (/^(POST|PUT)$/i.test(request.method)) {
xhr.upload.addEventListener('progress', request.progress);
}
}
xhr.open(request.method, request.getUrl(), true);
if (request.timeout) {
xhr.timeout = request.timeout;
}
if (request.responseType && 'responseType' in xhr) {
xhr.responseType = request.responseType;
}
if (request.withCredentials || request.credentials) {
xhr.withCredentials = true;
}
if (!request.crossOrigin) {
request.headers.set('X-Requested-With', 'XMLHttpRequest');
}
request.headers.forEach(function (value, name) {
xhr.setRequestHeader(name, value);
});
xhr.onload = handler;
xhr.onabort = handler;
xhr.onerror = handler;
xhr.ontimeout = handler;
xhr.send(request.getBody());
});
};
/**
* Http client (Node).
*/
var nodeClient = function (request) {
var client = __webpack_require__(6);
return new PromiseObj(function (resolve) {
var url = request.getUrl();
var body = request.getBody();
var method = request.method;
var headers = {}, handler;
request.headers.forEach(function (value, name) {
headers[name] = value;
});
client(url, {body: body, method: method, headers: headers}).then(handler = function (resp) {
var response = request.respondWith(resp.body, {
status: resp.statusCode,
statusText: trim(resp.statusMessage)
}
);
each(resp.headers, function (value, name) {
response.headers.set(name, value);
});
resolve(response);
}, function (error$$1) { return handler(error$$1.response); });
});
};
/**
* Base client.
*/
var Client = function (context) {
var reqHandlers = [sendRequest], resHandlers = [], handler;
if (!isObject(context)) {
context = null;
}
function Client(request) {
return new PromiseObj(function (resolve, reject) {
function exec() {
handler = reqHandlers.pop();
if (isFunction(handler)) {
handler.call(context, request, next);
} else {
warn(("Invalid interceptor of type " + (typeof handler) + ", must be a function"));
next();
}
}
function next(response) {
if (isFunction(response)) {
resHandlers.unshift(response);
} else if (isObject(response)) {
resHandlers.forEach(function (handler) {
response = when(response, function (response) {
return handler.call(context, response) || response;
}, reject);
});
when(response, resolve, reject);
return;
}
exec();
}
exec();
}, context);
}
Client.use = function (handler) {
reqHandlers.push(handler);
};
return Client;
};
function sendRequest(request, resolve) {
var client = request.client || (inBrowser ? xhrClient : nodeClient);
resolve(client(request));
}
/**
* HTTP Headers.
*/
var Headers = function Headers(headers) {
var this$1 = this;
this.map = {};
each(headers, function (value, name) { return this$1.append(name, value); });
};
Headers.prototype.has = function has (name) {
return getName(this.map, name) !== null;
};
Headers.prototype.get = function get (name) {
var list = this.map[getName(this.map, name)];
return list ? list.join() : null;
};
Headers.prototype.getAll = function getAll (name) {
return this.map[getName(this.map, name)] || [];
};
Headers.prototype.set = function set (name, value) {
this.map[normalizeName(getName(this.map, name) || name)] = [trim(value)];
};
Headers.prototype.append = function append (name, value){
var list = this.map[getName(this.map, name)];
if (list) {
list.push(trim(value));
} else {
this.set(name, value);
}
};
Headers.prototype.delete = function delete$1 (name){
delete this.map[getName(this.map, name)];
};
Headers.prototype.deleteAll = function deleteAll (){
this.map = {};
};
Headers.prototype.forEach = function forEach (callback, thisArg) {
var this$1 = this;
each(this.map, function (list, name) {
each(list, function (value) { return callback.call(thisArg, value, name, this$1); });
});
};
function getName(map, name) {
return Object.keys(map).reduce(function (prev, curr) {
return toLower(name) === toLower(curr) ? curr : prev;
}, null);
}
function normalizeName(name) {
if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
throw new TypeError('Invalid character in header field name');
}
return trim(name);
}
/**
* HTTP Response.
*/
var Response = function Response(body, ref) {
var url = ref.url;
var headers = ref.headers;
var status = ref.status;
var statusText = ref.statusText;
this.url = url;
this.ok = status >= 200 && status < 300;
this.status = status || 0;
this.statusText = statusText || '';
this.headers = new Headers(headers);
this.body = body;
if (isString(body)) {
this.bodyText = body;
} else if (isBlob(body)) {
this.bodyBlob = body;
if (isBlobText(body)) {
this.bodyText = blobText(body);
}
}
};
Response.prototype.blob = function blob () {
return when(this.bodyBlob);
};
Response.prototype.text = function text () {
return when(this.bodyText);
};
Response.prototype.json = function json () {
return when(this.text(), function (text) { return JSON.parse(text); });
};
Object.defineProperty(Response.prototype, 'data', {
get: function get() {
return this.body;
},
set: function set(body) {
this.body = body;
}
});
function blobText(body) {
return new PromiseObj(function (resolve) {
var reader = new FileReader();
reader.readAsText(body);
reader.onload = function () {
resolve(reader.result);
};
});
}
function isBlobText(body) {
return body.type.indexOf('text') === 0 || body.type.indexOf('json') !== -1;
}
/**
* HTTP Request.
*/
var Request = function Request(options$$1) {
this.body = null;
this.params = {};
assign(this, options$$1, {
method: toUpper(options$$1.method || 'GET')
});
if (!(this.headers instanceof Headers)) {
this.headers = new Headers(this.headers);
}
};
Request.prototype.getUrl = function getUrl (){
return Url(this);
};
Request.prototype.getBody = function getBody (){
return this.body;
};
Request.prototype.respondWith = function respondWith (body, options$$1) {
return new Response(body, assign(options$$1 || {}, {url: this.getUrl()}));
};
/**
* Service for sending network requests.
*/
var COMMON_HEADERS = {'Accept': 'application/json, text/plain, */*'};
var JSON_CONTENT_TYPE = {'Content-Type': 'application/json;charset=utf-8'};
function Http(options$$1) {
var self = this || {}, client = Client(self.$vm);
defaults(options$$1 || {}, self.$options, Http.options);
Http.interceptors.forEach(function (handler) {
if (isString(handler)) {
handler = Http.interceptor[handler];
}
if (isFunction(handler)) {
client.use(handler);
}
});
return client(new Request(options$$1)).then(function (response) {
return response.ok ? response : PromiseObj.reject(response);
}, function (response) {
if (response instanceof Error) {
error(response);
}
return PromiseObj.reject(response);
});
}
Http.options = {};
Http.headers = {
put: JSON_CONTENT_TYPE,
post: JSON_CONTENT_TYPE,
patch: JSON_CONTENT_TYPE,
delete: JSON_CONTENT_TYPE,
common: COMMON_HEADERS,
custom: {}
};
Http.interceptor = {before: before, method: method, jsonp: jsonp, json: json, form: form, header: header, cors: cors};
Http.interceptors = ['before', 'method', 'jsonp', 'json', 'form', 'header', 'cors'];
['get', 'delete', 'head', 'jsonp'].forEach(function (method$$1) {
Http[method$$1] = function (url, options$$1) {
return this(assign(options$$1 || {}, {url: url, method: method$$1}));
};
});
['post', 'put', 'patch'].forEach(function (method$$1) {
Http[method$$1] = function (url, body, options$$1) {
return this(assign(options$$1 || {}, {url: url, method: method$$1, body: body}));
};
});
/**
* Service for interacting with RESTful services.
*/
function Resource(url, params, actions, options$$1) {
var self = this || {}, resource = {};
actions = assign({},
Resource.actions,
actions
);
each(actions, function (action, name) {
action = merge({url: url, params: assign({}, params)}, options$$1, action);
resource[name] = function () {
return (self.$http || Http)(opts(action, arguments));
};
});
return resource;
}
function opts(action, args) {
var options$$1 = assign({}, action), params = {}, body;
switch (args.length) {
case 2:
params = args[0];
body = args[1];
break;
case 1:
if (/^(POST|PUT|PATCH)$/i.test(options$$1.method)) {
body = args[0];
} else {
params = args[0];
}
break;
case 0:
break;
default:
throw 'Expected up to 2 arguments [params, body], got ' + args.length + ' arguments';
}
options$$1.body = body;
options$$1.params = assign({}, options$$1.params, params);
return options$$1;
}
Resource.actions = {
get: {method: 'GET'},
save: {method: 'POST'},
query: {method: 'GET'},
update: {method: 'PUT'},
remove: {method: 'DELETE'},
delete: {method: 'DELETE'}
};
/**
* Install plugin.
*/
function plugin(Vue) {
if (plugin.installed) {
return;
}
Util(Vue);
Vue.url = Url;
Vue.http = Http;
Vue.resource = Resource;
Vue.Promise = PromiseObj;
Object.defineProperties(Vue.prototype, {
$url: {
get: function get() {
return options(Vue.url, this, this.$options.url);
}
},
$http: {
get: function get() {
return options(Vue.http, this, this.$options.http);
}
},
$resource: {
get: function get() {
return Vue.resource.bind(this);
}
},
$promise: {
get: function get() {
var this$1 = this;
return function (executor) { return new Vue.Promise(executor, this$1); };
}
}
});
}
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(plugin);
}
/* harmony default export */ __webpack_exports__["default"] = (plugin);
/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* WEBPACK VAR INJECTION */(function(process) {/**
* vue-router v2.7.0
* (c) 2017 Evan You
* @license MIT
*/
/* */
function assert (condition, message) {
if (!condition) {
throw new Error(("[vue-router] " + message))
}
}
function warn (condition, message) {
if (process.env.NODE_ENV !== 'production' && !condition) {
typeof console !== 'undefined' && console.warn(("[vue-router] " + message));
}
}
function isError (err) {
return Object.prototype.toString.call(err).indexOf('Error') > -1
}
var View = {
name: 'router-view',
functional: true,
props: {
name: {
type: String,
default: 'default'
}
},
render: function render (_, ref) {
var props = ref.props;
var children = ref.children;
var parent = ref.parent;
var data = ref.data;
data.routerView = true;
// directly use parent context's createElement() function
// so that components rendered by router-view can resolve named slots
var h = parent.$createElement;
var name = props.name;
var route = parent.$route;
var cache = parent._routerViewCache || (parent._routerViewCache = {});
// determine current view depth, also check to see if the tree
// has been toggled inactive but kept-alive.
var depth = 0;
var inactive = false;
while (parent && parent._routerRoot !== parent) {
if (parent.$vnode && parent.$vnode.data.routerView) {
depth++;
}
if (parent._inactive) {
inactive = true;
}
parent = parent.$parent;
}
data.routerViewDepth = depth;
// render previous view if the tree is inactive and kept-alive
if (inactive) {
return h(cache[name], data, children)
}
var matched = route.matched[depth];
// render empty node if no matched route
if (!matched) {
cache[name] = null;
return h()
}
var component = cache[name] = matched.components[name];
// attach instance registration hook
// this will be called in the instance's injected lifecycle hooks
data.registerRouteInstance = function (vm, val) {
// val could be undefined for unregistration
var current = matched.instances[name];
if (
(val && current !== vm) ||
(!val && current === vm)
) {
matched.instances[name] = val;
}
}
// also regiseter instance in prepatch hook
// in case the same component instance is reused across different routes
;(data.hook || (data.hook = {})).prepatch = function (_, vnode) {
matched.instances[name] = vnode.componentInstance;
};
// resolve props
data.props = resolveProps(route, matched.props && matched.props[name]);
return h(component, data, children)
}
};
function resolveProps (route, config) {
switch (typeof config) {
case 'undefined':
return
case 'object':
return config
case 'function':
return config(route)
case 'boolean':
return config ? route.params : undefined
default:
if (process.env.NODE_ENV !== 'production') {
warn(
false,
"props in \"" + (route.path) + "\" is a " + (typeof config) + ", " +
"expecting an object, function or boolean."
);
}
}
}
/* */
var encodeReserveRE = /[!'()*]/g;
var encodeReserveReplacer = function (c) { return '%' + c.charCodeAt(0).toString(16); };
var commaRE = /%2C/g;
// fixed encodeURIComponent which is more conformant to RFC3986:
// - escapes [!'()*]
// - preserve commas
var encode = function (str) { return encodeURIComponent(str)
.replace(encodeReserveRE, encodeReserveReplacer)
.replace(commaRE, ','); };
var decode = decodeURIComponent;
function resolveQuery (
query,
extraQuery,
_parseQuery
) {
if ( extraQuery === void 0 ) extraQuery = {};
var parse = _parseQuery || parseQuery;
var parsedQuery;
try {
parsedQuery = parse(query || '');
} catch (e) {
process.env.NODE_ENV !== 'production' && warn(false, e.message);
parsedQuery = {};
}
for (var key in extraQuery) {
var val = extraQuery[key];
parsedQuery[key] = Array.isArray(val) ? val.slice() : val;
}
return parsedQuery
}
function parseQuery (query) {
var res = {};
query = query.trim().replace(/^(\?|#|&)/, '');
if (!query) {
return res
}
query.split('&').forEach(function (param) {
var parts = param.replace(/\+/g, ' ').split('=');
var key = decode(parts.shift());
var val = parts.length > 0
? decode(parts.join('='))
: null;
if (res[key] === undefined) {
res[key] = val;
} else if (Array.isArray(res[key])) {
res[key].push(val);
} else {
res[key] = [res[key], val];
}
});
return res
}
function stringifyQuery (obj) {
var res = obj ? Object.keys(obj).map(function (key) {
var val = obj[key];
if (val === undefined) {
return ''
}
if (val === null) {
return encode(key)
}
if (Array.isArray(val)) {
var result = [];
val.forEach(function (val2) {
if (val2 === undefined) {
return
}
if (val2 === null) {
result.push(encode(key));
} else {
result.push(encode(key) + '=' + encode(val2));
}
});
return result.join('&')
}
return encode(key) + '=' + encode(val)
}).filter(function (x) { return x.length > 0; }).join('&') : null;
return res ? ("?" + res) : ''
}
/* */
var trailingSlashRE = /\/?$/;
function createRoute (
record,
location,
redirectedFrom,
router
) {
var stringifyQuery$$1 = router && router.options.stringifyQuery;
var route = {
name: location.name || (record && record.name),
meta: (record && record.meta) || {},
path: location.path || '/',
hash: location.hash || '',
query: location.query || {},
params: location.params || {},
fullPath: getFullPath(location, stringifyQuery$$1),
matched: record ? formatMatch(record) : []
};
if (redirectedFrom) {
route.redirectedFrom = getFullPath(redirectedFrom, stringifyQuery$$1);
}
return Object.freeze(route)
}
// the starting route that represents the initial state
var START = createRoute(null, {
path: '/'
});
function formatMatch (record) {
var res = [];
while (record) {
res.unshift(record);
record = record.parent;
}
return res
}
function getFullPath (
ref,
_stringifyQuery
) {
var path = ref.path;
var query = ref.query; if ( query === void 0 ) query = {};
var hash = ref.hash; if ( hash === void 0 ) hash = '';
var stringify = _stringifyQuery || stringifyQuery;
return (path || '/') + stringify(query) + hash
}
function isSameRoute (a, b) {
if (b === START) {
return a === b
} else if (!b) {
return false
} else if (a.path && b.path) {
return (
a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') &&
a.hash === b.hash &&
isObjectEqual(a.query, b.query)
)
} else if (a.name && b.name) {
return (
a.name === b.name &&
a.hash === b.hash &&
isObjectEqual(a.query, b.query) &&
isObjectEqual(a.params, b.params)
)
} else {
return false
}
}
function isObjectEqual (a, b) {
if ( a === void 0 ) a = {};
if ( b === void 0 ) b = {};
var aKeys = Object.keys(a);
var bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false
}
return aKeys.every(function (key) {
var aVal = a[key];
var bVal = b[key];
// check nested equality
if (typeof aVal === 'object' && typeof bVal === 'object') {
return isObjectEqual(aVal, bVal)
}
return String(aVal) === String(bVal)
})
}
function isIncludedRoute (current, target) {
return (
current.path.replace(trailingSlashRE, '/').indexOf(
target.path.replace(trailingSlashRE, '/')
) === 0 &&
(!target.hash || current.hash === target.hash) &&
queryIncludes(current.query, target.query)
)
}
function queryIncludes (current, target) {
for (var key in target) {
if (!(key in current)) {
return false
}
}
return true
}
/* */
// work around weird flow bug
var toTypes = [String, Object];
var eventTypes = [String, Array];
var Link = {
name: 'router-link',
props: {
to: {
type: toTypes,
required: true
},
tag: {
type: String,
default: 'a'
},
exact: Boolean,
append: Boolean,
replace: Boolean,
activeClass: String,
exactActiveClass: String,
event: {
type: eventTypes,
default: 'click'
}
},
render: function render (h) {
var this$1 = this;
var router = this.$router;
var current = this.$route;
var ref = router.resolve(this.to, current, this.append);
var location = ref.location;
var route = ref.route;
var href = ref.href;
var classes = {};
var globalActiveClass = router.options.linkActiveClass;
var globalExactActiveClass = router.options.linkExactActiveClass;
// Support global empty active class
var activeClassFallback = globalActiveClass == null
? 'router-link-active'
: globalActiveClass;
var exactActiveClassFallback = globalExactActiveClass == null
? 'router-link-exact-active'
: globalExactActiveClass;
var activeClass = this.activeClass == null
? activeClassFallback
: this.activeClass;
var exactActiveClass = this.exactActiveClass == null
? exactActiveClassFallback
: this.exactActiveClass;
var compareTarget = location.path
? createRoute(null, location, null, router)
: route;
classes[exactActiveClass] = isSameRoute(current, compareTarget);
classes[activeClass] = this.exact
? classes[exactActiveClass]
: isIncludedRoute(current, compareTarget);
var handler = function (e) {
if (guardEvent(e)) {
if (this$1.replace) {
router.replace(location);
} else {
router.push(location);
}
}
};
var on = { click: guardEvent };
if (Array.isArray(this.event)) {
this.event.forEach(function (e) { on[e] = handler; });
} else {
on[this.event] = handler;
}
var data = {
class: classes
};
if (this.tag === 'a') {
data.on = on;
data.attrs = { href: href };
} else {
// find the first <a> child and apply listener and href
var a = findAnchor(this.$slots.default);
if (a) {
// in case the <a> is a static node
a.isStatic = false;
var extend = _Vue.util.extend;
var aData = a.data = extend({}, a.data);
aData.on = on;
var aAttrs = a.data.attrs = extend({}, a.data.attrs);
aAttrs.href = href;
} else {
// doesn't have <a> child, apply listener to self
data.on = on;
}
}
return h(this.tag, data, this.$slots.default)
}
};
function guardEvent (e) {
// don't redirect with control keys
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) { return }
// don't redirect when preventDefault called
if (e.defaultPrevented) { return }
// don't redirect on right click
if (e.button !== undefined && e.button !== 0) { return }
// don't redirect if `target="_blank"`
if (e.currentTarget && e.currentTarget.getAttribute) {
var target = e.currentTarget.getAttribute('target');
if (/\b_blank\b/i.test(target)) { return }
}
// this may be a Weex event which doesn't have this method
if (e.preventDefault) {
e.preventDefault();
}
return true
}
function findAnchor (children) {
if (children) {
var child;
for (var i = 0; i < children.length; i++) {
child = children[i];
if (child.tag === 'a') {
return child
}
if (child.children && (child = findAnchor(child.children))) {
return child
}
}
}
}
var _Vue;
function install (Vue) {
if (install.installed) { return }
install.installed = true;
_Vue = Vue;
var isDef = function (v) { return v !== undefined; };
var registerInstance = function (vm, callVal) {
var i = vm.$options._parentVnode;
if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
i(vm, callVal);
}
};
Vue.mixin({
beforeCreate: function beforeCreate () {
if (isDef(this.$options.router)) {
this._routerRoot = this;
this._router = this.$options.router;
this._router.init(this);
Vue.util.defineReactive(this, '_route', this._router.history.current);
} else {
this._routerRoot = (this.$parent && this.$parent._routerRoot) || this;
}
registerInstance(this, this);
},
destroyed: function destroyed () {
registerInstance(this);
}
});
Object.defineProperty(Vue.prototype, '$router', {
get: function get () { return this._routerRoot._router }
});
Object.defineProperty(Vue.prototype, '$route', {
get: function get () { return this._routerRoot._route }
});
Vue.component('router-view', View);
Vue.component('router-link', Link);
var strats = Vue.config.optionMergeStrategies;
// use the same hook merging strategy for route hooks
strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created;
}
/* */
var inBrowser = typeof window !== 'undefined';
/* */
function resolvePath (
relative,
base,
append
) {
var firstChar = relative.charAt(0);
if (firstChar === '/') {
return relative
}
if (firstChar === '?' || firstChar === '#') {
return base + relative
}
var stack = base.split('/');
// remove trailing segment if:
// - not appending
// - appending to trailing slash (last segment is empty)
if (!append || !stack[stack.length - 1]) {
stack.pop();
}
// resolve relative path
var segments = relative.replace(/^\//, '').split('/');
for (var i = 0; i < segments.length; i++) {
var segment = segments[i];
if (segment === '..') {
stack.pop();
} else if (segment !== '.') {
stack.push(segment);
}
}
// ensure leading slash
if (stack[0] !== '') {
stack.unshift('');
}
return stack.join('/')
}
function parsePath (path) {
var hash = '';
var query = '';
var hashIndex = path.indexOf('#');
if (hashIndex >= 0) {
hash = path.slice(hashIndex);
path = path.slice(0, hashIndex);
}
var queryIndex = path.indexOf('?');
if (queryIndex >= 0) {
query = path.slice(queryIndex + 1);
path = path.slice(0, queryIndex);
}
return {
path: path,
query: query,
hash: hash
}
}
function cleanPath (path) {
return path.replace(/\/\//g, '/')
}
var index$1 = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
/**
* Expose `pathToRegexp`.
*/
var index = pathToRegexp;
var parse_1 = parse;
var compile_1 = compile;
var tokensToFunction_1 = tokensToFunction;
var tokensToRegExp_1 = tokensToRegExp;
/**
* The main path matching regexp utility.
*
* @type {RegExp}
*/
var PATH_REGEXP = new RegExp([
// Match escaped characters that would otherwise appear in future matches.
// This allows the user to escape special characters that won't transform.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
// "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
'([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
].join('|'), 'g');
/**
* Parse a string for the raw tokens.
*
* @param {string} str
* @param {Object=} options
* @return {!Array}
*/
function parse (str, options) {
var tokens = [];
var key = 0;
var index = 0;
var path = '';
var defaultDelimiter = options && options.delimiter || '/';
var res;
while ((res = PATH_REGEXP.exec(str)) != null) {
var m = res[0];
var escaped = res[1];
var offset = res.index;
path += str.slice(index, offset);
index = offset + m.length;
// Ignore already escaped sequences.
if (escaped) {
path += escaped[1];
continue
}
var next = str[index];
var prefix = res[2];
var name = res[3];
var capture = res[4];
var group = res[5];
var modifier = res[6];
var asterisk = res[7];
// Push the current path onto the tokens.
if (path) {
tokens.push(path);
path = '';
}
var partial = prefix != null && next != null && next !== prefix;
var repeat = modifier === '+' || modifier === '*';
var optional = modifier === '?' || modifier === '*';
var delimiter = res[2] || defaultDelimiter;
var pattern = capture || group;
tokens.push({
name: name || key++,
prefix: prefix || '',
delimiter: delimiter,
optional: optional,
repeat: repeat,
partial: partial,
asterisk: !!asterisk,
pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
});
}
// Match any characters still remaining.
if (index < str.length) {
path += str.substr(index);
}
// If the path exists, push it onto the end.
if (path) {
tokens.push(path);
}
return tokens
}
/**
* Compile a string to a template function for the path.
*
* @param {string} str
* @param {Object=} options
* @return {!function(Object=, Object=)}
*/
function compile (str, options) {
return tokensToFunction(parse(str, options))
}
/**
* Prettier encoding of URI path segments.
*
* @param {string}
* @return {string}
*/
function encodeURIComponentPretty (str) {
return encodeURI(str).replace(/[\/?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
/**
* Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
*
* @param {string}
* @return {string}
*/
function encodeAsterisk (str) {
return encodeURI(str).replace(/[?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
/**
* Expose a method for transforming tokens into the path function.
*/
function tokensToFunction (tokens) {
// Compile all the tokens into regexps.
var matches = new Array(tokens.length);
// Compile all the patterns before compilation.
for (var i = 0; i < tokens.length; i++) {
if (typeof tokens[i] === 'object') {
matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$');
}
}
return function (obj, opts) {
var path = '';
var data = obj || {};
var options = opts || {};
var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === 'string') {
path += token;
continue
}
var value = data[token.name];
var segment;
if (value == null) {
if (token.optional) {
// Prepend partial segment prefixes.
if (token.partial) {
path += token.prefix;
}
continue
} else {
throw new TypeError('Expected "' + token.name + '" to be defined')
}
}
if (index$1(value)) {
if (!token.repeat) {
throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
}
if (value.length === 0) {
if (token.optional) {
continue
} else {
throw new TypeError('Expected "' + token.name + '" to not be empty')
}
}
for (var j = 0; j < value.length; j++) {
segment = encode(value[j]);
if (!matches[i].test(segment)) {
throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
}
path += (j === 0 ? token.prefix : token.delimiter) + segment;
}
continue
}
segment = token.asterisk ? encodeAsterisk(value) : encode(value);
if (!matches[i].test(segment)) {
throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
}
path += token.prefix + segment;
}
return path
}
}
/**
* Escape a regular expression string.
*
* @param {string} str
* @return {string}
*/
function escapeString (str) {
return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1')
}
/**
* Escape the capturing group by escaping special characters and meaning.
*
* @param {string} group
* @return {string}
*/
function escapeGroup (group) {
return group.replace(/([=!:$\/()])/g, '\\$1')
}
/**
* Attach the keys as a property of the regexp.
*
* @param {!RegExp} re
* @param {Array} keys
* @return {!RegExp}
*/
function attachKeys (re, keys) {
re.keys = keys;
return re
}
/**
* Get the flags for a regexp from the options.
*
* @param {Object} options
* @return {string}
*/
function flags (options) {
return options.sensitive ? '' : 'i'
}
/**
* Pull out keys from a regexp.
*
* @param {!RegExp} path
* @param {!Array} keys
* @return {!RegExp}
*/
function regexpToRegexp (path, keys) {
// Use a negative lookahead to match only capturing groups.
var groups = path.source.match(/\((?!\?)/g);
if (groups) {
for (var i = 0; i < groups.length; i++) {
keys.push({
name: i,
prefix: null,
delimiter: null,
optional: false,
repeat: false,
partial: false,
asterisk: false,
pattern: null
});
}
}
return attachKeys(path, keys)
}
/**
* Transform an array into a regexp.
*
* @param {!Array} path
* @param {Array} keys
* @param {!Object} options
* @return {!RegExp}
*/
function arrayToRegexp (path, keys, options) {
var parts = [];
for (var i = 0; i < path.length; i++) {
parts.push(pathToRegexp(path[i], keys, options).source);
}
var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
return attachKeys(regexp, keys)
}
/**
* Create a path regexp from string input.
*
* @param {string} path
* @param {!Array} keys
* @param {!Object} options
* @return {!RegExp}
*/
function stringToRegexp (path, keys, options) {
return tokensToRegExp(parse(path, options), keys, options)
}
/**
* Expose a function for taking tokens and returning a RegExp.
*
* @param {!Array} tokens
* @param {(Array|Object)=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function tokensToRegExp (tokens, keys, options) {
if (!index$1(keys)) {
options = /** @type {!Object} */ (keys || options);
keys = [];
}
options = options || {};
var strict = options.strict;
var end = options.end !== false;
var route = '';
// Iterate over the tokens and create our regexp string.
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === 'string') {
route += escapeString(token);
} else {
var prefix = escapeString(token.prefix);
var capture = '(?:' + token.pattern + ')';
keys.push(token);
if (token.repeat) {
capture += '(?:' + prefix + capture + ')*';
}
if (token.optional) {
if (!token.partial) {
capture = '(?:' + prefix + '(' + capture + '))?';
} else {
capture = prefix + '(' + capture + ')?';
}
} else {
capture = prefix + '(' + capture + ')';
}
route += capture;
}
}
var delimiter = escapeString(options.delimiter || '/');
var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
// In non-strict mode we allow a slash at the end of match. If the path to
// match already ends with a slash, we remove it for consistency. The slash
// is valid at the end of a path match, not in the middle. This is important
// in non-ending mode, where "/test/" shouldn't match "/test//route".
if (!strict) {
route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?';
}
if (end) {
route += '$';
} else {
// In non-ending mode, we need the capturing groups to match as much as
// possible by using a positive lookahead to the end or next path segment.
route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
}
return attachKeys(new RegExp('^' + route, flags(options)), keys)
}
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array can be passed in for the keys, which will hold the
* placeholder key descriptions. For example, using `/user/:id`, `keys` will
* contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
*
* @param {(string|RegExp|Array)} path
* @param {(Array|Object)=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function pathToRegexp (path, keys, options) {
if (!index$1(keys)) {
options = /** @type {!Object} */ (keys || options);
keys = [];
}
options = options || {};
if (path instanceof RegExp) {
return regexpToRegexp(path, /** @type {!Array} */ (keys))
}
if (index$1(path)) {
return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)
}
return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)
}
index.parse = parse_1;
index.compile = compile_1;
index.tokensToFunction = tokensToFunction_1;
index.tokensToRegExp = tokensToRegExp_1;
/* */
var regexpCompileCache = Object.create(null);
function fillParams (
path,
params,
routeMsg
) {
try {
var filler =
regexpCompileCache[path] ||
(regexpCompileCache[path] = index.compile(path));
return filler(params || {}, { pretty: true })
} catch (e) {
if (process.env.NODE_ENV !== 'production') {
warn(false, ("missing param for " + routeMsg + ": " + (e.message)));
}
return ''
}
}
/* */
function createRouteMap (
routes,
oldPathList,
oldPathMap,
oldNameMap
) {
// the path list is used to control path matching priority
var pathList = oldPathList || [];
var pathMap = oldPathMap || Object.create(null);
var nameMap = oldNameMap || Object.create(null);
routes.forEach(function (route) {
addRouteRecord(pathList, pathMap, nameMap, route);
});
// ensure wildcard routes are always at the end
for (var i = 0, l = pathList.length; i < l; i++) {
if (pathList[i] === '*') {
pathList.push(pathList.splice(i, 1)[0]);
l--;
i--;
}
}
return {
pathList: pathList,
pathMap: pathMap,
nameMap: nameMap
}
}
function addRouteRecord (
pathList,
pathMap,
nameMap,
route,
parent,
matchAs
) {
var path = route.path;
var name = route.name;
if (process.env.NODE_ENV !== 'production') {
assert(path != null, "\"path\" is required in a route configuration.");
assert(
typeof route.component !== 'string',
"route config \"component\" for path: " + (String(path || name)) + " cannot be a " +
"string id. Use an actual component instead."
);
}
var normalizedPath = normalizePath(path, parent);
var pathToRegexpOptions = route.pathToRegexpOptions || {};
if (typeof route.caseSensitive === 'boolean') {
pathToRegexpOptions.sensitive = route.caseSensitive;
}
var record = {
path: normalizedPath,
regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
components: route.components || { default: route.component },
instances: {},
name: name,
parent: parent,
matchAs: matchAs,
redirect: route.redirect,
beforeEnter: route.beforeEnter,
meta: route.meta || {},
props: route.props == null
? {}
: route.components
? route.props
: { default: route.props }
};
if (route.children) {
// Warn if route is named, does not redirect and has a default child route.
// If users navigate to this route by name, the default child will
// not be rendered (GH Issue #629)
if (process.env.NODE_ENV !== 'production') {
if (route.name && !route.redirect && route.children.some(function (child) { return /^\/?$/.test(child.path); })) {
warn(
false,
"Named Route '" + (route.name) + "' has a default child route. " +
"When navigating to this named route (:to=\"{name: '" + (route.name) + "'\"), " +
"the default child route will not be rendered. Remove the name from " +
"this route and use the name of the default child route for named " +
"links instead."
);
}
}
route.children.forEach(function (child) {
var childMatchAs = matchAs
? cleanPath((matchAs + "/" + (child.path)))
: undefined;
addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs);
});
}
if (route.alias !== undefined) {
var aliases = Array.isArray(route.alias)
? route.alias
: [route.alias];
aliases.forEach(function (alias) {
var aliasRoute = {
path: alias,
children: route.children
};
addRouteRecord(
pathList,
pathMap,
nameMap,
aliasRoute,
parent,
record.path || '/' // matchAs
);
});
}
if (!pathMap[record.path]) {
pathList.push(record.path);
pathMap[record.path] = record;
}
if (name) {
if (!nameMap[name]) {
nameMap[name] = record;
} else if (process.env.NODE_ENV !== 'production' && !matchAs) {
warn(
false,
"Duplicate named routes definition: " +
"{ name: \"" + name + "\", path: \"" + (record.path) + "\" }"
);
}
}
}
function compileRouteRegex (path, pathToRegexpOptions) {
var regex = index(path, [], pathToRegexpOptions);
if (process.env.NODE_ENV !== 'production') {
var keys = {};
regex.keys.forEach(function (key) {
warn(!keys[key.name], ("Duplicate param keys in route with path: \"" + path + "\""));
keys[key.name] = true;
});
}
return regex
}
function normalizePath (path, parent) {
path = path.replace(/\/$/, '');
if (path[0] === '/') { return path }
if (parent == null) { return path }
return cleanPath(((parent.path) + "/" + path))
}
/* */
function normalizeLocation (
raw,
current,
append,
router
) {
var next = typeof raw === 'string' ? { path: raw } : raw;
// named target
if (next.name || next._normalized) {
return next
}
// relative params
if (!next.path && next.params && current) {
next = assign({}, next);
next._normalized = true;
var params = assign(assign({}, current.params), next.params);
if (current.name) {
next.name = current.name;
next.params = params;
} else if (current.matched.length) {
var rawPath = current.matched[current.matched.length - 1].path;
next.path = fillParams(rawPath, params, ("path " + (current.path)));
} else if (process.env.NODE_ENV !== 'production') {
warn(false, "relative params navigation requires a current route.");
}
return next
}
var parsedPath = parsePath(next.path || '');
var basePath = (current && current.path) || '/';
var path = parsedPath.path
? resolvePath(parsedPath.path, basePath, append || next.append)
: basePath;
var query = resolveQuery(
parsedPath.query,
next.query,
router && router.options.parseQuery
);
var hash = next.hash || parsedPath.hash;
if (hash && hash.charAt(0) !== '#') {
hash = "#" + hash;
}
return {
_normalized: true,
path: path,
query: query,
hash: hash
}
}
function assign (a, b) {
for (var key in b) {
a[key] = b[key];
}
return a
}
/* */
function createMatcher (
routes,
router
) {
var ref = createRouteMap(routes);
var pathList = ref.pathList;
var pathMap = ref.pathMap;
var nameMap = ref.nameMap;
function addRoutes (routes) {
createRouteMap(routes, pathList, pathMap, nameMap);
}
function match (
raw,
currentRoute,
redirectedFrom
) {
var location = normalizeLocation(raw, currentRoute, false, router);
var name = location.name;
if (name) {
var record = nameMap[name];
if (process.env.NODE_ENV !== 'production') {
warn(record, ("Route with name '" + name + "' does not exist"));
}
if (!record) { return _createRoute(null, location) }
var paramNames = record.regex.keys
.filter(function (key) { return !key.optional; })
.map(function (key) { return key.name; });
if (typeof location.params !== 'object') {
location.params = {};
}
if (currentRoute && typeof currentRoute.params === 'object') {
for (var key in currentRoute.params) {
if (!(key in location.params) && paramNames.indexOf(key) > -1) {
location.params[key] = currentRoute.params[key];
}
}
}
if (record) {
location.path = fillParams(record.path, location.params, ("named route \"" + name + "\""));
return _createRoute(record, location, redirectedFrom)
}
} else if (location.path) {
location.params = {};
for (var i = 0; i < pathList.length; i++) {
var path = pathList[i];
var record$1 = pathMap[path];
if (matchRoute(record$1.regex, location.path, location.params)) {
return _createRoute(record$1, location, redirectedFrom)
}
}
}
// no match
return _createRoute(null, location)
}
function redirect (
record,
location
) {
var originalRedirect = record.redirect;
var redirect = typeof originalRedirect === 'function'
? originalRedirect(createRoute(record, location, null, router))
: originalRedirect;
if (typeof redirect === 'string') {
redirect = { path: redirect };
}
if (!redirect || typeof redirect !== 'object') {
if (process.env.NODE_ENV !== 'production') {
warn(
false, ("invalid redirect option: " + (JSON.stringify(redirect)))
);
}
return _createRoute(null, location)
}
var re = redirect;
var name = re.name;
var path = re.path;
var query = location.query;
var hash = location.hash;
var params = location.params;
query = re.hasOwnProperty('query') ? re.query : query;
hash = re.hasOwnProperty('hash') ? re.hash : hash;
params = re.hasOwnProperty('params') ? re.params : params;
if (name) {
// resolved named direct
var targetRecord = nameMap[name];
if (process.env.NODE_ENV !== 'production') {
assert(targetRecord, ("redirect failed: named route \"" + name + "\" not found."));
}
return match({
_normalized: true,
name: name,
query: query,
hash: hash,
params: params
}, undefined, location)
} else if (path) {
// 1. resolve relative redirect
var rawPath = resolveRecordPath(path, record);
// 2. resolve params
var resolvedPath = fillParams(rawPath, params, ("redirect route with path \"" + rawPath + "\""));
// 3. rematch with existing query and hash
return match({
_normalized: true,
path: resolvedPath,
query: query,
hash: hash
}, undefined, location)
} else {
if (process.env.NODE_ENV !== 'production') {
warn(false, ("invalid redirect option: " + (JSON.stringify(redirect))));
}
return _createRoute(null, location)
}
}
function alias (
record,
location,
matchAs
) {
var aliasedPath = fillParams(matchAs, location.params, ("aliased route with path \"" + matchAs + "\""));
var aliasedMatch = match({
_normalized: true,
path: aliasedPath
});
if (aliasedMatch) {
var matched = aliasedMatch.matched;
var aliasedRecord = matched[matched.length - 1];
location.params = aliasedMatch.params;
return _createRoute(aliasedRecord, location)
}
return _createRoute(null, location)
}
function _createRoute (
record,
location,
redirectedFrom
) {
if (record && record.redirect) {
return redirect(record, redirectedFrom || location)
}
if (record && record.matchAs) {
return alias(record, location, record.matchAs)
}
return createRoute(record, location, redirectedFrom, router)
}
return {
match: match,
addRoutes: addRoutes
}
}
function matchRoute (
regex,
path,
params
) {
var m = path.match(regex);
if (!m) {
return false
} else if (!params) {
return true
}
for (var i = 1, len = m.length; i < len; ++i) {
var key = regex.keys[i - 1];
var val = typeof m[i] === 'string' ? decodeURIComponent(m[i]) : m[i];
if (key) {
params[key.name] = val;
}
}
return true
}
function resolveRecordPath (path, record) {
return resolvePath(path, record.parent ? record.parent.path : '/', true)
}
/* */
var positionStore = Object.create(null);
function setupScroll () {
window.addEventListener('popstate', function (e) {
saveScrollPosition();
if (e.state && e.state.key) {
setStateKey(e.state.key);
}
});
}
function handleScroll (
router,
to,
from,
isPop
) {
if (!router.app) {
return
}
var behavior = router.options.scrollBehavior;
if (!behavior) {
return
}
if (process.env.NODE_ENV !== 'production') {
assert(typeof behavior === 'function', "scrollBehavior must be a function");
}
// wait until re-render finishes before scrolling
router.app.$nextTick(function () {
var position = getScrollPosition();
var shouldScroll = behavior(to, from, isPop ? position : null);
if (!shouldScroll) {
return
}
var isObject = typeof shouldScroll === 'object';
if (isObject && typeof shouldScroll.selector === 'string') {
var el = document.querySelector(shouldScroll.selector);
if (el) {
var offset = shouldScroll.offset && typeof shouldScroll.offset === 'object' ? shouldScroll.offset : {};
offset = normalizeOffset(offset);
position = getElementPosition(el, offset);
} else if (isValidPosition(shouldScroll)) {
position = normalizePosition(shouldScroll);
}
} else if (isObject && isValidPosition(shouldScroll)) {
position = normalizePosition(shouldScroll);
}
if (position) {
window.scrollTo(position.x, position.y);
}
});
}
function saveScrollPosition () {
var key = getStateKey();
if (key) {
positionStore[key] = {
x: window.pageXOffset,
y: window.pageYOffset
};
}
}
function getScrollPosition () {
var key = getStateKey();
if (key) {
return positionStore[key]
}
}
function getElementPosition (el, offset) {
var docEl = document.documentElement;
var docRect = docEl.getBoundingClientRect();
var elRect = el.getBoundingClientRect();
return {
x: elRect.left - docRect.left - offset.x,
y: elRect.top - docRect.top - offset.y
}
}
function isValidPosition (obj) {
return isNumber(obj.x) || isNumber(obj.y)
}
function normalizePosition (obj) {
return {
x: isNumber(obj.x) ? obj.x : window.pageXOffset,
y: isNumber(obj.y) ? obj.y : window.pageYOffset
}
}
function normalizeOffset (obj) {
return {
x: isNumber(obj.x) ? obj.x : 0,
y: isNumber(obj.y) ? obj.y : 0
}
}
function isNumber (v) {
return typeof v === 'number'
}
/* */
var supportsPushState = inBrowser && (function () {
var ua = window.navigator.userAgent;
if (
(ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) &&
ua.indexOf('Mobile Safari') !== -1 &&
ua.indexOf('Chrome') === -1 &&
ua.indexOf('Windows Phone') === -1
) {
return false
}
return window.history && 'pushState' in window.history
})();
// use User Timing api (if present) for more accurate key precision
var Time = inBrowser && window.performance && window.performance.now
? window.performance
: Date;
var _key = genKey();
function genKey () {
return Time.now().toFixed(3)
}
function getStateKey () {
return _key
}
function setStateKey (key) {
_key = key;
}
function pushState (url, replace) {
saveScrollPosition();
// try...catch the pushState call to get around Safari
// DOM Exception 18 where it limits to 100 pushState calls
var history = window.history;
try {
if (replace) {
history.replaceState({ key: _key }, '', url);
} else {
_key = genKey();
history.pushState({ key: _key }, '', url);
}
} catch (e) {
window.location[replace ? 'replace' : 'assign'](url);
}
}
function replaceState (url) {
pushState(url, true);
}
/* */
function runQueue (queue, fn, cb) {
var step = function (index) {
if (index >= queue.length) {
cb();
} else {
if (queue[index]) {
fn(queue[index], function () {
step(index + 1);
});
} else {
step(index + 1);
}
}
};
step(0);
}
/* */
function resolveAsyncComponents (matched) {
return function (to, from, next) {
var hasAsync = false;
var pending = 0;
var error = null;
flatMapComponents(matched, function (def, _, match, key) {
// if it's a function and doesn't have cid attached,
// assume it's an async component resolve function.
// we are not using Vue's default async resolving mechanism because
// we want to halt the navigation until the incoming component has been
// resolved.
if (typeof def === 'function' && def.cid === undefined) {
hasAsync = true;
pending++;
var resolve = once(function (resolvedDef) {
if (resolvedDef.__esModule && resolvedDef.default) {
resolvedDef = resolvedDef.default;
}
// save resolved on async factory in case it's used elsewhere
def.resolved = typeof resolvedDef === 'function'
? resolvedDef
: _Vue.extend(resolvedDef);
match.components[key] = resolvedDef;
pending--;
if (pending <= 0) {
next();
}
});
var reject = once(function (reason) {
var msg = "Failed to resolve async component " + key + ": " + reason;
process.env.NODE_ENV !== 'production' && warn(false, msg);
if (!error) {
error = isError(reason)
? reason
: new Error(msg);
next(error);
}
});
var res;
try {
res = def(resolve, reject);
} catch (e) {
reject(e);
}
if (res) {
if (typeof res.then === 'function') {
res.then(resolve, reject);
} else {
// new syntax in Vue 2.3
var comp = res.component;
if (comp && typeof comp.then === 'function') {
comp.then(resolve, reject);
}
}
}
}
});
if (!hasAsync) { next(); }
}
}
function flatMapComponents (
matched,
fn
) {
return flatten(matched.map(function (m) {
return Object.keys(m.components).map(function (key) { return fn(
m.components[key],
m.instances[key],
m, key
); })
}))
}
function flatten (arr) {
return Array.prototype.concat.apply([], arr)
}
// in Webpack 2, require.ensure now also returns a Promise
// so the resolve/reject functions may get called an extra time
// if the user uses an arrow function shorthand that happens to
// return that Promise.
function once (fn) {
var called = false;
return function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
if (called) { return }
called = true;
return fn.apply(this, args)
}
}
/* */
var History = function History (router, base) {
this.router = router;
this.base = normalizeBase(base);
// start with a route object that stands for "nowhere"
this.current = START;
this.pending = null;
this.ready = false;
this.readyCbs = [];
this.readyErrorCbs = [];
this.errorCbs = [];
};
History.prototype.listen = function listen (cb) {
this.cb = cb;
};
History.prototype.onReady = function onReady (cb, errorCb) {
if (this.ready) {
cb();
} else {
this.readyCbs.push(cb);
if (errorCb) {
this.readyErrorCbs.push(errorCb);
}
}
};
History.prototype.onError = function onError (errorCb) {
this.errorCbs.push(errorCb);
};
History.prototype.transitionTo = function transitionTo (location, onComplete, onAbort) {
var this$1 = this;
var route = this.router.match(location, this.current);
this.confirmTransition(route, function () {
this$1.updateRoute(route);
onComplete && onComplete(route);
this$1.ensureURL();
// fire ready cbs once
if (!this$1.ready) {
this$1.ready = true;
this$1.readyCbs.forEach(function (cb) { cb(route); });
}
}, function (err) {
if (onAbort) {
onAbort(err);
}
if (err && !this$1.ready) {
this$1.ready = true;
this$1.readyErrorCbs.forEach(function (cb) { cb(err); });
}
});
};
History.prototype.confirmTransition = function confirmTransition (route, onComplete, onAbort) {
var this$1 = this;
var current = this.current;
var abort = function (err) {
if (isError(err)) {
if (this$1.errorCbs.length) {
this$1.errorCbs.forEach(function (cb) { cb(err); });
} else {
warn(false, 'uncaught error during route navigation:');
console.error(err);
}
}
onAbort && onAbort(err);
};
if (
isSameRoute(route, current) &&
// in the case the route map has been dynamically appended to
route.matched.length === current.matched.length
) {
this.ensureURL();
return abort()
}
var ref = resolveQueue(this.current.matched, route.matched);
var updated = ref.updated;
var deactivated = ref.deactivated;
var activated = ref.activated;
var queue = [].concat(
// in-component leave guards
extractLeaveGuards(deactivated),
// global before hooks
this.router.beforeHooks,
// in-component update hooks
extractUpdateHooks(updated),
// in-config enter guards
activated.map(function (m) { return m.beforeEnter; }),
// async components
resolveAsyncComponents(activated)
);
this.pending = route;
var iterator = function (hook, next) {
if (this$1.pending !== route) {
return abort()
}
try {
hook(route, current, function (to) {
if (to === false || isError(to)) {
// next(false) -> abort navigation, ensure current URL
this$1.ensureURL(true);
abort(to);
} else if (
typeof to === 'string' ||
(typeof to === 'object' && (
typeof to.path === 'string' ||
typeof to.name === 'string'
))
) {
// next('/') or next({ path: '/' }) -> redirect
abort();
if (typeof to === 'object' && to.replace) {
this$1.replace(to);
} else {
this$1.push(to);
}
} else {
// confirm transition and pass on the value
next(to);
}
});
} catch (e) {
abort(e);
}
};
runQueue(queue, iterator, function () {
var postEnterCbs = [];
var isValid = function () { return this$1.current === route; };
// wait until async components are resolved before
// extracting in-component enter guards
var enterGuards = extractEnterGuards(activated, postEnterCbs, isValid);
var queue = enterGuards.concat(this$1.router.resolveHooks);
runQueue(queue, iterator, function () {
if (this$1.pending !== route) {
return abort()
}
this$1.pending = null;
onComplete(route);
if (this$1.router.app) {
this$1.router.app.$nextTick(function () {
postEnterCbs.forEach(function (cb) { cb(); });
});
}
});
});
};
History.prototype.updateRoute = function updateRoute (route) {
var prev = this.current;
this.current = route;
this.cb && this.cb(route);
this.router.afterHooks.forEach(function (hook) {
hook && hook(route, prev);
});
};
function normalizeBase (base) {
if (!base) {
if (inBrowser) {
// respect <base> tag
var baseEl = document.querySelector('base');
base = (baseEl && baseEl.getAttribute('href')) || '/';
// strip full URL origin
base = base.replace(/^https?:\/\/[^\/]+/, '');
} else {
base = '/';
}
}
// make sure there's the starting slash
if (base.charAt(0) !== '/') {
base = '/' + base;
}
// remove trailing slash
return base.replace(/\/$/, '')
}
function resolveQueue (
current,
next
) {
var i;
var max = Math.max(current.length, next.length);
for (i = 0; i < max; i++) {
if (current[i] !== next[i]) {
break
}
}
return {
updated: next.slice(0, i),
activated: next.slice(i),
deactivated: current.slice(i)
}
}
function extractGuards (
records,
name,
bind,
reverse
) {
var guards = flatMapComponents(records, function (def, instance, match, key) {
var guard = extractGuard(def, name);
if (guard) {
return Array.isArray(guard)
? guard.map(function (guard) { return bind(guard, instance, match, key); })
: bind(guard, instance, match, key)
}
});
return flatten(reverse ? guards.reverse() : guards)
}
function extractGuard (
def,
key
) {
if (typeof def !== 'function') {
// extend now so that global mixins are applied.
def = _Vue.extend(def);
}
return def.options[key]
}
function extractLeaveGuards (deactivated) {
return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true)
}
function extractUpdateHooks (updated) {
return extractGuards(updated, 'beforeRouteUpdate', bindGuard)
}
function bindGuard (guard, instance) {
if (instance) {
return function boundRouteGuard () {
return guard.apply(instance, arguments)
}
}
}
function extractEnterGuards (
activated,
cbs,
isValid
) {
return extractGuards(activated, 'beforeRouteEnter', function (guard, _, match, key) {
return bindEnterGuard(guard, match, key, cbs, isValid)
})
}
function bindEnterGuard (
guard,
match,
key,
cbs,
isValid
) {
return function routeEnterGuard (to, from, next) {
return guard(to, from, function (cb) {
next(cb);
if (typeof cb === 'function') {
cbs.push(function () {
// #750
// if a router-view is wrapped with an out-in transition,
// the instance may not have been registered at this time.
// we will need to poll for registration until current route
// is no longer valid.
poll(cb, match.instances, key, isValid);
});
}
})
}
}
function poll (
cb, // somehow flow cannot infer this is a function
instances,
key,
isValid
) {
if (instances[key]) {
cb(instances[key]);
} else if (isValid()) {
setTimeout(function () {
poll(cb, instances, key, isValid);
}, 16);
}
}
/* */
var HTML5History = (function (History$$1) {
function HTML5History (router, base) {
var this$1 = this;
History$$1.call(this, router, base);
var expectScroll = router.options.scrollBehavior;
if (expectScroll) {
setupScroll();
}
window.addEventListener('popstate', function (e) {
var current = this$1.current;
this$1.transitionTo(getLocation(this$1.base), function (route) {
if (expectScroll) {
handleScroll(router, route, current, true);
}
});
});
}
if ( History$$1 ) HTML5History.__proto__ = History$$1;
HTML5History.prototype = Object.create( History$$1 && History$$1.prototype );
HTML5History.prototype.constructor = HTML5History;
HTML5History.prototype.go = function go (n) {
window.history.go(n);
};
HTML5History.prototype.push = function push (location, onComplete, onAbort) {
var this$1 = this;
var ref = this;
var fromRoute = ref.current;
this.transitionTo(location, function (route) {
pushState(cleanPath(this$1.base + route.fullPath));
handleScroll(this$1.router, route, fromRoute, false);
onComplete && onComplete(route);
}, onAbort);
};
HTML5History.prototype.replace = function replace (location, onComplete, onAbort) {
var this$1 = this;
var ref = this;
var fromRoute = ref.current;
this.transitionTo(location, function (route) {
replaceState(cleanPath(this$1.base + route.fullPath));
handleScroll(this$1.router, route, fromRoute, false);
onComplete && onComplete(route);
}, onAbort);
};
HTML5History.prototype.ensureURL = function ensureURL (push) {
if (getLocation(this.base) !== this.current.fullPath) {
var current = cleanPath(this.base + this.current.fullPath);
push ? pushState(current) : replaceState(current);
}
};
HTML5History.prototype.getCurrentLocation = function getCurrentLocation () {
return getLocation(this.base)
};
return HTML5History;
}(History));
function getLocation (base) {
var path = window.location.pathname;
if (base && path.indexOf(base) === 0) {
path = path.slice(base.length);
}
return (path || '/') + window.location.search + window.location.hash
}
/* */
var HashHistory = (function (History$$1) {
function HashHistory (router, base, fallback) {
History$$1.call(this, router, base);
// check history fallback deeplinking
if (fallback && checkFallback(this.base)) {
return
}
ensureSlash();
}
if ( History$$1 ) HashHistory.__proto__ = History$$1;
HashHistory.prototype = Object.create( History$$1 && History$$1.prototype );
HashHistory.prototype.constructor = HashHistory;
// this is delayed until the app mounts
// to avoid the hashchange listener being fired too early
HashHistory.prototype.setupListeners = function setupListeners () {
var this$1 = this;
window.addEventListener('hashchange', function () {
if (!ensureSlash()) {
return
}
this$1.transitionTo(getHash(), function (route) {
replaceHash(route.fullPath);
});
});
};
HashHistory.prototype.push = function push (location, onComplete, onAbort) {
this.transitionTo(location, function (route) {
pushHash(route.fullPath);
onComplete && onComplete(route);
}, onAbort);
};
HashHistory.prototype.replace = function replace (location, onComplete, onAbort) {
this.transitionTo(location, function (route) {
replaceHash(route.fullPath);
onComplete && onComplete(route);
}, onAbort);
};
HashHistory.prototype.go = function go (n) {
window.history.go(n);
};
HashHistory.prototype.ensureURL = function ensureURL (push) {
var current = this.current.fullPath;
if (getHash() !== current) {
push ? pushHash(current) : replaceHash(current);
}
};
HashHistory.prototype.getCurrentLocation = function getCurrentLocation () {
return getHash()
};
return HashHistory;
}(History));
function checkFallback (base) {
var location = getLocation(base);
if (!/^\/#/.test(location)) {
window.location.replace(
cleanPath(base + '/#' + location)
);
return true
}
}
function ensureSlash () {
var path = getHash();
if (path.charAt(0) === '/') {
return true
}
replaceHash('/' + path);
return false
}
function getHash () {
// We can't use window.location.hash here because it's not
// consistent across browsers - Firefox will pre-decode it!
var href = window.location.href;
var index = href.indexOf('#');
return index === -1 ? '' : href.slice(index + 1)
}
function pushHash (path) {
window.location.hash = path;
}
function replaceHash (path) {
var href = window.location.href;
var i = href.indexOf('#');
var base = i >= 0 ? href.slice(0, i) : href;
window.location.replace((base + "#" + path));
}
/* */
var AbstractHistory = (function (History$$1) {
function AbstractHistory (router, base) {
History$$1.call(this, router, base);
this.stack = [];
this.index = -1;
}
if ( History$$1 ) AbstractHistory.__proto__ = History$$1;
AbstractHistory.prototype = Object.create( History$$1 && History$$1.prototype );
AbstractHistory.prototype.constructor = AbstractHistory;
AbstractHistory.prototype.push = function push (location, onComplete, onAbort) {
var this$1 = this;
this.transitionTo(location, function (route) {
this$1.stack = this$1.stack.slice(0, this$1.index + 1).concat(route);
this$1.index++;
onComplete && onComplete(route);
}, onAbort);
};
AbstractHistory.prototype.replace = function replace (location, onComplete, onAbort) {
var this$1 = this;
this.transitionTo(location, function (route) {
this$1.stack = this$1.stack.slice(0, this$1.index).concat(route);
onComplete && onComplete(route);
}, onAbort);
};
AbstractHistory.prototype.go = function go (n) {
var this$1 = this;
var targetIndex = this.index + n;
if (targetIndex < 0 || targetIndex >= this.stack.length) {
return
}
var route = this.stack[targetIndex];
this.confirmTransition(route, function () {
this$1.index = targetIndex;
this$1.updateRoute(route);
});
};
AbstractHistory.prototype.getCurrentLocation = function getCurrentLocation () {
var current = this.stack[this.stack.length - 1];
return current ? current.fullPath : '/'
};
AbstractHistory.prototype.ensureURL = function ensureURL () {
// noop
};
return AbstractHistory;
}(History));
/* */
var VueRouter = function VueRouter (options) {
if ( options === void 0 ) options = {};
this.app = null;
this.apps = [];
this.options = options;
this.beforeHooks = [];
this.resolveHooks = [];
this.afterHooks = [];
this.matcher = createMatcher(options.routes || [], this);
var mode = options.mode || 'hash';
this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false;
if (this.fallback) {
mode = 'hash';
}
if (!inBrowser) {
mode = 'abstract';
}
this.mode = mode;
switch (mode) {
case 'history':
this.history = new HTML5History(this, options.base);
break
case 'hash':
this.history = new HashHistory(this, options.base, this.fallback);
break
case 'abstract':
this.history = new AbstractHistory(this, options.base);
break
default:
if (process.env.NODE_ENV !== 'production') {
assert(false, ("invalid mode: " + mode));
}
}
};
var prototypeAccessors = { currentRoute: {} };
VueRouter.prototype.match = function match (
raw,
current,
redirectedFrom
) {
return this.matcher.match(raw, current, redirectedFrom)
};
prototypeAccessors.currentRoute.get = function () {
return this.history && this.history.current
};
VueRouter.prototype.init = function init (app /* Vue component instance */) {
var this$1 = this;
process.env.NODE_ENV !== 'production' && assert(
install.installed,
"not installed. Make sure to call `Vue.use(VueRouter)` " +
"before creating root instance."
);
this.apps.push(app);
// main app already initialized.
if (this.app) {
return
}
this.app = app;
var history = this.history;
if (history instanceof HTML5History) {
history.transitionTo(history.getCurrentLocation());
} else if (history instanceof HashHistory) {
var setupHashListener = function () {
history.setupListeners();
};
history.transitionTo(
history.getCurrentLocation(),
setupHashListener,
setupHashListener
);
}
history.listen(function (route) {
this$1.apps.forEach(function (app) {
app._route = route;
});
});
};
VueRouter.prototype.beforeEach = function beforeEach (fn) {
return registerHook(this.beforeHooks, fn)
};
VueRouter.prototype.beforeResolve = function beforeResolve (fn) {
return registerHook(this.resolveHooks, fn)
};
VueRouter.prototype.afterEach = function afterEach (fn) {
return registerHook(this.afterHooks, fn)
};
VueRouter.prototype.onReady = function onReady (cb, errorCb) {
this.history.onReady(cb, errorCb);
};
VueRouter.prototype.onError = function onError (errorCb) {
this.history.onError(errorCb);
};
VueRouter.prototype.push = function push (location, onComplete, onAbort) {
this.history.push(location, onComplete, onAbort);
};
VueRouter.prototype.replace = function replace (location, onComplete, onAbort) {
this.history.replace(location, onComplete, onAbort);
};
VueRouter.prototype.go = function go (n) {
this.history.go(n);
};
VueRouter.prototype.back = function back () {
this.go(-1);
};
VueRouter.prototype.forward = function forward () {
this.go(1);
};
VueRouter.prototype.getMatchedComponents = function getMatchedComponents (to) {
var route = to
? to.matched
? to
: this.resolve(to).route
: this.currentRoute;
if (!route) {
return []
}
return [].concat.apply([], route.matched.map(function (m) {
return Object.keys(m.components).map(function (key) {
return m.components[key]
})
}))
};
VueRouter.prototype.resolve = function resolve (
to,
current,
append
) {
var location = normalizeLocation(
to,
current || this.history.current,
append,
this
);
var route = this.match(location, current);
var fullPath = route.redirectedFrom || route.fullPath;
var base = this.history.base;
var href = createHref(base, fullPath, this.mode);
return {
location: location,
route: route,
href: href,
// for backwards compat
normalizedTo: location,
resolved: route
}
};
VueRouter.prototype.addRoutes = function addRoutes (routes) {
this.matcher.addRoutes(routes);
if (this.history.current !== START) {
this.history.transitionTo(this.history.getCurrentLocation());
}
};
Object.defineProperties( VueRouter.prototype, prototypeAccessors );
function registerHook (list, fn) {
list.push(fn);
return function () {
var i = list.indexOf(fn);
if (i > -1) { list.splice(i, 1); }
}
}
function createHref (base, fullPath, mode) {
var path = mode === 'hash' ? '#' + fullPath : fullPath;
return base ? cleanPath(base + '/' + path) : path
}
VueRouter.install = install;
VueRouter.version = '2.7.0';
if (inBrowser && window.Vue) {
window.Vue.use(VueRouter);
}
/* harmony default export */ __webpack_exports__["default"] = (VueRouter);
/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(0)))
/***/ }),
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* WEBPACK VAR INJECTION */(function(process, global) {/*!
* Vue.js v2.3.4
* (c) 2014-2017 Evan You
* Released under the MIT License.
*/
/* */
// these helpers produces better vm code in JS engines due to their
// explicitness and function inlining
function isUndef (v) {
return v === undefined || v === null
}
function isDef (v) {
return v !== undefined && v !== null
}
function isTrue (v) {
return v === true
}
function isFalse (v) {
return v === false
}
/**
* Check if value is primitive
*/
function isPrimitive (value) {
return typeof value === 'string' || typeof value === 'number'
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
var _toString = Object.prototype.toString;
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
function isPlainObject (obj) {
return _toString.call(obj) === '[object Object]'
}
function isRegExp (v) {
return _toString.call(v) === '[object RegExp]'
}
/**
* Convert a value to a string that is actually rendered.
*/
function toString (val) {
return val == null
? ''
: typeof val === 'object'
? JSON.stringify(val, null, 2)
: String(val)
}
/**
* Convert a input value to a number for persistence.
* If the conversion fails, return original string.
*/
function toNumber (val) {
var n = parseFloat(val);
return isNaN(n) ? val : n
}
/**
* Make a map and return a function for checking if a key
* is in that map.
*/
function makeMap (
str,
expectsLowerCase
) {
var map = Object.create(null);
var list = str.split(',');
for (var i = 0; i < list.length; i++) {
map[list[i]] = true;
}
return expectsLowerCase
? function (val) { return map[val.toLowerCase()]; }
: function (val) { return map[val]; }
}
/**
* Check if a tag is a built-in tag.
*/
var isBuiltInTag = makeMap('slot,component', true);
/**
* Remove an item from an array
*/
function remove (arr, item) {
if (arr.length) {
var index = arr.indexOf(item);
if (index > -1) {
return arr.splice(index, 1)
}
}
}
/**
* Check whether the object has the property.
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
/**
* Create a cached version of a pure function.
*/
function cached (fn) {
var cache = Object.create(null);
return (function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
})
}
/**
* Camelize a hyphen-delimited string.
*/
var camelizeRE = /-(\w)/g;
var camelize = cached(function (str) {
return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
});
/**
* Capitalize a string.
*/
var capitalize = cached(function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
});
/**
* Hyphenate a camelCase string.
*/
var hyphenateRE = /([^-])([A-Z])/g;
var hyphenate = cached(function (str) {
return str
.replace(hyphenateRE, '$1-$2')
.replace(hyphenateRE, '$1-$2')
.toLowerCase()
});
/**
* Simple bind, faster than native
*/
function bind (fn, ctx) {
function boundFn (a) {
var l = arguments.length;
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
// record original fn length
boundFn._length = fn.length;
return boundFn
}
/**
* Convert an Array-like object to a real Array.
*/
function toArray (list, start) {
start = start || 0;
var i = list.length - start;
var ret = new Array(i);
while (i--) {
ret[i] = list[i + start];
}
return ret
}
/**
* Mix properties into target object.
*/
function extend (to, _from) {
for (var key in _from) {
to[key] = _from[key];
}
return to
}
/**
* Merge an Array of Objects into a single Object.
*/
function toObject (arr) {
var res = {};
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i]);
}
}
return res
}
/**
* Perform no operation.
*/
function noop () {}
/**
* Always return false.
*/
var no = function () { return false; };
/**
* Return same value
*/
var identity = function (_) { return _; };
/**
* Generate a static keys string from compiler modules.
*/
function genStaticKeys (modules) {
return modules.reduce(function (keys, m) {
return keys.concat(m.staticKeys || [])
}, []).join(',')
}
/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
*/
function looseEqual (a, b) {
var isObjectA = isObject(a);
var isObjectB = isObject(b);
if (isObjectA && isObjectB) {
try {
return JSON.stringify(a) === JSON.stringify(b)
} catch (e) {
// possible circular reference
return a === b
}
} else if (!isObjectA && !isObjectB) {
return String(a) === String(b)
} else {
return false
}
}
function looseIndexOf (arr, val) {
for (var i = 0; i < arr.length; i++) {
if (looseEqual(arr[i], val)) { return i }
}
return -1
}
/**
* Ensure a function is called only once.
*/
function once (fn) {
var called = false;
return function () {
if (!called) {
called = true;
fn.apply(this, arguments);
}
}
}
var SSR_ATTR = 'data-server-rendered';
var ASSET_TYPES = [
'component',
'directive',
'filter'
];
var LIFECYCLE_HOOKS = [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
'activated',
'deactivated'
];
/* */
var config = ({
/**
* Option merge strategies (used in core/util/options)
*/
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Show production mode tip message on boot?
*/
productionTip: process.env.NODE_ENV !== 'production',
/**
* Whether to enable devtools
*/
devtools: process.env.NODE_ENV !== 'production',
/**
* Whether to record perf
*/
performance: false,
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: [],
/**
* Custom user key aliases for v-on
*/
keyCodes: Object.create(null),
/**
* Check if a tag is reserved so that it cannot be registered as a
* component. This is platform-dependent and may be overwritten.
*/
isReservedTag: no,
/**
* Check if an attribute is reserved so that it cannot be used as a component
* prop. This is platform-dependent and may be overwritten.
*/
isReservedAttr: no,
/**
* Check if a tag is an unknown element.
* Platform-dependent.
*/
isUnknownElement: no,
/**
* Get the namespace of an element
*/
getTagNamespace: noop,
/**
* Parse the real tag name for the specific platform.
*/
parsePlatformTagName: identity,
/**
* Check if an attribute must be bound using property, e.g. value
* Platform-dependent.
*/
mustUseProp: no,
/**
* Exposed for legacy reasons
*/
_lifecycleHooks: LIFECYCLE_HOOKS
});
/* */
var emptyObject = Object.freeze({});
/**
* Check if a string starts with $ or _
*/
function isReserved (str) {
var c = (str + '').charCodeAt(0);
return c === 0x24 || c === 0x5F
}
/**
* Define a property.
*/
function def (obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
});
}
/**
* Parse simple path.
*/
var bailRE = /[^\w.$]/;
function parsePath (path) {
if (bailRE.test(path)) {
return
}
var segments = path.split('.');
return function (obj) {
for (var i = 0; i < segments.length; i++) {
if (!obj) { return }
obj = obj[segments[i]];
}
return obj
}
}
/* */
var warn = noop;
var tip = noop;
var formatComponentName = (null); // work around flow check
if (process.env.NODE_ENV !== 'production') {
var hasConsole = typeof console !== 'undefined';
var classifyRE = /(?:^|[-_])(\w)/g;
var classify = function (str) { return str
.replace(classifyRE, function (c) { return c.toUpperCase(); })
.replace(/[-_]/g, ''); };
warn = function (msg, vm) {
if (hasConsole && (!config.silent)) {
console.error("[Vue warn]: " + msg + (
vm ? generateComponentTrace(vm) : ''
));
}
};
tip = function (msg, vm) {
if (hasConsole && (!config.silent)) {
console.warn("[Vue tip]: " + msg + (
vm ? generateComponentTrace(vm) : ''
));
}
};
formatComponentName = function (vm, includeFile) {
if (vm.$root === vm) {
return '<Root>'
}
var name = typeof vm === 'string'
? vm
: typeof vm === 'function' && vm.options
? vm.options.name
: vm._isVue
? vm.$options.name || vm.$options._componentTag
: vm.name;
var file = vm._isVue && vm.$options.__file;
if (!name && file) {
var match = file.match(/([^/\\]+)\.vue$/);
name = match && match[1];
}
return (
(name ? ("<" + (classify(name)) + ">") : "<Anonymous>") +
(file && includeFile !== false ? (" at " + file) : '')
)
};
var repeat = function (str, n) {
var res = '';
while (n) {
if (n % 2 === 1) { res += str; }
if (n > 1) { str += str; }
n >>= 1;
}
return res
};
var generateComponentTrace = function (vm) {
if (vm._isVue && vm.$parent) {
var tree = [];
var currentRecursiveSequence = 0;
while (vm) {
if (tree.length > 0) {
var last = tree[tree.length - 1];
if (last.constructor === vm.constructor) {
currentRecursiveSequence++;
vm = vm.$parent;
continue
} else if (currentRecursiveSequence > 0) {
tree[tree.length - 1] = [last, currentRecursiveSequence];
currentRecursiveSequence = 0;
}
}
tree.push(vm);
vm = vm.$parent;
}
return '\n\nfound in\n\n' + tree
.map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm)
? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)")
: formatComponentName(vm))); })
.join('\n')
} else {
return ("\n\n(found in " + (formatComponentName(vm)) + ")")
}
};
}
/* */
function handleError (err, vm, info) {
if (config.errorHandler) {
config.errorHandler.call(null, err, vm, info);
} else {
if (process.env.NODE_ENV !== 'production') {
warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm);
}
/* istanbul ignore else */
if (inBrowser && typeof console !== 'undefined') {
console.error(err);
} else {
throw err
}
}
}
/* */
/* globals MutationObserver */
// can we use __proto__?
var hasProto = '__proto__' in {};
// Browser environment sniffing
var inBrowser = typeof window !== 'undefined';
var UA = inBrowser && window.navigator.userAgent.toLowerCase();
var isIE = UA && /msie|trident/.test(UA);
var isIE9 = UA && UA.indexOf('msie 9.0') > 0;
var isEdge = UA && UA.indexOf('edge/') > 0;
var isAndroid = UA && UA.indexOf('android') > 0;
var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);
var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
var supportsPassive = false;
if (inBrowser) {
try {
var opts = {};
Object.defineProperty(opts, 'passive', ({
get: function get () {
/* istanbul ignore next */
supportsPassive = true;
}
} )); // https://github.com/facebook/flow/issues/285
window.addEventListener('test-passive', null, opts);
} catch (e) {}
}
// this needs to be lazy-evaled because vue may be required before
// vue-server-renderer can set VUE_ENV
var _isServer;
var isServerRendering = function () {
if (_isServer === undefined) {
/* istanbul ignore if */
if (!inBrowser && typeof global !== 'undefined') {
// detect presence of vue-server-renderer and avoid
// Webpack shimming the process
_isServer = global['process'].env.VUE_ENV === 'server';
} else {
_isServer = false;
}
}
return _isServer
};
// detect devtools
var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
/* istanbul ignore next */
function isNative (Ctor) {
return typeof Ctor === 'function' && /native code/.test(Ctor.toString())
}
var hasSymbol =
typeof Symbol !== 'undefined' && isNative(Symbol) &&
typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys);
/**
* Defer a task to execute it asynchronously.
*/
var nextTick = (function () {
var callbacks = [];
var pending = false;
var timerFunc;
function nextTickHandler () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
// the nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore if */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve();
var logError = function (err) { console.error(err); };
timerFunc = function () {
p.then(nextTickHandler).catch(logError);
// in problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) { setTimeout(noop); }
};
} else if (typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// use MutationObserver where native Promise is not available,
// e.g. PhantomJS IE11, iOS7, Android 4.4
var counter = 1;
var observer = new MutationObserver(nextTickHandler);
var textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true
});
timerFunc = function () {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
} else {
// fallback to setTimeout
/* istanbul ignore next */
timerFunc = function () {
setTimeout(nextTickHandler, 0);
};
}
return function queueNextTick (cb, ctx) {
var _resolve;
callbacks.push(function () {
if (cb) {
try {
cb.call(ctx);
} catch (e) {
handleError(e, ctx, 'nextTick');
}
} else if (_resolve) {
_resolve(ctx);
}
});
if (!pending) {
pending = true;
timerFunc();
}
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function (resolve, reject) {
_resolve = resolve;
})
}
}
})();
var _Set;
/* istanbul ignore if */
if (typeof Set !== 'undefined' && isNative(Set)) {
// use native Set when available.
_Set = Set;
} else {
// a non-standard Set polyfill that only works with primitive keys.
_Set = (function () {
function Set () {
this.set = Object.create(null);
}
Set.prototype.has = function has (key) {
return this.set[key] === true
};
Set.prototype.add = function add (key) {
this.set[key] = true;
};
Set.prototype.clear = function clear () {
this.set = Object.create(null);
};
return Set;
}());
}
/* */
var uid = 0;
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
var Dep = function Dep () {
this.id = uid++;
this.subs = [];
};
Dep.prototype.addSub = function addSub (sub) {
this.subs.push(sub);
};
Dep.prototype.removeSub = function removeSub (sub) {
remove(this.subs, sub);
};
Dep.prototype.depend = function depend () {
if (Dep.target) {
Dep.target.addDep(this);
}
};
Dep.prototype.notify = function notify () {
// stabilize the subscriber list first
var subs = this.subs.slice();
for (var i = 0, l = subs.length; i < l; i++) {
subs[i].update();
}
};
// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null;
var targetStack = [];
function pushTarget (_target) {
if (Dep.target) { targetStack.push(Dep.target); }
Dep.target = _target;
}
function popTarget () {
Dep.target = targetStack.pop();
}
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/
var arrayProto = Array.prototype;
var arrayMethods = Object.create(arrayProto);[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.forEach(function (method) {
// cache original method
var original = arrayProto[method];
def(arrayMethods, method, function mutator () {
var arguments$1 = arguments;
// avoid leaking arguments:
// http://jsperf.com/closure-with-arguments
var i = arguments.length;
var args = new Array(i);
while (i--) {
args[i] = arguments$1[i];
}
var result = original.apply(this, args);
var ob = this.__ob__;
var inserted;
switch (method) {
case 'push':
inserted = args;
break
case 'unshift':
inserted = args;
break
case 'splice':
inserted = args.slice(2);
break
}
if (inserted) { ob.observeArray(inserted); }
// notify change
ob.dep.notify();
return result
});
});
/* */
var arrayKeys = Object.getOwnPropertyNames(arrayMethods);
/**
* By default, when a reactive property is set, the new value is
* also converted to become reactive. However when passing down props,
* we don't want to force conversion because the value may be a nested value
* under a frozen data structure. Converting it would defeat the optimization.
*/
var observerState = {
shouldConvert: true,
isSettingProps: false
};
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*/
var Observer = function Observer (value) {
this.value = value;
this.dep = new Dep();
this.vmCount = 0;
def(value, '__ob__', this);
if (Array.isArray(value)) {
var augment = hasProto
? protoAugment
: copyAugment;
augment(value, arrayMethods, arrayKeys);
this.observeArray(value);
} else {
this.walk(value);
}
};
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
Observer.prototype.walk = function walk (obj) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
defineReactive$$1(obj, keys[i], obj[keys[i]]);
}
};
/**
* Observe a list of Array items.
*/
Observer.prototype.observeArray = function observeArray (items) {
for (var i = 0, l = items.length; i < l; i++) {
observe(items[i]);
}
};
// helpers
/**
* Augment an target Object or Array by intercepting
* the prototype chain using __proto__
*/
function protoAugment (target, src) {
/* eslint-disable no-proto */
target.__proto__ = src;
/* eslint-enable no-proto */
}
/**
* Augment an target Object or Array by defining
* hidden properties.
*/
/* istanbul ignore next */
function copyAugment (target, src, keys) {
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i];
def(target, key, src[key]);
}
}
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/
function observe (value, asRootData) {
if (!isObject(value)) {
return
}
var ob;
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__;
} else if (
observerState.shouldConvert &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value);
}
if (asRootData && ob) {
ob.vmCount++;
}
return ob
}
/**
* Define a reactive property on an Object.
*/
function defineReactive$$1 (
obj,
key,
val,
customSetter
) {
var dep = new Dep();
var property = Object.getOwnPropertyDescriptor(obj, key);
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
var getter = property && property.get;
var setter = property && property.set;
var childOb = observe(val);
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
var value = getter ? getter.call(obj) : val;
if (Dep.target) {
dep.depend();
if (childOb) {
childOb.dep.depend();
}
if (Array.isArray(value)) {
dependArray(value);
}
}
return value
},
set: function reactiveSetter (newVal) {
var value = getter ? getter.call(obj) : val;
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter();
}
if (setter) {
setter.call(obj, newVal);
} else {
val = newVal;
}
childOb = observe(newVal);
dep.notify();
}
});
}
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
function set (target, key, val) {
if (Array.isArray(target) && typeof key === 'number') {
target.length = Math.max(target.length, key);
target.splice(key, 1, val);
return val
}
if (hasOwn(target, key)) {
target[key] = val;
return val
}
var ob = (target ).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
);
return val
}
if (!ob) {
target[key] = val;
return val
}
defineReactive$$1(ob.value, key, val);
ob.dep.notify();
return val
}
/**
* Delete a property and trigger change if necessary.
*/
function del (target, key) {
if (Array.isArray(target) && typeof key === 'number') {
target.splice(key, 1);
return
}
var ob = (target ).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid deleting properties on a Vue instance or its root $data ' +
'- just set it to null.'
);
return
}
if (!hasOwn(target, key)) {
return
}
delete target[key];
if (!ob) {
return
}
ob.dep.notify();
}
/**
* Collect dependencies on array elements when the array is touched, since
* we cannot intercept array element access like property getters.
*/
function dependArray (value) {
for (var e = (void 0), i = 0, l = value.length; i < l; i++) {
e = value[i];
e && e.__ob__ && e.__ob__.dep.depend();
if (Array.isArray(e)) {
dependArray(e);
}
}
}
/* */
/**
* Option overwriting strategies are functions that handle
* how to merge a parent option value and a child option
* value into the final value.
*/
var strats = config.optionMergeStrategies;
/**
* Options with restrictions
*/
if (process.env.NODE_ENV !== 'production') {
strats.el = strats.propsData = function (parent, child, vm, key) {
if (!vm) {
warn(
"option \"" + key + "\" can only be used during instance " +
'creation with the `new` keyword.'
);
}
return defaultStrat(parent, child)
};
}
/**
* Helper that recursively merges two data objects together.
*/
function mergeData (to, from) {
if (!from) { return to }
var key, toVal, fromVal;
var keys = Object.keys(from);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
toVal = to[key];
fromVal = from[key];
if (!hasOwn(to, key)) {
set(to, key, fromVal);
} else if (isPlainObject(toVal) && isPlainObject(fromVal)) {
mergeData(toVal, fromVal);
}
}
return to
}
/**
* Data
*/
strats.data = function (
parentVal,
childVal,
vm
) {
if (!vm) {
// in a Vue.extend merge, both should be functions
if (!childVal) {
return parentVal
}
if (typeof childVal !== 'function') {
process.env.NODE_ENV !== 'production' && warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
);
return parentVal
}
if (!parentVal) {
return childVal
}
// when parentVal & childVal are both present,
// we need to return a function that returns the
// merged result of both functions... no need to
// check if parentVal is a function here because
// it has to be a function to pass previous merges.
return function mergedDataFn () {
return mergeData(
childVal.call(this),
parentVal.call(this)
)
}
} else if (parentVal || childVal) {
return function mergedInstanceDataFn () {
// instance merge
var instanceData = typeof childVal === 'function'
? childVal.call(vm)
: childVal;
var defaultData = typeof parentVal === 'function'
? parentVal.call(vm)
: undefined;
if (instanceData) {
return mergeData(instanceData, defaultData)
} else {
return defaultData
}
}
}
};
/**
* Hooks and props are merged as arrays.
*/
function mergeHook (
parentVal,
childVal
) {
return childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal
}
LIFECYCLE_HOOKS.forEach(function (hook) {
strats[hook] = mergeHook;
});
/**
* Assets
*
* When a vm is present (instance creation), we need to do
* a three-way merge between constructor options, instance
* options and parent options.
*/
function mergeAssets (parentVal, childVal) {
var res = Object.create(parentVal || null);
return childVal
? extend(res, childVal)
: res
}
ASSET_TYPES.forEach(function (type) {
strats[type + 's'] = mergeAssets;
});
/**
* Watchers.
*
* Watchers hashes should not overwrite one
* another, so we merge them as arrays.
*/
strats.watch = function (parentVal, childVal) {
/* istanbul ignore if */
if (!childVal) { return Object.create(parentVal || null) }
if (!parentVal) { return childVal }
var ret = {};
extend(ret, parentVal);
for (var key in childVal) {
var parent = ret[key];
var child = childVal[key];
if (parent && !Array.isArray(parent)) {
parent = [parent];
}
ret[key] = parent
? parent.concat(child)
: [child];
}
return ret
};
/**
* Other object hashes.
*/
strats.props =
strats.methods =
strats.computed = function (parentVal, childVal) {
if (!childVal) { return Object.create(parentVal || null) }
if (!parentVal) { return childVal }
var ret = Object.create(null);
extend(ret, parentVal);
extend(ret, childVal);
return ret
};
/**
* Default strategy.
*/
var defaultStrat = function (parentVal, childVal) {
return childVal === undefined
? parentVal
: childVal
};
/**
* Validate component names
*/
function checkComponents (options) {
for (var key in options.components) {
var lower = key.toLowerCase();
if (isBuiltInTag(lower) || config.isReservedTag(lower)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + key
);
}
}
}
/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
function normalizeProps (options) {
var props = options.props;
if (!props) { return }
var res = {};
var i, val, name;
if (Array.isArray(props)) {
i = props.length;
while (i--) {
val = props[i];
if (typeof val === 'string') {
name = camelize(val);
res[name] = { type: null };
} else if (process.env.NODE_ENV !== 'production') {
warn('props must be strings when using array syntax.');
}
}
} else if (isPlainObject(props)) {
for (var key in props) {
val = props[key];
name = camelize(key);
res[name] = isPlainObject(val)
? val
: { type: val };
}
}
options.props = res;
}
/**
* Normalize raw function directives into object format.
*/
function normalizeDirectives (options) {
var dirs = options.directives;
if (dirs) {
for (var key in dirs) {
var def = dirs[key];
if (typeof def === 'function') {
dirs[key] = { bind: def, update: def };
}
}
}
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
function mergeOptions (
parent,
child,
vm
) {
if (process.env.NODE_ENV !== 'production') {
checkComponents(child);
}
if (typeof child === 'function') {
child = child.options;
}
normalizeProps(child);
normalizeDirectives(child);
var extendsFrom = child.extends;
if (extendsFrom) {
parent = mergeOptions(parent, extendsFrom, vm);
}
if (child.mixins) {
for (var i = 0, l = child.mixins.length; i < l; i++) {
parent = mergeOptions(parent, child.mixins[i], vm);
}
}
var options = {};
var key;
for (key in parent) {
mergeField(key);
}
for (key in child) {
if (!hasOwn(parent, key)) {
mergeField(key);
}
}
function mergeField (key) {
var strat = strats[key] || defaultStrat;
options[key] = strat(parent[key], child[key], vm, key);
}
return options
}
/**
* Resolve an asset.
* This function is used because child instances need access
* to assets defined in its ancestor chain.
*/
function resolveAsset (
options,
type,
id,
warnMissing
) {
/* istanbul ignore if */
if (typeof id !== 'string') {
return
}
var assets = options[type];
// check local registration variations first
if (hasOwn(assets, id)) { return assets[id] }
var camelizedId = camelize(id);
if (hasOwn(assets, camelizedId)) { return assets[camelizedId] }
var PascalCaseId = capitalize(camelizedId);
if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] }
// fallback to prototype chain
var res = assets[id] || assets[camelizedId] || assets[PascalCaseId];
if (process.env.NODE_ENV !== 'production' && warnMissing && !res) {
warn(
'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
options
);
}
return res
}
/* */
function validateProp (
key,
propOptions,
propsData,
vm
) {
var prop = propOptions[key];
var absent = !hasOwn(propsData, key);
var value = propsData[key];
// handle boolean props
if (isType(Boolean, prop.type)) {
if (absent && !hasOwn(prop, 'default')) {
value = false;
} else if (!isType(String, prop.type) && (value === '' || value === hyphenate(key))) {
value = true;
}
}
// check default value
if (value === undefined) {
value = getPropDefaultValue(vm, prop, key);
// since the default value is a fresh copy,
// make sure to observe it.
var prevShouldConvert = observerState.shouldConvert;
observerState.shouldConvert = true;
observe(value);
observerState.shouldConvert = prevShouldConvert;
}
if (process.env.NODE_ENV !== 'production') {
assertProp(prop, key, value, vm, absent);
}
return value
}
/**
* Get the default value of a prop.
*/
function getPropDefaultValue (vm, prop, key) {
// no default, return undefined
if (!hasOwn(prop, 'default')) {
return undefined
}
var def = prop.default;
// warn against non-factory defaults for Object & Array
if (process.env.NODE_ENV !== 'production' && isObject(def)) {
warn(
'Invalid default value for prop "' + key + '": ' +
'Props with type Object/Array must use a factory function ' +
'to return the default value.',
vm
);
}
// the raw prop value was also undefined from previous render,
// return previous default value to avoid unnecessary watcher trigger
if (vm && vm.$options.propsData &&
vm.$options.propsData[key] === undefined &&
vm._props[key] !== undefined
) {
return vm._props[key]
}
// call factory function for non-Function types
// a value is Function if its prototype is function even across different execution context
return typeof def === 'function' && getType(prop.type) !== 'Function'
? def.call(vm)
: def
}
/**
* Assert whether a prop is valid.
*/
function assertProp (
prop,
name,
value,
vm,
absent
) {
if (prop.required && absent) {
warn(
'Missing required prop: "' + name + '"',
vm
);
return
}
if (value == null && !prop.required) {
return
}
var type = prop.type;
var valid = !type || type === true;
var expectedTypes = [];
if (type) {
if (!Array.isArray(type)) {
type = [type];
}
for (var i = 0; i < type.length && !valid; i++) {
var assertedType = assertType(value, type[i]);
expectedTypes.push(assertedType.expectedType || '');
valid = assertedType.valid;
}
}
if (!valid) {
warn(
'Invalid prop: type check failed for prop "' + name + '".' +
' Expected ' + expectedTypes.map(capitalize).join(', ') +
', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.',
vm
);
return
}
var validator = prop.validator;
if (validator) {
if (!validator(value)) {
warn(
'Invalid prop: custom validator check failed for prop "' + name + '".',
vm
);
}
}
}
var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/;
function assertType (value, type) {
var valid;
var expectedType = getType(type);
if (simpleCheckRE.test(expectedType)) {
valid = typeof value === expectedType.toLowerCase();
} else if (expectedType === 'Object') {
valid = isPlainObject(value);
} else if (expectedType === 'Array') {
valid = Array.isArray(value);
} else {
valid = value instanceof type;
}
return {
valid: valid,
expectedType: expectedType
}
}
/**
* Use function string name to check built-in types,
* because a simple equality check will fail when running
* across different vms / iframes.
*/
function getType (fn) {
var match = fn && fn.toString().match(/^\s*function (\w+)/);
return match ? match[1] : ''
}
function isType (type, fn) {
if (!Array.isArray(fn)) {
return getType(fn) === getType(type)
}
for (var i = 0, len = fn.length; i < len; i++) {
if (getType(fn[i]) === getType(type)) {
return true
}
}
/* istanbul ignore next */
return false
}
/* */
var mark;
var measure;
if (process.env.NODE_ENV !== 'production') {
var perf = inBrowser && window.performance;
/* istanbul ignore if */
if (
perf &&
perf.mark &&
perf.measure &&
perf.clearMarks &&
perf.clearMeasures
) {
mark = function (tag) { return perf.mark(tag); };
measure = function (name, startTag, endTag) {
perf.measure(name, startTag, endTag);
perf.clearMarks(startTag);
perf.clearMarks(endTag);
perf.clearMeasures(name);
};
}
}
/* not type checking this file because flow doesn't play well with Proxy */
var initProxy;
if (process.env.NODE_ENV !== 'production') {
var allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
);
var warnNonPresent = function (target, key) {
warn(
"Property or method \"" + key + "\" is not defined on the instance but " +
"referenced during render. Make sure to declare reactive data " +
"properties in the data option.",
target
);
};
var hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/);
if (hasProxy) {
var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta');
config.keyCodes = new Proxy(config.keyCodes, {
set: function set (target, key, value) {
if (isBuiltInModifier(key)) {
warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key));
return false
} else {
target[key] = value;
return true
}
}
});
}
var hasHandler = {
has: function has (target, key) {
var has = key in target;
var isAllowed = allowedGlobals(key) || key.charAt(0) === '_';
if (!has && !isAllowed) {
warnNonPresent(target, key);
}
return has || !isAllowed
}
};
var getHandler = {
get: function get (target, key) {
if (typeof key === 'string' && !(key in target)) {
warnNonPresent(target, key);
}
return target[key]
}
};
initProxy = function initProxy (vm) {
if (hasProxy) {
// determine which proxy handler to use
var options = vm.$options;
var handlers = options.render && options.render._withStripped
? getHandler
: hasHandler;
vm._renderProxy = new Proxy(vm, handlers);
} else {
vm._renderProxy = vm;
}
};
}
/* */
var VNode = function VNode (
tag,
data,
children,
text,
elm,
context,
componentOptions
) {
this.tag = tag;
this.data = data;
this.children = children;
this.text = text;
this.elm = elm;
this.ns = undefined;
this.context = context;
this.functionalContext = undefined;
this.key = data && data.key;
this.componentOptions = componentOptions;
this.componentInstance = undefined;
this.parent = undefined;
this.raw = false;
this.isStatic = false;
this.isRootInsert = true;
this.isComment = false;
this.isCloned = false;
this.isOnce = false;
};
var prototypeAccessors = { child: {} };
// DEPRECATED: alias for componentInstance for backwards compat.
/* istanbul ignore next */
prototypeAccessors.child.get = function () {
return this.componentInstance
};
Object.defineProperties( VNode.prototype, prototypeAccessors );
var createEmptyVNode = function () {
var node = new VNode();
node.text = '';
node.isComment = true;
return node
};
function createTextVNode (val) {
return new VNode(undefined, undefined, undefined, String(val))
}
// optimized shallow clone
// used for static nodes and slot nodes because they may be reused across
// multiple renders, cloning them avoids errors when DOM manipulations rely
// on their elm reference.
function cloneVNode (vnode) {
var cloned = new VNode(
vnode.tag,
vnode.data,
vnode.children,
vnode.text,
vnode.elm,
vnode.context,
vnode.componentOptions
);
cloned.ns = vnode.ns;
cloned.isStatic = vnode.isStatic;
cloned.key = vnode.key;
cloned.isComment = vnode.isComment;
cloned.isCloned = true;
return cloned
}
function cloneVNodes (vnodes) {
var len = vnodes.length;
var res = new Array(len);
for (var i = 0; i < len; i++) {
res[i] = cloneVNode(vnodes[i]);
}
return res
}
/* */
var normalizeEvent = cached(function (name) {
var passive = name.charAt(0) === '&';
name = passive ? name.slice(1) : name;
var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first
name = once$$1 ? name.slice(1) : name;
var capture = name.charAt(0) === '!';
name = capture ? name.slice(1) : name;
return {
name: name,
once: once$$1,
capture: capture,
passive: passive
}
});
function createFnInvoker (fns) {
function invoker () {
var arguments$1 = arguments;
var fns = invoker.fns;
if (Array.isArray(fns)) {
for (var i = 0; i < fns.length; i++) {
fns[i].apply(null, arguments$1);
}
} else {
// return handler return value for single handlers
return fns.apply(null, arguments)
}
}
invoker.fns = fns;
return invoker
}
function updateListeners (
on,
oldOn,
add,
remove$$1,
vm
) {
var name, cur, old, event;
for (name in on) {
cur = on[name];
old = oldOn[name];
event = normalizeEvent(name);
if (isUndef(cur)) {
process.env.NODE_ENV !== 'production' && warn(
"Invalid handler for event \"" + (event.name) + "\": got " + String(cur),
vm
);
} else if (isUndef(old)) {
if (isUndef(cur.fns)) {
cur = on[name] = createFnInvoker(cur);
}
add(event.name, cur, event.once, event.capture, event.passive);
} else if (cur !== old) {
old.fns = cur;
on[name] = old;
}
}
for (name in oldOn) {
if (isUndef(on[name])) {
event = normalizeEvent(name);
remove$$1(event.name, oldOn[name], event.capture);
}
}
}
/* */
function mergeVNodeHook (def, hookKey, hook) {
var invoker;
var oldHook = def[hookKey];
function wrappedHook () {
hook.apply(this, arguments);
// important: remove merged hook to ensure it's called only once
// and prevent memory leak
remove(invoker.fns, wrappedHook);
}
if (isUndef(oldHook)) {
// no existing hook
invoker = createFnInvoker([wrappedHook]);
} else {
/* istanbul ignore if */
if (isDef(oldHook.fns) && isTrue(oldHook.merged)) {
// already a merged invoker
invoker = oldHook;
invoker.fns.push(wrappedHook);
} else {
// existing plain hook
invoker = createFnInvoker([oldHook, wrappedHook]);
}
}
invoker.merged = true;
def[hookKey] = invoker;
}
/* */
function extractPropsFromVNodeData (
data,
Ctor,
tag
) {
// we are only extracting raw values here.
// validation and default values are handled in the child
// component itself.
var propOptions = Ctor.options.props;
if (isUndef(propOptions)) {
return
}
var res = {};
var attrs = data.attrs;
var props = data.props;
if (isDef(attrs) || isDef(props)) {
for (var key in propOptions) {
var altKey = hyphenate(key);
if (process.env.NODE_ENV !== 'production') {
var keyInLowerCase = key.toLowerCase();
if (
key !== keyInLowerCase &&
attrs && hasOwn(attrs, keyInLowerCase)
) {
tip(
"Prop \"" + keyInLowerCase + "\" is passed to component " +
(formatComponentName(tag || Ctor)) + ", but the declared prop name is" +
" \"" + key + "\". " +
"Note that HTML attributes are case-insensitive and camelCased " +
"props need to use their kebab-case equivalents when using in-DOM " +
"templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"."
);
}
}
checkProp(res, props, key, altKey, true) ||
checkProp(res, attrs, key, altKey, false);
}
}
return res
}
function checkProp (
res,
hash,
key,
altKey,
preserve
) {
if (isDef(hash)) {
if (hasOwn(hash, key)) {
res[key] = hash[key];
if (!preserve) {
delete hash[key];
}
return true
} else if (hasOwn(hash, altKey)) {
res[key] = hash[altKey];
if (!preserve) {
delete hash[altKey];
}
return true
}
}
return false
}
/* */
// The template compiler attempts to minimize the need for normalization by
// statically analyzing the template at compile time.
//
// For plain HTML markup, normalization can be completely skipped because the
// generated render function is guaranteed to return Array<VNode>. There are
// two cases where extra normalization is needed:
// 1. When the children contains components - because a functional component
// may return an Array instead of a single root. In this case, just a simple
// normalization is needed - if any child is an Array, we flatten the whole
// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
// because functional components already normalize their own children.
function simpleNormalizeChildren (children) {
for (var i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
return Array.prototype.concat.apply([], children)
}
}
return children
}
// 2. When the children contains constructs that always generated nested Arrays,
// e.g. <template>, <slot>, v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
function normalizeChildren (children) {
return isPrimitive(children)
? [createTextVNode(children)]
: Array.isArray(children)
? normalizeArrayChildren(children)
: undefined
}
function isTextNode (node) {
return isDef(node) && isDef(node.text) && isFalse(node.isComment)
}
function normalizeArrayChildren (children, nestedIndex) {
var res = [];
var i, c, last;
for (i = 0; i < children.length; i++) {
c = children[i];
if (isUndef(c) || typeof c === 'boolean') { continue }
last = res[res.length - 1];
// nested
if (Array.isArray(c)) {
res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)));
} else if (isPrimitive(c)) {
if (isTextNode(last)) {
// merge adjacent text nodes
// this is necessary for SSR hydration because text nodes are
// essentially merged when rendered to HTML strings
(last).text += String(c);
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c));
}
} else {
if (isTextNode(c) && isTextNode(last)) {
// merge adjacent text nodes
res[res.length - 1] = createTextVNode(last.text + c.text);
} else {
// default key for nested array children (likely generated by v-for)
if (isTrue(children._isVList) &&
isDef(c.tag) &&
isUndef(c.key) &&
isDef(nestedIndex)) {
c.key = "__vlist" + nestedIndex + "_" + i + "__";
}
res.push(c);
}
}
}
return res
}
/* */
function ensureCtor (comp, base) {
return isObject(comp)
? base.extend(comp)
: comp
}
function resolveAsyncComponent (
factory,
baseCtor,
context
) {
if (isTrue(factory.error) && isDef(factory.errorComp)) {
return factory.errorComp
}
if (isDef(factory.resolved)) {
return factory.resolved
}
if (isTrue(factory.loading) && isDef(factory.loadingComp)) {
return factory.loadingComp
}
if (isDef(factory.contexts)) {
// already pending
factory.contexts.push(context);
} else {
var contexts = factory.contexts = [context];
var sync = true;
var forceRender = function () {
for (var i = 0, l = contexts.length; i < l; i++) {
contexts[i].$forceUpdate();
}
};
var resolve = once(function (res) {
// cache resolved
factory.resolved = ensureCtor(res, baseCtor);
// invoke callbacks only if this is not a synchronous resolve
// (async resolves are shimmed as synchronous during SSR)
if (!sync) {
forceRender();
}
});
var reject = once(function (reason) {
process.env.NODE_ENV !== 'production' && warn(
"Failed to resolve async component: " + (String(factory)) +
(reason ? ("\nReason: " + reason) : '')
);
if (isDef(factory.errorComp)) {
factory.error = true;
forceRender();
}
});
var res = factory(resolve, reject);
if (isObject(res)) {
if (typeof res.then === 'function') {
// () => Promise
if (isUndef(factory.resolved)) {
res.then(resolve, reject);
}
} else if (isDef(res.component) && typeof res.component.then === 'function') {
res.component.then(resolve, reject);
if (isDef(res.error)) {
factory.errorComp = ensureCtor(res.error, baseCtor);
}
if (isDef(res.loading)) {
factory.loadingComp = ensureCtor(res.loading, baseCtor);
if (res.delay === 0) {
factory.loading = true;
} else {
setTimeout(function () {
if (isUndef(factory.resolved) && isUndef(factory.error)) {
factory.loading = true;
forceRender();
}
}, res.delay || 200);
}
}
if (isDef(res.timeout)) {
setTimeout(function () {
if (isUndef(factory.resolved)) {
reject(
process.env.NODE_ENV !== 'production'
? ("timeout (" + (res.timeout) + "ms)")
: null
);
}
}, res.timeout);
}
}
}
sync = false;
// return in case resolved synchronously
return factory.loading
? factory.loadingComp
: factory.resolved
}
}
/* */
function getFirstComponentChild (children) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var c = children[i];
if (isDef(c) && isDef(c.componentOptions)) {
return c
}
}
}
}
/* */
/* */
function initEvents (vm) {
vm._events = Object.create(null);
vm._hasHookEvent = false;
// init parent attached events
var listeners = vm.$options._parentListeners;
if (listeners) {
updateComponentListeners(vm, listeners);
}
}
var target;
function add (event, fn, once$$1) {
if (once$$1) {
target.$once(event, fn);
} else {
target.$on(event, fn);
}
}
function remove$1 (event, fn) {
target.$off(event, fn);
}
function updateComponentListeners (
vm,
listeners,
oldListeners
) {
target = vm;
updateListeners(listeners, oldListeners || {}, add, remove$1, vm);
}
function eventsMixin (Vue) {
var hookRE = /^hook:/;
Vue.prototype.$on = function (event, fn) {
var this$1 = this;
var vm = this;
if (Array.isArray(event)) {
for (var i = 0, l = event.length; i < l; i++) {
this$1.$on(event[i], fn);
}
} else {
(vm._events[event] || (vm._events[event] = [])).push(fn);
// optimize hook:event cost by using a boolean flag marked at registration
// instead of a hash lookup
if (hookRE.test(event)) {
vm._hasHookEvent = true;
}
}
return vm
};
Vue.prototype.$once = function (event, fn) {
var vm = this;
function on () {
vm.$off(event, on);
fn.apply(vm, arguments);
}
on.fn = fn;
vm.$on(event, on);
return vm
};
Vue.prototype.$off = function (event, fn) {
var this$1 = this;
var vm = this;
// all
if (!arguments.length) {
vm._events = Object.create(null);
return vm
}
// array of events
if (Array.isArray(event)) {
for (var i$1 = 0, l = event.length; i$1 < l; i$1++) {
this$1.$off(event[i$1], fn);
}
return vm
}
// specific event
var cbs = vm._events[event];
if (!cbs) {
return vm
}
if (arguments.length === 1) {
vm._events[event] = null;
return vm
}
// specific handler
var cb;
var i = cbs.length;
while (i--) {
cb = cbs[i];
if (cb === fn || cb.fn === fn) {
cbs.splice(i, 1);
break
}
}
return vm
};
Vue.prototype.$emit = function (event) {
var vm = this;
if (process.env.NODE_ENV !== 'production') {
var lowerCaseEvent = event.toLowerCase();
if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {
tip(
"Event \"" + lowerCaseEvent + "\" is emitted in component " +
(formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " +
"Note that HTML attributes are case-insensitive and you cannot use " +
"v-on to listen to camelCase events when using in-DOM templates. " +
"You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"."
);
}
}
var cbs = vm._events[event];
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs;
var args = toArray(arguments, 1);
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i].apply(vm, args);
}
}
return vm
};
}
/* */
/**
* Runtime helper for resolving raw children VNodes into a slot object.
*/
function resolveSlots (
children,
context
) {
var slots = {};
if (!children) {
return slots
}
var defaultSlot = [];
for (var i = 0, l = children.length; i < l; i++) {
var child = children[i];
// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.functionalContext === context) &&
child.data && child.data.slot != null
) {
var name = child.data.slot;
var slot = (slots[name] || (slots[name] = []));
if (child.tag === 'template') {
slot.push.apply(slot, child.children);
} else {
slot.push(child);
}
} else {
defaultSlot.push(child);
}
}
// ignore whitespace
if (!defaultSlot.every(isWhitespace)) {
slots.default = defaultSlot;
}
return slots
}
function isWhitespace (node) {
return node.isComment || node.text === ' '
}
function resolveScopedSlots (
fns, // see flow/vnode
res
) {
res = res || {};
for (var i = 0; i < fns.length; i++) {
if (Array.isArray(fns[i])) {
resolveScopedSlots(fns[i], res);
} else {
res[fns[i].key] = fns[i].fn;
}
}
return res
}
/* */
var activeInstance = null;
function initLifecycle (vm) {
var options = vm.$options;
// locate first non-abstract parent
var parent = options.parent;
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent;
}
parent.$children.push(vm);
}
vm.$parent = parent;
vm.$root = parent ? parent.$root : vm;
vm.$children = [];
vm.$refs = {};
vm._watcher = null;
vm._inactive = null;
vm._directInactive = false;
vm._isMounted = false;
vm._isDestroyed = false;
vm._isBeingDestroyed = false;
}
function lifecycleMixin (Vue) {
Vue.prototype._update = function (vnode, hydrating) {
var vm = this;
if (vm._isMounted) {
callHook(vm, 'beforeUpdate');
}
var prevEl = vm.$el;
var prevVnode = vm._vnode;
var prevActiveInstance = activeInstance;
activeInstance = vm;
vm._vnode = vnode;
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevVnode) {
// initial render
vm.$el = vm.__patch__(
vm.$el, vnode, hydrating, false /* removeOnly */,
vm.$options._parentElm,
vm.$options._refElm
);
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode);
}
activeInstance = prevActiveInstance;
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null;
}
if (vm.$el) {
vm.$el.__vue__ = vm;
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el;
}
// updated hook is called by the scheduler to ensure that children are
// updated in a parent's updated hook.
};
Vue.prototype.$forceUpdate = function () {
var vm = this;
if (vm._watcher) {
vm._watcher.update();
}
};
Vue.prototype.$destroy = function () {
var vm = this;
if (vm._isBeingDestroyed) {
return
}
callHook(vm, 'beforeDestroy');
vm._isBeingDestroyed = true;
// remove self from parent
var parent = vm.$parent;
if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
remove(parent.$children, vm);
}
// teardown watchers
if (vm._watcher) {
vm._watcher.teardown();
}
var i = vm._watchers.length;
while (i--) {
vm._watchers[i].teardown();
}
// remove reference from data ob
// frozen object may not have observer.
if (vm._data.__ob__) {
vm._data.__ob__.vmCount--;
}
// call the last hook...
vm._isDestroyed = true;
// invoke destroy hooks on current rendered tree
vm.__patch__(vm._vnode, null);
// fire destroyed hook
callHook(vm, 'destroyed');
// turn off all instance listeners.
vm.$off();
// remove __vue__ reference
if (vm.$el) {
vm.$el.__vue__ = null;
}
// remove reference to DOM nodes (prevents leak)
vm.$options._parentElm = vm.$options._refElm = null;
};
}
function mountComponent (
vm,
el,
hydrating
) {
vm.$el = el;
if (!vm.$options.render) {
vm.$options.render = createEmptyVNode;
if (process.env.NODE_ENV !== 'production') {
/* istanbul ignore if */
if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
vm.$options.el || el) {
warn(
'You are using the runtime-only build of Vue where the template ' +
'compiler is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
);
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
);
}
}
}
callHook(vm, 'beforeMount');
var updateComponent;
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
updateComponent = function () {
var name = vm._name;
var id = vm._uid;
var startTag = "vue-perf-start:" + id;
var endTag = "vue-perf-end:" + id;
mark(startTag);
var vnode = vm._render();
mark(endTag);
measure((name + " render"), startTag, endTag);
mark(startTag);
vm._update(vnode, hydrating);
mark(endTag);
measure((name + " patch"), startTag, endTag);
};
} else {
updateComponent = function () {
vm._update(vm._render(), hydrating);
};
}
vm._watcher = new Watcher(vm, updateComponent, noop);
hydrating = false;
// manually mounted instance, call mounted on self
// mounted is called for render-created child components in its inserted hook
if (vm.$vnode == null) {
vm._isMounted = true;
callHook(vm, 'mounted');
}
return vm
}
function updateChildComponent (
vm,
propsData,
listeners,
parentVnode,
renderChildren
) {
// determine whether component has slot children
// we need to do this before overwriting $options._renderChildren
var hasChildren = !!(
renderChildren || // has new static slots
vm.$options._renderChildren || // has old static slots
parentVnode.data.scopedSlots || // has new scoped slots
vm.$scopedSlots !== emptyObject // has old scoped slots
);
vm.$options._parentVnode = parentVnode;
vm.$vnode = parentVnode; // update vm's placeholder node without re-render
if (vm._vnode) { // update child tree's parent
vm._vnode.parent = parentVnode;
}
vm.$options._renderChildren = renderChildren;
// update props
if (propsData && vm.$options.props) {
observerState.shouldConvert = false;
if (process.env.NODE_ENV !== 'production') {
observerState.isSettingProps = true;
}
var props = vm._props;
var propKeys = vm.$options._propKeys || [];
for (var i = 0; i < propKeys.length; i++) {
var key = propKeys[i];
props[key] = validateProp(key, vm.$options.props, propsData, vm);
}
observerState.shouldConvert = true;
if (process.env.NODE_ENV !== 'production') {
observerState.isSettingProps = false;
}
// keep a copy of raw propsData
vm.$options.propsData = propsData;
}
// update listeners
if (listeners) {
var oldListeners = vm.$options._parentListeners;
vm.$options._parentListeners = listeners;
updateComponentListeners(vm, listeners, oldListeners);
}
// resolve slots + force update if has children
if (hasChildren) {
vm.$slots = resolveSlots(renderChildren, parentVnode.context);
vm.$forceUpdate();
}
}
function isInInactiveTree (vm) {
while (vm && (vm = vm.$parent)) {
if (vm._inactive) { return true }
}
return false
}
function activateChildComponent (vm, direct) {
if (direct) {
vm._directInactive = false;
if (isInInactiveTree(vm)) {
return
}
} else if (vm._directInactive) {
return
}
if (vm._inactive || vm._inactive === null) {
vm._inactive = false;
for (var i = 0; i < vm.$children.length; i++) {
activateChildComponent(vm.$children[i]);
}
callHook(vm, 'activated');
}
}
function deactivateChildComponent (vm, direct) {
if (direct) {
vm._directInactive = true;
if (isInInactiveTree(vm)) {
return
}
}
if (!vm._inactive) {
vm._inactive = true;
for (var i = 0; i < vm.$children.length; i++) {
deactivateChildComponent(vm.$children[i]);
}
callHook(vm, 'deactivated');
}
}
function callHook (vm, hook) {
var handlers = vm.$options[hook];
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
try {
handlers[i].call(vm);
} catch (e) {
handleError(e, vm, (hook + " hook"));
}
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook);
}
}
/* */
var MAX_UPDATE_COUNT = 100;
var queue = [];
var activatedChildren = [];
var has = {};
var circular = {};
var waiting = false;
var flushing = false;
var index = 0;
/**
* Reset the scheduler's state.
*/
function resetSchedulerState () {
index = queue.length = activatedChildren.length = 0;
has = {};
if (process.env.NODE_ENV !== 'production') {
circular = {};
}
waiting = flushing = false;
}
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
flushing = true;
var watcher, id;
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort(function (a, b) { return a.id - b.id; });
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
watcher = queue[index];
id = watcher.id;
has[id] = null;
watcher.run();
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production' && has[id] != null) {
circular[id] = (circular[id] || 0) + 1;
if (circular[id] > MAX_UPDATE_COUNT) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? ("in watcher with expression \"" + (watcher.expression) + "\"")
: "in a component render function."
),
watcher.vm
);
break
}
}
}
// keep copies of post queues before resetting state
var activatedQueue = activatedChildren.slice();
var updatedQueue = queue.slice();
resetSchedulerState();
// call component updated and activated hooks
callActivatedHooks(activatedQueue);
callUpdateHooks(updatedQueue);
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush');
}
}
function callUpdateHooks (queue) {
var i = queue.length;
while (i--) {
var watcher = queue[i];
var vm = watcher.vm;
if (vm._watcher === watcher && vm._isMounted) {
callHook(vm, 'updated');
}
}
}
/**
* Queue a kept-alive component that was activated during patch.
* The queue will be processed after the entire tree has been patched.
*/
function queueActivatedComponent (vm) {
// setting _inactive to false here so that a render function can
// rely on checking whether it's in an inactive tree (e.g. router-view)
vm._inactive = false;
activatedChildren.push(vm);
}
function callActivatedHooks (queue) {
for (var i = 0; i < queue.length; i++) {
queue[i]._inactive = true;
activateChildComponent(queue[i], true /* true */);
}
}
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/
function queueWatcher (watcher) {
var id = watcher.id;
if (has[id] == null) {
has[id] = true;
if (!flushing) {
queue.push(watcher);
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
var i = queue.length - 1;
while (i > index && queue[i].id > watcher.id) {
i--;
}
queue.splice(i + 1, 0, watcher);
}
// queue the flush
if (!waiting) {
waiting = true;
nextTick(flushSchedulerQueue);
}
}
}
/* */
var uid$2 = 0;
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*/
var Watcher = function Watcher (
vm,
expOrFn,
cb,
options
) {
this.vm = vm;
vm._watchers.push(this);
// options
if (options) {
this.deep = !!options.deep;
this.user = !!options.user;
this.lazy = !!options.lazy;
this.sync = !!options.sync;
} else {
this.deep = this.user = this.lazy = this.sync = false;
}
this.cb = cb;
this.id = ++uid$2; // uid for batching
this.active = true;
this.dirty = this.lazy; // for lazy watchers
this.deps = [];
this.newDeps = [];
this.depIds = new _Set();
this.newDepIds = new _Set();
this.expression = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: '';
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn;
} else {
this.getter = parsePath(expOrFn);
if (!this.getter) {
this.getter = function () {};
process.env.NODE_ENV !== 'production' && warn(
"Failed watching path: \"" + expOrFn + "\" " +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
);
}
}
this.value = this.lazy
? undefined
: this.get();
};
/**
* Evaluate the getter, and re-collect dependencies.
*/
Watcher.prototype.get = function get () {
pushTarget(this);
var value;
var vm = this.vm;
if (this.user) {
try {
value = this.getter.call(vm, vm);
} catch (e) {
handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\""));
}
} else {
value = this.getter.call(vm, vm);
}
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value);
}
popTarget();
this.cleanupDeps();
return value
};
/**
* Add a dependency to this directive.
*/
Watcher.prototype.addDep = function addDep (dep) {
var id = dep.id;
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id);
this.newDeps.push(dep);
if (!this.depIds.has(id)) {
dep.addSub(this);
}
}
};
/**
* Clean up for dependency collection.
*/
Watcher.prototype.cleanupDeps = function cleanupDeps () {
var this$1 = this;
var i = this.deps.length;
while (i--) {
var dep = this$1.deps[i];
if (!this$1.newDepIds.has(dep.id)) {
dep.removeSub(this$1);
}
}
var tmp = this.depIds;
this.depIds = this.newDepIds;
this.newDepIds = tmp;
this.newDepIds.clear();
tmp = this.deps;
this.deps = this.newDeps;
this.newDeps = tmp;
this.newDeps.length = 0;
};
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
Watcher.prototype.update = function update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true;
} else if (this.sync) {
this.run();
} else {
queueWatcher(this);
}
};
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
Watcher.prototype.run = function run () {
if (this.active) {
var value = this.get();
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
var oldValue = this.value;
this.value = value;
if (this.user) {
try {
this.cb.call(this.vm, value, oldValue);
} catch (e) {
handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\""));
}
} else {
this.cb.call(this.vm, value, oldValue);
}
}
}
};
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
Watcher.prototype.evaluate = function evaluate () {
this.value = this.get();
this.dirty = false;
};
/**
* Depend on all deps collected by this watcher.
*/
Watcher.prototype.depend = function depend () {
var this$1 = this;
var i = this.deps.length;
while (i--) {
this$1.deps[i].depend();
}
};
/**
* Remove self from all dependencies' subscriber list.
*/
Watcher.prototype.teardown = function teardown () {
var this$1 = this;
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed.
if (!this.vm._isBeingDestroyed) {
remove(this.vm._watchers, this);
}
var i = this.deps.length;
while (i--) {
this$1.deps[i].removeSub(this$1);
}
this.active = false;
}
};
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
var seenObjects = new _Set();
function traverse (val) {
seenObjects.clear();
_traverse(val, seenObjects);
}
function _traverse (val, seen) {
var i, keys;
var isA = Array.isArray(val);
if ((!isA && !isObject(val)) || !Object.isExtensible(val)) {
return
}
if (val.__ob__) {
var depId = val.__ob__.dep.id;
if (seen.has(depId)) {
return
}
seen.add(depId);
}
if (isA) {
i = val.length;
while (i--) { _traverse(val[i], seen); }
} else {
keys = Object.keys(val);
i = keys.length;
while (i--) { _traverse(val[keys[i]], seen); }
}
}
/* */
var sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
};
function proxy (target, sourceKey, key) {
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
};
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val;
};
Object.defineProperty(target, key, sharedPropertyDefinition);
}
function initState (vm) {
vm._watchers = [];
var opts = vm.$options;
if (opts.props) { initProps(vm, opts.props); }
if (opts.methods) { initMethods(vm, opts.methods); }
if (opts.data) {
initData(vm);
} else {
observe(vm._data = {}, true /* asRootData */);
}
if (opts.computed) { initComputed(vm, opts.computed); }
if (opts.watch) { initWatch(vm, opts.watch); }
}
var isReservedProp = {
key: 1,
ref: 1,
slot: 1
};
function initProps (vm, propsOptions) {
var propsData = vm.$options.propsData || {};
var props = vm._props = {};
// cache prop keys so that future props updates can iterate using Array
// instead of dynamic object key enumeration.
var keys = vm.$options._propKeys = [];
var isRoot = !vm.$parent;
// root instance props should be converted
observerState.shouldConvert = isRoot;
var loop = function ( key ) {
keys.push(key);
var value = validateProp(key, propsOptions, propsData, vm);
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
if (isReservedProp[key] || config.isReservedAttr(key)) {
warn(
("\"" + key + "\" is a reserved attribute and cannot be used as component prop."),
vm
);
}
defineReactive$$1(props, key, value, function () {
if (vm.$parent && !observerState.isSettingProps) {
warn(
"Avoid mutating a prop directly since the value will be " +
"overwritten whenever the parent component re-renders. " +
"Instead, use a data or computed property based on the prop's " +
"value. Prop being mutated: \"" + key + "\"",
vm
);
}
});
} else {
defineReactive$$1(props, key, value);
}
// static props are already proxied on the component's prototype
// during Vue.extend(). We only need to proxy props defined at
// instantiation here.
if (!(key in vm)) {
proxy(vm, "_props", key);
}
};
for (var key in propsOptions) loop( key );
observerState.shouldConvert = true;
}
function initData (vm) {
var data = vm.$options.data;
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {};
if (!isPlainObject(data)) {
data = {};
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
);
}
// proxy data on instance
var keys = Object.keys(data);
var props = vm.$options.props;
var i = keys.length;
while (i--) {
if (props && hasOwn(props, keys[i])) {
process.env.NODE_ENV !== 'production' && warn(
"The data property \"" + (keys[i]) + "\" is already declared as a prop. " +
"Use prop default value instead.",
vm
);
} else if (!isReserved(keys[i])) {
proxy(vm, "_data", keys[i]);
}
}
// observe data
observe(data, true /* asRootData */);
}
function getData (data, vm) {
try {
return data.call(vm)
} catch (e) {
handleError(e, vm, "data()");
return {}
}
}
var computedWatcherOptions = { lazy: true };
function initComputed (vm, computed) {
var watchers = vm._computedWatchers = Object.create(null);
for (var key in computed) {
var userDef = computed[key];
var getter = typeof userDef === 'function' ? userDef : userDef.get;
if (process.env.NODE_ENV !== 'production') {
if (getter === undefined) {
warn(
("No getter function has been defined for computed property \"" + key + "\"."),
vm
);
getter = noop;
}
}
// create internal watcher for the computed property.
watchers[key] = new Watcher(vm, getter, noop, computedWatcherOptions);
// component-defined computed properties are already defined on the
// component prototype. We only need to define computed properties defined
// at instantiation here.
if (!(key in vm)) {
defineComputed(vm, key, userDef);
} else if (process.env.NODE_ENV !== 'production') {
if (key in vm.$data) {
warn(("The computed property \"" + key + "\" is already defined in data."), vm);
} else if (vm.$options.props && key in vm.$options.props) {
warn(("The computed property \"" + key + "\" is already defined as a prop."), vm);
}
}
}
}
function defineComputed (target, key, userDef) {
if (typeof userDef === 'function') {
sharedPropertyDefinition.get = createComputedGetter(key);
sharedPropertyDefinition.set = noop;
} else {
sharedPropertyDefinition.get = userDef.get
? userDef.cache !== false
? createComputedGetter(key)
: userDef.get
: noop;
sharedPropertyDefinition.set = userDef.set
? userDef.set
: noop;
}
Object.defineProperty(target, key, sharedPropertyDefinition);
}
function createComputedGetter (key) {
return function computedGetter () {
var watcher = this._computedWatchers && this._computedWatchers[key];
if (watcher) {
if (watcher.dirty) {
watcher.evaluate();
}
if (Dep.target) {
watcher.depend();
}
return watcher.value
}
}
}
function initMethods (vm, methods) {
var props = vm.$options.props;
for (var key in methods) {
vm[key] = methods[key] == null ? noop : bind(methods[key], vm);
if (process.env.NODE_ENV !== 'production') {
if (methods[key] == null) {
warn(
"method \"" + key + "\" has an undefined value in the component definition. " +
"Did you reference the function correctly?",
vm
);
}
if (props && hasOwn(props, key)) {
warn(
("method \"" + key + "\" has already been defined as a prop."),
vm
);
}
}
}
}
function initWatch (vm, watch) {
for (var key in watch) {
var handler = watch[key];
if (Array.isArray(handler)) {
for (var i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i]);
}
} else {
createWatcher(vm, key, handler);
}
}
}
function createWatcher (vm, key, handler) {
var options;
if (isPlainObject(handler)) {
options = handler;
handler = handler.handler;
}
if (typeof handler === 'string') {
handler = vm[handler];
}
vm.$watch(key, handler, options);
}
function stateMixin (Vue) {
// flow somehow has problems with directly declared definition object
// when using Object.defineProperty, so we have to procedurally build up
// the object here.
var dataDef = {};
dataDef.get = function () { return this._data };
var propsDef = {};
propsDef.get = function () { return this._props };
if (process.env.NODE_ENV !== 'production') {
dataDef.set = function (newData) {
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
);
};
propsDef.set = function () {
warn("$props is readonly.", this);
};
}
Object.defineProperty(Vue.prototype, '$data', dataDef);
Object.defineProperty(Vue.prototype, '$props', propsDef);
Vue.prototype.$set = set;
Vue.prototype.$delete = del;
Vue.prototype.$watch = function (
expOrFn,
cb,
options
) {
var vm = this;
options = options || {};
options.user = true;
var watcher = new Watcher(vm, expOrFn, cb, options);
if (options.immediate) {
cb.call(vm, watcher.value);
}
return function unwatchFn () {
watcher.teardown();
}
};
}
/* */
function initProvide (vm) {
var provide = vm.$options.provide;
if (provide) {
vm._provided = typeof provide === 'function'
? provide.call(vm)
: provide;
}
}
function initInjections (vm) {
var result = resolveInject(vm.$options.inject, vm);
if (result) {
Object.keys(result).forEach(function (key) {
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
defineReactive$$1(vm, key, result[key], function () {
warn(
"Avoid mutating an injected value directly since the changes will be " +
"overwritten whenever the provided component re-renders. " +
"injection being mutated: \"" + key + "\"",
vm
);
});
} else {
defineReactive$$1(vm, key, result[key]);
}
});
}
}
function resolveInject (inject, vm) {
if (inject) {
// inject is :any because flow is not smart enough to figure out cached
// isArray here
var isArray = Array.isArray(inject);
var result = Object.create(null);
var keys = isArray
? inject
: hasSymbol
? Reflect.ownKeys(inject)
: Object.keys(inject);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var provideKey = isArray ? key : inject[key];
var source = vm;
while (source) {
if (source._provided && provideKey in source._provided) {
result[key] = source._provided[provideKey];
break
}
source = source.$parent;
}
}
return result
}
}
/* */
function createFunctionalComponent (
Ctor,
propsData,
data,
context,
children
) {
var props = {};
var propOptions = Ctor.options.props;
if (isDef(propOptions)) {
for (var key in propOptions) {
props[key] = validateProp(key, propOptions, propsData || {});
}
} else {
if (isDef(data.attrs)) { mergeProps(props, data.attrs); }
if (isDef(data.props)) { mergeProps(props, data.props); }
}
// ensure the createElement function in functional components
// gets a unique context - this is necessary for correct named slot check
var _context = Object.create(context);
var h = function (a, b, c, d) { return createElement(_context, a, b, c, d, true); };
var vnode = Ctor.options.render.call(null, h, {
data: data,
props: props,
children: children,
parent: context,
listeners: data.on || {},
injections: resolveInject(Ctor.options.inject, context),
slots: function () { return resolveSlots(children, context); }
});
if (vnode instanceof VNode) {
vnode.functionalContext = context;
vnode.functionalOptions = Ctor.options;
if (data.slot) {
(vnode.data || (vnode.data = {})).slot = data.slot;
}
}
return vnode
}
function mergeProps (to, from) {
for (var key in from) {
to[camelize(key)] = from[key];
}
}
/* */
// hooks to be invoked on component VNodes during patch
var componentVNodeHooks = {
init: function init (
vnode,
hydrating,
parentElm,
refElm
) {
if (!vnode.componentInstance || vnode.componentInstance._isDestroyed) {
var child = vnode.componentInstance = createComponentInstanceForVnode(
vnode,
activeInstance,
parentElm,
refElm
);
child.$mount(hydrating ? vnode.elm : undefined, hydrating);
} else if (vnode.data.keepAlive) {
// kept-alive components, treat as a patch
var mountedNode = vnode; // work around flow
componentVNodeHooks.prepatch(mountedNode, mountedNode);
}
},
prepatch: function prepatch (oldVnode, vnode) {
var options = vnode.componentOptions;
var child = vnode.componentInstance = oldVnode.componentInstance;
updateChildComponent(
child,
options.propsData, // updated props
options.listeners, // updated listeners
vnode, // new parent vnode
options.children // new children
);
},
insert: function insert (vnode) {
var context = vnode.context;
var componentInstance = vnode.componentInstance;
if (!componentInstance._isMounted) {
componentInstance._isMounted = true;
callHook(componentInstance, 'mounted');
}
if (vnode.data.keepAlive) {
if (context._isMounted) {
// vue-router#1212
// During updates, a kept-alive component's child components may
// change, so directly walking the tree here may call activated hooks
// on incorrect children. Instead we push them into a queue which will
// be processed after the whole patch process ended.
queueActivatedComponent(componentInstance);
} else {
activateChildComponent(componentInstance, true /* direct */);
}
}
},
destroy: function destroy (vnode) {
var componentInstance = vnode.componentInstance;
if (!componentInstance._isDestroyed) {
if (!vnode.data.keepAlive) {
componentInstance.$destroy();
} else {
deactivateChildComponent(componentInstance, true /* direct */);
}
}
}
};
var hooksToMerge = Object.keys(componentVNodeHooks);
function createComponent (
Ctor,
data,
context,
children,
tag
) {
if (isUndef(Ctor)) {
return
}
var baseCtor = context.$options._base;
// plain options object: turn it into a constructor
if (isObject(Ctor)) {
Ctor = baseCtor.extend(Ctor);
}
// if at this stage it's not a constructor or an async component factory,
// reject.
if (typeof Ctor !== 'function') {
if (process.env.NODE_ENV !== 'production') {
warn(("Invalid Component definition: " + (String(Ctor))), context);
}
return
}
// async component
if (isUndef(Ctor.cid)) {
Ctor = resolveAsyncComponent(Ctor, baseCtor, context);
if (Ctor === undefined) {
// return nothing if this is indeed an async component
// wait for the callback to trigger parent update.
return
}
}
// resolve constructor options in case global mixins are applied after
// component constructor creation
resolveConstructorOptions(Ctor);
data = data || {};
// transform component v-model data into props & events
if (isDef(data.model)) {
transformModel(Ctor.options, data);
}
// extract props
var propsData = extractPropsFromVNodeData(data, Ctor, tag);
// functional component
if (isTrue(Ctor.options.functional)) {
return createFunctionalComponent(Ctor, propsData, data, context, children)
}
// extract listeners, since these needs to be treated as
// child component listeners instead of DOM listeners
var listeners = data.on;
// replace with listeners with .native modifier
data.on = data.nativeOn;
if (isTrue(Ctor.options.abstract)) {
// abstract components do not keep anything
// other than props & listeners
data = {};
}
// merge component management hooks onto the placeholder node
mergeHooks(data);
// return a placeholder vnode
var name = Ctor.options.name || tag;
var vnode = new VNode(
("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')),
data, undefined, undefined, undefined, context,
{ Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }
);
return vnode
}
function createComponentInstanceForVnode (
vnode, // we know it's MountedComponentVNode but flow doesn't
parent, // activeInstance in lifecycle state
parentElm,
refElm
) {
var vnodeComponentOptions = vnode.componentOptions;
var options = {
_isComponent: true,
parent: parent,
propsData: vnodeComponentOptions.propsData,
_componentTag: vnodeComponentOptions.tag,
_parentVnode: vnode,
_parentListeners: vnodeComponentOptions.listeners,
_renderChildren: vnodeComponentOptions.children,
_parentElm: parentElm || null,
_refElm: refElm || null
};
// check inline-template render functions
var inlineTemplate = vnode.data.inlineTemplate;
if (isDef(inlineTemplate)) {
options.render = inlineTemplate.render;
options.staticRenderFns = inlineTemplate.staticRenderFns;
}
return new vnodeComponentOptions.Ctor(options)
}
function mergeHooks (data) {
if (!data.hook) {
data.hook = {};
}
for (var i = 0; i < hooksToMerge.length; i++) {
var key = hooksToMerge[i];
var fromParent = data.hook[key];
var ours = componentVNodeHooks[key];
data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours;
}
}
function mergeHook$1 (one, two) {
return function (a, b, c, d) {
one(a, b, c, d);
two(a, b, c, d);
}
}
// transform component v-model info (value and callback) into
// prop and event handler respectively.
function transformModel (options, data) {
var prop = (options.model && options.model.prop) || 'value';
var event = (options.model && options.model.event) || 'input';(data.props || (data.props = {}))[prop] = data.model.value;
var on = data.on || (data.on = {});
if (isDef(on[event])) {
on[event] = [data.model.callback].concat(on[event]);
} else {
on[event] = data.model.callback;
}
}
/* */
var SIMPLE_NORMALIZE = 1;
var ALWAYS_NORMALIZE = 2;
// wrapper function for providing a more flexible interface
// without getting yelled at by flow
function createElement (
context,
tag,
data,
children,
normalizationType,
alwaysNormalize
) {
if (Array.isArray(data) || isPrimitive(data)) {
normalizationType = children;
children = data;
data = undefined;
}
if (isTrue(alwaysNormalize)) {
normalizationType = ALWAYS_NORMALIZE;
}
return _createElement(context, tag, data, children, normalizationType)
}
function _createElement (
context,
tag,
data,
children,
normalizationType
) {
if (isDef(data) && isDef((data).__ob__)) {
process.env.NODE_ENV !== 'production' && warn(
"Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" +
'Always create fresh vnode data objects in each render!',
context
);
return createEmptyVNode()
}
if (!tag) {
// in case of component :is set to falsy value
return createEmptyVNode()
}
// support single function children as default scoped slot
if (Array.isArray(children) &&
typeof children[0] === 'function'
) {
data = data || {};
data.scopedSlots = { default: children[0] };
children.length = 0;
}
if (normalizationType === ALWAYS_NORMALIZE) {
children = normalizeChildren(children);
} else if (normalizationType === SIMPLE_NORMALIZE) {
children = simpleNormalizeChildren(children);
}
var vnode, ns;
if (typeof tag === 'string') {
var Ctor;
ns = config.getTagNamespace(tag);
if (config.isReservedTag(tag)) {
// platform built-in elements
vnode = new VNode(
config.parsePlatformTagName(tag), data, children,
undefined, undefined, context
);
} else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
vnode = createComponent(Ctor, data, context, children, tag);
} else {
// unknown or unlisted namespaced elements
// check at runtime because it may get assigned a namespace when its
// parent normalizes children
vnode = new VNode(
tag, data, children,
undefined, undefined, context
);
}
} else {
// direct component options / constructor
vnode = createComponent(tag, data, context, children);
}
if (isDef(vnode)) {
if (ns) { applyNS(vnode, ns); }
return vnode
} else {
return createEmptyVNode()
}
}
function applyNS (vnode, ns) {
vnode.ns = ns;
if (vnode.tag === 'foreignObject') {
// use default namespace inside foreignObject
return
}
if (isDef(vnode.children)) {
for (var i = 0, l = vnode.children.length; i < l; i++) {
var child = vnode.children[i];
if (isDef(child.tag) && isUndef(child.ns)) {
applyNS(child, ns);
}
}
}
}
/* */
/**
* Runtime helper for rendering v-for lists.
*/
function renderList (
val,
render
) {
var ret, i, l, keys, key;
if (Array.isArray(val) || typeof val === 'string') {
ret = new Array(val.length);
for (i = 0, l = val.length; i < l; i++) {
ret[i] = render(val[i], i);
}
} else if (typeof val === 'number') {
ret = new Array(val);
for (i = 0; i < val; i++) {
ret[i] = render(i + 1, i);
}
} else if (isObject(val)) {
keys = Object.keys(val);
ret = new Array(keys.length);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret[i] = render(val[key], key, i);
}
}
if (isDef(ret)) {
(ret)._isVList = true;
}
return ret
}
/* */
/**
* Runtime helper for rendering <slot>
*/
function renderSlot (
name,
fallback,
props,
bindObject
) {
var scopedSlotFn = this.$scopedSlots[name];
if (scopedSlotFn) { // scoped slot
props = props || {};
if (bindObject) {
extend(props, bindObject);
}
return scopedSlotFn(props) || fallback
} else {
var slotNodes = this.$slots[name];
// warn duplicate slot usage
if (slotNodes && process.env.NODE_ENV !== 'production') {
slotNodes._rendered && warn(
"Duplicate presence of slot \"" + name + "\" found in the same render tree " +
"- this will likely cause render errors.",
this
);
slotNodes._rendered = true;
}
return slotNodes || fallback
}
}
/* */
/**
* Runtime helper for resolving filters
*/
function resolveFilter (id) {
return resolveAsset(this.$options, 'filters', id, true) || identity
}
/* */
/**
* Runtime helper for checking keyCodes from config.
*/
function checkKeyCodes (
eventKeyCode,
key,
builtInAlias
) {
var keyCodes = config.keyCodes[key] || builtInAlias;
if (Array.isArray(keyCodes)) {
return keyCodes.indexOf(eventKeyCode) === -1
} else {
return keyCodes !== eventKeyCode
}
}
/* */
/**
* Runtime helper for merging v-bind="object" into a VNode's data.
*/
function bindObjectProps (
data,
tag,
value,
asProp
) {
if (value) {
if (!isObject(value)) {
process.env.NODE_ENV !== 'production' && warn(
'v-bind without argument expects an Object or Array value',
this
);
} else {
if (Array.isArray(value)) {
value = toObject(value);
}
var hash;
for (var key in value) {
if (key === 'class' || key === 'style') {
hash = data;
} else {
var type = data.attrs && data.attrs.type;
hash = asProp || config.mustUseProp(tag, type, key)
? data.domProps || (data.domProps = {})
: data.attrs || (data.attrs = {});
}
if (!(key in hash)) {
hash[key] = value[key];
}
}
}
}
return data
}
/* */
/**
* Runtime helper for rendering static trees.
*/
function renderStatic (
index,
isInFor
) {
var tree = this._staticTrees[index];
// if has already-rendered static tree and not inside v-for,
// we can reuse the same tree by doing a shallow clone.
if (tree && !isInFor) {
return Array.isArray(tree)
? cloneVNodes(tree)
: cloneVNode(tree)
}
// otherwise, render a fresh tree.
tree = this._staticTrees[index] =
this.$options.staticRenderFns[index].call(this._renderProxy);
markStatic(tree, ("__static__" + index), false);
return tree
}
/**
* Runtime helper for v-once.
* Effectively it means marking the node as static with a unique key.
*/
function markOnce (
tree,
index,
key
) {
markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true);
return tree
}
function markStatic (
tree,
key,
isOnce
) {
if (Array.isArray(tree)) {
for (var i = 0; i < tree.length; i++) {
if (tree[i] && typeof tree[i] !== 'string') {
markStaticNode(tree[i], (key + "_" + i), isOnce);
}
}
} else {
markStaticNode(tree, key, isOnce);
}
}
function markStaticNode (node, key, isOnce) {
node.isStatic = true;
node.key = key;
node.isOnce = isOnce;
}
/* */
function initRender (vm) {
vm._vnode = null; // the root of the child tree
vm._staticTrees = null;
var parentVnode = vm.$vnode = vm.$options._parentVnode; // the placeholder node in parent tree
var renderContext = parentVnode && parentVnode.context;
vm.$slots = resolveSlots(vm.$options._renderChildren, renderContext);
vm.$scopedSlots = emptyObject;
// bind the createElement fn to this instance
// so that we get proper render context inside it.
// args order: tag, data, children, normalizationType, alwaysNormalize
// internal version is used by render functions compiled from templates
vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); };
// normalization is always applied for the public version, used in
// user-written render functions.
vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };
}
function renderMixin (Vue) {
Vue.prototype.$nextTick = function (fn) {
return nextTick(fn, this)
};
Vue.prototype._render = function () {
var vm = this;
var ref = vm.$options;
var render = ref.render;
var staticRenderFns = ref.staticRenderFns;
var _parentVnode = ref._parentVnode;
if (vm._isMounted) {
// clone slot nodes on re-renders
for (var key in vm.$slots) {
vm.$slots[key] = cloneVNodes(vm.$slots[key]);
}
}
vm.$scopedSlots = (_parentVnode && _parentVnode.data.scopedSlots) || emptyObject;
if (staticRenderFns && !vm._staticTrees) {
vm._staticTrees = [];
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
vm.$vnode = _parentVnode;
// render self
var vnode;
try {
vnode = render.call(vm._renderProxy, vm.$createElement);
} catch (e) {
handleError(e, vm, "render function");
// return error render result,
// or previous vnode to prevent render error causing blank component
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
vnode = vm.$options.renderError
? vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
: vm._vnode;
} else {
vnode = vm._vnode;
}
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
);
}
vnode = createEmptyVNode();
}
// set parent
vnode.parent = _parentVnode;
return vnode
};
// internal render helpers.
// these are exposed on the instance prototype to reduce generated render
// code size.
Vue.prototype._o = markOnce;
Vue.prototype._n = toNumber;
Vue.prototype._s = toString;
Vue.prototype._l = renderList;
Vue.prototype._t = renderSlot;
Vue.prototype._q = looseEqual;
Vue.prototype._i = looseIndexOf;
Vue.prototype._m = renderStatic;
Vue.prototype._f = resolveFilter;
Vue.prototype._k = checkKeyCodes;
Vue.prototype._b = bindObjectProps;
Vue.prototype._v = createTextVNode;
Vue.prototype._e = createEmptyVNode;
Vue.prototype._u = resolveScopedSlots;
}
/* */
var uid$1 = 0;
function initMixin (Vue) {
Vue.prototype._init = function (options) {
var vm = this;
// a uid
vm._uid = uid$1++;
var startTag, endTag;
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
startTag = "vue-perf-init:" + (vm._uid);
endTag = "vue-perf-end:" + (vm._uid);
mark(startTag);
}
// a flag to avoid this being observed
vm._isVue = true;
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options);
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
);
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
initProxy(vm);
} else {
vm._renderProxy = vm;
}
// expose real self
vm._self = vm;
initLifecycle(vm);
initEvents(vm);
initRender(vm);
callHook(vm, 'beforeCreate');
initInjections(vm); // resolve injections before data/props
initState(vm);
initProvide(vm); // resolve provide after data/props
callHook(vm, 'created');
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
vm._name = formatComponentName(vm, false);
mark(endTag);
measure(((vm._name) + " init"), startTag, endTag);
}
if (vm.$options.el) {
vm.$mount(vm.$options.el);
}
};
}
function initInternalComponent (vm, options) {
var opts = vm.$options = Object.create(vm.constructor.options);
// doing this because it's faster than dynamic enumeration.
opts.parent = options.parent;
opts.propsData = options.propsData;
opts._parentVnode = options._parentVnode;
opts._parentListeners = options._parentListeners;
opts._renderChildren = options._renderChildren;
opts._componentTag = options._componentTag;
opts._parentElm = options._parentElm;
opts._refElm = options._refElm;
if (options.render) {
opts.render = options.render;
opts.staticRenderFns = options.staticRenderFns;
}
}
function resolveConstructorOptions (Ctor) {
var options = Ctor.options;
if (Ctor.super) {
var superOptions = resolveConstructorOptions(Ctor.super);
var cachedSuperOptions = Ctor.superOptions;
if (superOptions !== cachedSuperOptions) {
// super option changed,
// need to resolve new options.
Ctor.superOptions = superOptions;
// check if there are any late-modified/attached options (#4976)
var modifiedOptions = resolveModifiedOptions(Ctor);
// update base extend options
if (modifiedOptions) {
extend(Ctor.extendOptions, modifiedOptions);
}
options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions);
if (options.name) {
options.components[options.name] = Ctor;
}
}
}
return options
}
function resolveModifiedOptions (Ctor) {
var modified;
var latest = Ctor.options;
var extended = Ctor.extendOptions;
var sealed = Ctor.sealedOptions;
for (var key in latest) {
if (latest[key] !== sealed[key]) {
if (!modified) { modified = {}; }
modified[key] = dedupe(latest[key], extended[key], sealed[key]);
}
}
return modified
}
function dedupe (latest, extended, sealed) {
// compare latest and sealed to ensure lifecycle hooks won't be duplicated
// between merges
if (Array.isArray(latest)) {
var res = [];
sealed = Array.isArray(sealed) ? sealed : [sealed];
extended = Array.isArray(extended) ? extended : [extended];
for (var i = 0; i < latest.length; i++) {
// push original options and not sealed options to exclude duplicated options
if (extended.indexOf(latest[i]) >= 0 || sealed.indexOf(latest[i]) < 0) {
res.push(latest[i]);
}
}
return res
} else {
return latest
}
}
function Vue$3 (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue$3)
) {
warn('Vue is a constructor and should be called with the `new` keyword');
}
this._init(options);
}
initMixin(Vue$3);
stateMixin(Vue$3);
eventsMixin(Vue$3);
lifecycleMixin(Vue$3);
renderMixin(Vue$3);
/* */
function initUse (Vue) {
Vue.use = function (plugin) {
/* istanbul ignore if */
if (plugin.installed) {
return this
}
// additional parameters
var args = toArray(arguments, 1);
args.unshift(this);
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args);
} else if (typeof plugin === 'function') {
plugin.apply(null, args);
}
plugin.installed = true;
return this
};
}
/* */
function initMixin$1 (Vue) {
Vue.mixin = function (mixin) {
this.options = mergeOptions(this.options, mixin);
return this
};
}
/* */
function initExtend (Vue) {
/**
* Each instance constructor, including Vue, has a unique
* cid. This enables us to create wrapped "child
* constructors" for prototypal inheritance and cache them.
*/
Vue.cid = 0;
var cid = 1;
/**
* Class inheritance
*/
Vue.extend = function (extendOptions) {
extendOptions = extendOptions || {};
var Super = this;
var SuperId = Super.cid;
var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {});
if (cachedCtors[SuperId]) {
return cachedCtors[SuperId]
}
var name = extendOptions.name || Super.options.name;
if (process.env.NODE_ENV !== 'production') {
if (!/^[a-zA-Z][\w-]*$/.test(name)) {
warn(
'Invalid component name: "' + name + '". Component names ' +
'can only contain alphanumeric characters and the hyphen, ' +
'and must start with a letter.'
);
}
}
var Sub = function VueComponent (options) {
this._init(options);
};
Sub.prototype = Object.create(Super.prototype);
Sub.prototype.constructor = Sub;
Sub.cid = cid++;
Sub.options = mergeOptions(
Super.options,
extendOptions
);
Sub['super'] = Super;
// For props and computed properties, we define the proxy getters on
// the Vue instances at extension time, on the extended prototype. This
// avoids Object.defineProperty calls for each instance created.
if (Sub.options.props) {
initProps$1(Sub);
}
if (Sub.options.computed) {
initComputed$1(Sub);
}
// allow further extension/mixin/plugin usage
Sub.extend = Super.extend;
Sub.mixin = Super.mixin;
Sub.use = Super.use;
// create asset registers, so extended classes
// can have their private assets too.
ASSET_TYPES.forEach(function (type) {
Sub[type] = Super[type];
});
// enable recursive self-lookup
if (name) {
Sub.options.components[name] = Sub;
}
// keep a reference to the super options at extension time.
// later at instantiation we can check if Super's options have
// been updated.
Sub.superOptions = Super.options;
Sub.extendOptions = extendOptions;
Sub.sealedOptions = extend({}, Sub.options);
// cache constructor
cachedCtors[SuperId] = Sub;
return Sub
};
}
function initProps$1 (Comp) {
var props = Comp.options.props;
for (var key in props) {
proxy(Comp.prototype, "_props", key);
}
}
function initComputed$1 (Comp) {
var computed = Comp.options.computed;
for (var key in computed) {
defineComputed(Comp.prototype, key, computed[key]);
}
}
/* */
function initAssetRegisters (Vue) {
/**
* Create asset registration methods.
*/
ASSET_TYPES.forEach(function (type) {
Vue[type] = function (
id,
definition
) {
if (!definition) {
return this.options[type + 's'][id]
} else {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
if (type === 'component' && config.isReservedTag(id)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + id
);
}
}
if (type === 'component' && isPlainObject(definition)) {
definition.name = definition.name || id;
definition = this.options._base.extend(definition);
}
if (type === 'directive' && typeof definition === 'function') {
definition = { bind: definition, update: definition };
}
this.options[type + 's'][id] = definition;
return definition
}
};
});
}
/* */
var patternTypes = [String, RegExp];
function getComponentName (opts) {
return opts && (opts.Ctor.options.name || opts.tag)
}
function matches (pattern, name) {
if (typeof pattern === 'string') {
return pattern.split(',').indexOf(name) > -1
} else if (isRegExp(pattern)) {
return pattern.test(name)
}
/* istanbul ignore next */
return false
}
function pruneCache (cache, current, filter) {
for (var key in cache) {
var cachedNode = cache[key];
if (cachedNode) {
var name = getComponentName(cachedNode.componentOptions);
if (name && !filter(name)) {
if (cachedNode !== current) {
pruneCacheEntry(cachedNode);
}
cache[key] = null;
}
}
}
}
function pruneCacheEntry (vnode) {
if (vnode) {
vnode.componentInstance.$destroy();
}
}
var KeepAlive = {
name: 'keep-alive',
abstract: true,
props: {
include: patternTypes,
exclude: patternTypes
},
created: function created () {
this.cache = Object.create(null);
},
destroyed: function destroyed () {
var this$1 = this;
for (var key in this$1.cache) {
pruneCacheEntry(this$1.cache[key]);
}
},
watch: {
include: function include (val) {
pruneCache(this.cache, this._vnode, function (name) { return matches(val, name); });
},
exclude: function exclude (val) {
pruneCache(this.cache, this._vnode, function (name) { return !matches(val, name); });
}
},
render: function render () {
var vnode = getFirstComponentChild(this.$slots.default);
var componentOptions = vnode && vnode.componentOptions;
if (componentOptions) {
// check pattern
var name = getComponentName(componentOptions);
if (name && (
(this.include && !matches(this.include, name)) ||
(this.exclude && matches(this.exclude, name))
)) {
return vnode
}
var key = vnode.key == null
// same constructor may get registered as different local components
// so cid alone is not enough (#3269)
? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '')
: vnode.key;
if (this.cache[key]) {
vnode.componentInstance = this.cache[key].componentInstance;
} else {
this.cache[key] = vnode;
}
vnode.data.keepAlive = true;
}
return vnode
}
};
var builtInComponents = {
KeepAlive: KeepAlive
};
/* */
function initGlobalAPI (Vue) {
// config
var configDef = {};
configDef.get = function () { return config; };
if (process.env.NODE_ENV !== 'production') {
configDef.set = function () {
warn(
'Do not replace the Vue.config object, set individual fields instead.'
);
};
}
Object.defineProperty(Vue, 'config', configDef);
// exposed util methods.
// NOTE: these are not considered part of the public API - avoid relying on
// them unless you are aware of the risk.
Vue.util = {
warn: warn,
extend: extend,
mergeOptions: mergeOptions,
defineReactive: defineReactive$$1
};
Vue.set = set;
Vue.delete = del;
Vue.nextTick = nextTick;
Vue.options = Object.create(null);
ASSET_TYPES.forEach(function (type) {
Vue.options[type + 's'] = Object.create(null);
});
// this is used to identify the "base" constructor to extend all plain-object
// components with in Weex's multi-instance scenarios.
Vue.options._base = Vue;
extend(Vue.options.components, builtInComponents);
initUse(Vue);
initMixin$1(Vue);
initExtend(Vue);
initAssetRegisters(Vue);
}
initGlobalAPI(Vue$3);
Object.defineProperty(Vue$3.prototype, '$isServer', {
get: isServerRendering
});
Object.defineProperty(Vue$3.prototype, '$ssrContext', {
get: function get () {
/* istanbul ignore next */
return this.$vnode.ssrContext
}
});
Vue$3.version = '2.3.4';
/* */
// these are reserved for web because they are directly compiled away
// during template compilation
var isReservedAttr = makeMap('style,class');
// attributes that should be using props for binding
var acceptValue = makeMap('input,textarea,option,select');
var mustUseProp = function (tag, type, attr) {
return (
(attr === 'value' && acceptValue(tag)) && type !== 'button' ||
(attr === 'selected' && tag === 'option') ||
(attr === 'checked' && tag === 'input') ||
(attr === 'muted' && tag === 'video')
)
};
var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck');
var isBooleanAttr = makeMap(
'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +
'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +
'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +
'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +
'required,reversed,scoped,seamless,selected,sortable,translate,' +
'truespeed,typemustmatch,visible'
);
var xlinkNS = 'http://www.w3.org/1999/xlink';
var isXlink = function (name) {
return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink'
};
var getXlinkProp = function (name) {
return isXlink(name) ? name.slice(6, name.length) : ''
};
var isFalsyAttrValue = function (val) {
return val == null || val === false
};
/* */
function genClassForVnode (vnode) {
var data = vnode.data;
var parentNode = vnode;
var childNode = vnode;
while (isDef(childNode.componentInstance)) {
childNode = childNode.componentInstance._vnode;
if (childNode.data) {
data = mergeClassData(childNode.data, data);
}
}
while (isDef(parentNode = parentNode.parent)) {
if (parentNode.data) {
data = mergeClassData(data, parentNode.data);
}
}
return genClassFromData(data)
}
function mergeClassData (child, parent) {
return {
staticClass: concat(child.staticClass, parent.staticClass),
class: isDef(child.class)
? [child.class, parent.class]
: parent.class
}
}
function genClassFromData (data) {
var dynamicClass = data.class;
var staticClass = data.staticClass;
if (isDef(staticClass) || isDef(dynamicClass)) {
return concat(staticClass, stringifyClass(dynamicClass))
}
/* istanbul ignore next */
return ''
}
function concat (a, b) {
return a ? b ? (a + ' ' + b) : a : (b || '')
}
function stringifyClass (value) {
if (isUndef(value)) {
return ''
}
if (typeof value === 'string') {
return value
}
var res = '';
if (Array.isArray(value)) {
var stringified;
for (var i = 0, l = value.length; i < l; i++) {
if (isDef(value[i])) {
if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') {
res += stringified + ' ';
}
}
}
return res.slice(0, -1)
}
if (isObject(value)) {
for (var key in value) {
if (value[key]) { res += key + ' '; }
}
return res.slice(0, -1)
}
/* istanbul ignore next */
return res
}
/* */
var namespaceMap = {
svg: 'http://www.w3.org/2000/svg',
math: 'http://www.w3.org/1998/Math/MathML'
};
var isHTMLTag = makeMap(
'html,body,base,head,link,meta,style,title,' +
'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
'div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,' +
'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
'embed,object,param,source,canvas,script,noscript,del,ins,' +
'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
'output,progress,select,textarea,' +
'details,dialog,menu,menuitem,summary,' +
'content,element,shadow,template'
);
// this map is intentionally selective, only covering SVG elements that may
// contain child elements.
var isSVG = makeMap(
'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' +
'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +
'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',
true
);
var isPreTag = function (tag) { return tag === 'pre'; };
var isReservedTag = function (tag) {
return isHTMLTag(tag) || isSVG(tag)
};
function getTagNamespace (tag) {
if (isSVG(tag)) {
return 'svg'
}
// basic support for MathML
// note it doesn't support other MathML elements being component roots
if (tag === 'math') {
return 'math'
}
}
var unknownElementCache = Object.create(null);
function isUnknownElement (tag) {
/* istanbul ignore if */
if (!inBrowser) {
return true
}
if (isReservedTag(tag)) {
return false
}
tag = tag.toLowerCase();
/* istanbul ignore if */
if (unknownElementCache[tag] != null) {
return unknownElementCache[tag]
}
var el = document.createElement(tag);
if (tag.indexOf('-') > -1) {
// http://stackoverflow.com/a/28210364/1070244
return (unknownElementCache[tag] = (
el.constructor === window.HTMLUnknownElement ||
el.constructor === window.HTMLElement
))
} else {
return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString()))
}
}
/* */
/**
* Query an element selector if it's not an element already.
*/
function query (el) {
if (typeof el === 'string') {
var selected = document.querySelector(el);
if (!selected) {
process.env.NODE_ENV !== 'production' && warn(
'Cannot find element: ' + el
);
return document.createElement('div')
}
return selected
} else {
return el
}
}
/* */
function createElement$1 (tagName, vnode) {
var elm = document.createElement(tagName);
if (tagName !== 'select') {
return elm
}
// false or null will remove the attribute but undefined will not
if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) {
elm.setAttribute('multiple', 'multiple');
}
return elm
}
function createElementNS (namespace, tagName) {
return document.createElementNS(namespaceMap[namespace], tagName)
}
function createTextNode (text) {
return document.createTextNode(text)
}
function createComment (text) {
return document.createComment(text)
}
function insertBefore (parentNode, newNode, referenceNode) {
parentNode.insertBefore(newNode, referenceNode);
}
function removeChild (node, child) {
node.removeChild(child);
}
function appendChild (node, child) {
node.appendChild(child);
}
function parentNode (node) {
return node.parentNode
}
function nextSibling (node) {
return node.nextSibling
}
function tagName (node) {
return node.tagName
}
function setTextContent (node, text) {
node.textContent = text;
}
function setAttribute (node, key, val) {
node.setAttribute(key, val);
}
var nodeOps = Object.freeze({
createElement: createElement$1,
createElementNS: createElementNS,
createTextNode: createTextNode,
createComment: createComment,
insertBefore: insertBefore,
removeChild: removeChild,
appendChild: appendChild,
parentNode: parentNode,
nextSibling: nextSibling,
tagName: tagName,
setTextContent: setTextContent,
setAttribute: setAttribute
});
/* */
var ref = {
create: function create (_, vnode) {
registerRef(vnode);
},
update: function update (oldVnode, vnode) {
if (oldVnode.data.ref !== vnode.data.ref) {
registerRef(oldVnode, true);
registerRef(vnode);
}
},
destroy: function destroy (vnode) {
registerRef(vnode, true);
}
};
function registerRef (vnode, isRemoval) {
var key = vnode.data.ref;
if (!key) { return }
var vm = vnode.context;
var ref = vnode.componentInstance || vnode.elm;
var refs = vm.$refs;
if (isRemoval) {
if (Array.isArray(refs[key])) {
remove(refs[key], ref);
} else if (refs[key] === ref) {
refs[key] = undefined;
}
} else {
if (vnode.data.refInFor) {
if (Array.isArray(refs[key]) && refs[key].indexOf(ref) < 0) {
refs[key].push(ref);
} else {
refs[key] = [ref];
}
} else {
refs[key] = ref;
}
}
}
/**
* Virtual DOM patching algorithm based on Snabbdom by
* Simon Friis Vindum (@paldepind)
* Licensed under the MIT License
* https://github.com/paldepind/snabbdom/blob/master/LICENSE
*
* modified by Evan You (@yyx990803)
*
/*
* Not type-checking this because this file is perf-critical and the cost
* of making flow understand it is not worth it.
*/
var emptyNode = new VNode('', {}, []);
var hooks = ['create', 'activate', 'update', 'remove', 'destroy'];
function sameVnode (a, b) {
return (
a.key === b.key &&
a.tag === b.tag &&
a.isComment === b.isComment &&
isDef(a.data) === isDef(b.data) &&
sameInputType(a, b)
)
}
// Some browsers do not support dynamically changing type for <input>
// so they need to be treated as different nodes
function sameInputType (a, b) {
if (a.tag !== 'input') { return true }
var i;
var typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type;
var typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type;
return typeA === typeB
}
function createKeyToOldIdx (children, beginIdx, endIdx) {
var i, key;
var map = {};
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key;
if (isDef(key)) { map[key] = i; }
}
return map
}
function createPatchFunction (backend) {
var i, j;
var cbs = {};
var modules = backend.modules;
var nodeOps = backend.nodeOps;
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = [];
for (j = 0; j < modules.length; ++j) {
if (isDef(modules[j][hooks[i]])) {
cbs[hooks[i]].push(modules[j][hooks[i]]);
}
}
}
function emptyNodeAt (elm) {
return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
}
function createRmCb (childElm, listeners) {
function remove$$1 () {
if (--remove$$1.listeners === 0) {
removeNode(childElm);
}
}
remove$$1.listeners = listeners;
return remove$$1
}
function removeNode (el) {
var parent = nodeOps.parentNode(el);
// element may have already been removed due to v-html / v-text
if (isDef(parent)) {
nodeOps.removeChild(parent, el);
}
}
var inPre = 0;
function createElm (vnode, insertedVnodeQueue, parentElm, refElm, nested) {
vnode.isRootInsert = !nested; // for transition enter check
if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
return
}
var data = vnode.data;
var children = vnode.children;
var tag = vnode.tag;
if (isDef(tag)) {
if (process.env.NODE_ENV !== 'production') {
if (data && data.pre) {
inPre++;
}
if (
!inPre &&
!vnode.ns &&
!(config.ignoredElements.length && config.ignoredElements.indexOf(tag) > -1) &&
config.isUnknownElement(tag)
) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
);
}
}
vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag, vnode);
setScope(vnode);
/* istanbul ignore if */
{
createChildren(vnode, children, insertedVnodeQueue);
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
}
insert(parentElm, vnode.elm, refElm);
}
if (process.env.NODE_ENV !== 'production' && data && data.pre) {
inPre--;
}
} else if (isTrue(vnode.isComment)) {
vnode.elm = nodeOps.createComment(vnode.text);
insert(parentElm, vnode.elm, refElm);
} else {
vnode.elm = nodeOps.createTextNode(vnode.text);
insert(parentElm, vnode.elm, refElm);
}
}
function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
var i = vnode.data;
if (isDef(i)) {
var isReactivated = isDef(vnode.componentInstance) && i.keepAlive;
if (isDef(i = i.hook) && isDef(i = i.init)) {
i(vnode, false /* hydrating */, parentElm, refElm);
}
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(vnode.componentInstance)) {
initComponent(vnode, insertedVnodeQueue);
if (isTrue(isReactivated)) {
reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm);
}
return true
}
}
}
function initComponent (vnode, insertedVnodeQueue) {
if (isDef(vnode.data.pendingInsert)) {
insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert);
vnode.data.pendingInsert = null;
}
vnode.elm = vnode.componentInstance.$el;
if (isPatchable(vnode)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
setScope(vnode);
} else {
// empty component root.
// skip all element-related modules except for ref (#3455)
registerRef(vnode);
// make sure to invoke the insert hook
insertedVnodeQueue.push(vnode);
}
}
function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
var i;
// hack for #4339: a reactivated component with inner transition
// does not trigger because the inner node's created hooks are not called
// again. It's not ideal to involve module-specific logic in here but
// there doesn't seem to be a better way to do it.
var innerNode = vnode;
while (innerNode.componentInstance) {
innerNode = innerNode.componentInstance._vnode;
if (isDef(i = innerNode.data) && isDef(i = i.transition)) {
for (i = 0; i < cbs.activate.length; ++i) {
cbs.activate[i](emptyNode, innerNode);
}
insertedVnodeQueue.push(innerNode);
break
}
}
// unlike a newly created component,
// a reactivated keep-alive component doesn't insert itself
insert(parentElm, vnode.elm, refElm);
}
function insert (parent, elm, ref) {
if (isDef(parent)) {
if (isDef(ref)) {
if (ref.parentNode === parent) {
nodeOps.insertBefore(parent, elm, ref);
}
} else {
nodeOps.appendChild(parent, elm);
}
}
}
function createChildren (vnode, children, insertedVnodeQueue) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; ++i) {
createElm(children[i], insertedVnodeQueue, vnode.elm, null, true);
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text));
}
}
function isPatchable (vnode) {
while (vnode.componentInstance) {
vnode = vnode.componentInstance._vnode;
}
return isDef(vnode.tag)
}
function invokeCreateHooks (vnode, insertedVnodeQueue) {
for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {
cbs.create[i$1](emptyNode, vnode);
}
i = vnode.data.hook; // Reuse variable
if (isDef(i)) {
if (isDef(i.create)) { i.create(emptyNode, vnode); }
if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); }
}
}
// set scope id attribute for scoped CSS.
// this is implemented as a special case to avoid the overhead
// of going through the normal attribute patching process.
function setScope (vnode) {
var i;
var ancestor = vnode;
while (ancestor) {
if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '');
}
ancestor = ancestor.parent;
}
// for slot content they should also get the scopeId from the host instance.
if (isDef(i = activeInstance) &&
i !== vnode.context &&
isDef(i = i.$options._scopeId)
) {
nodeOps.setAttribute(vnode.elm, i, '');
}
}
function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm);
}
}
function invokeDestroyHook (vnode) {
var i, j;
var data = vnode.data;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); }
for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); }
}
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j]);
}
}
}
function removeVnodes (parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
var ch = vnodes[startIdx];
if (isDef(ch)) {
if (isDef(ch.tag)) {
removeAndInvokeRemoveHook(ch);
invokeDestroyHook(ch);
} else { // Text node
removeNode(ch.elm);
}
}
}
}
function removeAndInvokeRemoveHook (vnode, rm) {
if (isDef(rm) || isDef(vnode.data)) {
var i;
var listeners = cbs.remove.length + 1;
if (isDef(rm)) {
// we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners;
} else {
// directly removing
rm = createRmCb(vnode.elm, listeners);
}
// recursively invoke hooks on child component root node
if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) {
removeAndInvokeRemoveHook(i, rm);
}
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](vnode, rm);
}
if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
i(vnode, rm);
} else {
rm();
}
} else {
removeNode(vnode.elm);
}
}
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
var oldStartIdx = 0;
var newStartIdx = 0;
var oldEndIdx = oldCh.length - 1;
var oldStartVnode = oldCh[0];
var oldEndVnode = oldCh[oldEndIdx];
var newEndIdx = newCh.length - 1;
var newStartVnode = newCh[0];
var newEndVnode = newCh[newEndIdx];
var oldKeyToIdx, idxInOld, elmToMove, refElm;
// removeOnly is a special flag used only by <transition-group>
// to ensure removed elements stay in correct relative positions
// during leaving transitions
var canMove = !removeOnly;
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx];
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue);
oldStartVnode = oldCh[++oldStartIdx];
newStartVnode = newCh[++newStartIdx];
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue);
oldEndVnode = oldCh[--oldEndIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue);
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm));
oldStartVnode = oldCh[++oldStartIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue);
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
oldEndVnode = oldCh[--oldEndIdx];
newStartVnode = newCh[++newStartIdx];
} else {
if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); }
idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : null;
if (isUndef(idxInOld)) { // New element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
elmToMove = oldCh[idxInOld];
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !elmToMove) {
warn(
'It seems there are duplicate keys that is causing an update error. ' +
'Make sure each v-for item has a unique key.'
);
}
if (sameVnode(elmToMove, newStartVnode)) {
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);
oldCh[idxInOld] = undefined;
canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
// same key but different element. treat as new element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
}
}
}
}
if (oldStartIdx > oldEndIdx) {
refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;
addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
}
}
function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) {
if (oldVnode === vnode) {
return
}
// reuse element for static trees.
// note we only do this if the vnode is cloned -
// if the new node is not cloned it means the render functions have been
// reset by the hot-reload-api and we need to do a proper re-render.
if (isTrue(vnode.isStatic) &&
isTrue(oldVnode.isStatic) &&
vnode.key === oldVnode.key &&
(isTrue(vnode.isCloned) || isTrue(vnode.isOnce))
) {
vnode.elm = oldVnode.elm;
vnode.componentInstance = oldVnode.componentInstance;
return
}
var i;
var data = vnode.data;
if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) {
i(oldVnode, vnode);
}
var elm = vnode.elm = oldVnode.elm;
var oldCh = oldVnode.children;
var ch = vnode.children;
if (isDef(data) && isPatchable(vnode)) {
for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); }
if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); }
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); }
} else if (isDef(ch)) {
if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); }
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1);
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '');
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text);
}
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); }
}
}
function invokeInsertHook (vnode, queue, initial) {
// delay insert hooks for component root nodes, invoke them after the
// element is really inserted
if (isTrue(initial) && isDef(vnode.parent)) {
vnode.parent.data.pendingInsert = queue;
} else {
for (var i = 0; i < queue.length; ++i) {
queue[i].data.hook.insert(queue[i]);
}
}
}
var bailed = false;
// list of modules that can skip create hook during hydration because they
// are already rendered on the client or has no need for initialization
var isRenderedModule = makeMap('attrs,style,class,staticClass,staticStyle,key');
// Note: this is a browser-only function so we can assume elms are DOM nodes.
function hydrate (elm, vnode, insertedVnodeQueue) {
if (process.env.NODE_ENV !== 'production') {
if (!assertNodeMatch(elm, vnode)) {
return false
}
}
vnode.elm = elm;
var tag = vnode.tag;
var data = vnode.data;
var children = vnode.children;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); }
if (isDef(i = vnode.componentInstance)) {
// child component. it should have hydrated its own tree.
initComponent(vnode, insertedVnodeQueue);
return true
}
}
if (isDef(tag)) {
if (isDef(children)) {
// empty element, allow client to pick up and populate children
if (!elm.hasChildNodes()) {
createChildren(vnode, children, insertedVnodeQueue);
} else {
var childrenMatch = true;
var childNode = elm.firstChild;
for (var i$1 = 0; i$1 < children.length; i$1++) {
if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue)) {
childrenMatch = false;
break
}
childNode = childNode.nextSibling;
}
// if childNode is not null, it means the actual childNodes list is
// longer than the virtual children list.
if (!childrenMatch || childNode) {
if (process.env.NODE_ENV !== 'production' &&
typeof console !== 'undefined' &&
!bailed
) {
bailed = true;
console.warn('Parent: ', elm);
console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children);
}
return false
}
}
}
if (isDef(data)) {
for (var key in data) {
if (!isRenderedModule(key)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
break
}
}
}
} else if (elm.data !== vnode.text) {
elm.data = vnode.text;
}
return true
}
function assertNodeMatch (node, vnode) {
if (isDef(vnode.tag)) {
return (
vnode.tag.indexOf('vue-component') === 0 ||
vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase())
)
} else {
return node.nodeType === (vnode.isComment ? 8 : 3)
}
}
return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) {
if (isUndef(vnode)) {
if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); }
return
}
var isInitialPatch = false;
var insertedVnodeQueue = [];
if (isUndef(oldVnode)) {
// empty mount (likely as component), create new root element
isInitialPatch = true;
createElm(vnode, insertedVnodeQueue, parentElm, refElm);
} else {
var isRealElement = isDef(oldVnode.nodeType);
if (!isRealElement && sameVnode(oldVnode, vnode)) {
// patch existing root node
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly);
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {
oldVnode.removeAttribute(SSR_ATTR);
hydrating = true;
}
if (isTrue(hydrating)) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true);
return oldVnode
} else if (process.env.NODE_ENV !== 'production') {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
);
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode);
}
// replacing existing element
var oldElm = oldVnode.elm;
var parentElm$1 = nodeOps.parentNode(oldElm);
createElm(
vnode,
insertedVnodeQueue,
// extremely rare edge case: do not insert if old element is in a
// leaving transition. Only happens when combining transition +
// keep-alive + HOCs. (#4590)
oldElm._leaveCb ? null : parentElm$1,
nodeOps.nextSibling(oldElm)
);
if (isDef(vnode.parent)) {
// component root element replaced.
// update parent placeholder node element, recursively
var ancestor = vnode.parent;
while (ancestor) {
ancestor.elm = vnode.elm;
ancestor = ancestor.parent;
}
if (isPatchable(vnode)) {
for (var i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode.parent);
}
}
}
if (isDef(parentElm$1)) {
removeVnodes(parentElm$1, [oldVnode], 0, 0);
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode);
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch);
return vnode.elm
}
}
/* */
var directives = {
create: updateDirectives,
update: updateDirectives,
destroy: function unbindDirectives (vnode) {
updateDirectives(vnode, emptyNode);
}
};
function updateDirectives (oldVnode, vnode) {
if (oldVnode.data.directives || vnode.data.directives) {
_update(oldVnode, vnode);
}
}
function _update (oldVnode, vnode) {
var isCreate = oldVnode === emptyNode;
var isDestroy = vnode === emptyNode;
var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context);
var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context);
var dirsWithInsert = [];
var dirsWithPostpatch = [];
var key, oldDir, dir;
for (key in newDirs) {
oldDir = oldDirs[key];
dir = newDirs[key];
if (!oldDir) {
// new directive, bind
callHook$1(dir, 'bind', vnode, oldVnode);
if (dir.def && dir.def.inserted) {
dirsWithInsert.push(dir);
}
} else {
// existing directive, update
dir.oldValue = oldDir.value;
callHook$1(dir, 'update', vnode, oldVnode);
if (dir.def && dir.def.componentUpdated) {
dirsWithPostpatch.push(dir);
}
}
}
if (dirsWithInsert.length) {
var callInsert = function () {
for (var i = 0; i < dirsWithInsert.length; i++) {
callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode);
}
};
if (isCreate) {
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', callInsert);
} else {
callInsert();
}
}
if (dirsWithPostpatch.length) {
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'postpatch', function () {
for (var i = 0; i < dirsWithPostpatch.length; i++) {
callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode);
}
});
}
if (!isCreate) {
for (key in oldDirs) {
if (!newDirs[key]) {
// no longer present, unbind
callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy);
}
}
}
}
var emptyModifiers = Object.create(null);
function normalizeDirectives$1 (
dirs,
vm
) {
var res = Object.create(null);
if (!dirs) {
return res
}
var i, dir;
for (i = 0; i < dirs.length; i++) {
dir = dirs[i];
if (!dir.modifiers) {
dir.modifiers = emptyModifiers;
}
res[getRawDirName(dir)] = dir;
dir.def = resolveAsset(vm.$options, 'directives', dir.name, true);
}
return res
}
function getRawDirName (dir) {
return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.')))
}
function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) {
var fn = dir.def && dir.def[hook];
if (fn) {
try {
fn(vnode.elm, dir, vnode, oldVnode, isDestroy);
} catch (e) {
handleError(e, vnode.context, ("directive " + (dir.name) + " " + hook + " hook"));
}
}
}
var baseModules = [
ref,
directives
];
/* */
function updateAttrs (oldVnode, vnode) {
if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) {
return
}
var key, cur, old;
var elm = vnode.elm;
var oldAttrs = oldVnode.data.attrs || {};
var attrs = vnode.data.attrs || {};
// clone observed objects, as the user probably wants to mutate it
if (isDef(attrs.__ob__)) {
attrs = vnode.data.attrs = extend({}, attrs);
}
for (key in attrs) {
cur = attrs[key];
old = oldAttrs[key];
if (old !== cur) {
setAttr(elm, key, cur);
}
}
// #4391: in IE9, setting type can reset value for input[type=radio]
/* istanbul ignore if */
if (isIE9 && attrs.value !== oldAttrs.value) {
setAttr(elm, 'value', attrs.value);
}
for (key in oldAttrs) {
if (isUndef(attrs[key])) {
if (isXlink(key)) {
elm.removeAttributeNS(xlinkNS, getXlinkProp(key));
} else if (!isEnumeratedAttr(key)) {
elm.removeAttribute(key);
}
}
}
}
function setAttr (el, key, value) {
if (isBooleanAttr(key)) {
// set attribute for blank value
// e.g. <option disabled>Select one</option>
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
el.setAttribute(key, key);
}
} else if (isEnumeratedAttr(key)) {
el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true');
} else if (isXlink(key)) {
if (isFalsyAttrValue(value)) {
el.removeAttributeNS(xlinkNS, getXlinkProp(key));
} else {
el.setAttributeNS(xlinkNS, key, value);
}
} else {
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
el.setAttribute(key, value);
}
}
}
var attrs = {
create: updateAttrs,
update: updateAttrs
};
/* */
function updateClass (oldVnode, vnode) {
var el = vnode.elm;
var data = vnode.data;
var oldData = oldVnode.data;
if (
isUndef(data.staticClass) &&
isUndef(data.class) && (
isUndef(oldData) || (
isUndef(oldData.staticClass) &&
isUndef(oldData.class)
)
)
) {
return
}
var cls = genClassForVnode(vnode);
// handle transition classes
var transitionClass = el._transitionClasses;
if (isDef(transitionClass)) {
cls = concat(cls, stringifyClass(transitionClass));
}
// set the class
if (cls !== el._prevClass) {
el.setAttribute('class', cls);
el._prevClass = cls;
}
}
var klass = {
create: updateClass,
update: updateClass
};
/* */
var validDivisionCharRE = /[\w).+\-_$\]]/;
function parseFilters (exp) {
var inSingle = false;
var inDouble = false;
var inTemplateString = false;
var inRegex = false;
var curly = 0;
var square = 0;
var paren = 0;
var lastFilterIndex = 0;
var c, prev, i, expression, filters;
for (i = 0; i < exp.length; i++) {
prev = c;
c = exp.charCodeAt(i);
if (inSingle) {
if (c === 0x27 && prev !== 0x5C) { inSingle = false; }
} else if (inDouble) {
if (c === 0x22 && prev !== 0x5C) { inDouble = false; }
} else if (inTemplateString) {
if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; }
} else if (inRegex) {
if (c === 0x2f && prev !== 0x5C) { inRegex = false; }
} else if (
c === 0x7C && // pipe
exp.charCodeAt(i + 1) !== 0x7C &&
exp.charCodeAt(i - 1) !== 0x7C &&
!curly && !square && !paren
) {
if (expression === undefined) {
// first filter, end of expression
lastFilterIndex = i + 1;
expression = exp.slice(0, i).trim();
} else {
pushFilter();
}
} else {
switch (c) {
case 0x22: inDouble = true; break // "
case 0x27: inSingle = true; break // '
case 0x60: inTemplateString = true; break // `
case 0x28: paren++; break // (
case 0x29: paren--; break // )
case 0x5B: square++; break // [
case 0x5D: square--; break // ]
case 0x7B: curly++; break // {
case 0x7D: curly--; break // }
}
if (c === 0x2f) { // /
var j = i - 1;
var p = (void 0);
// find first non-whitespace prev char
for (; j >= 0; j--) {
p = exp.charAt(j);
if (p !== ' ') { break }
}
if (!p || !validDivisionCharRE.test(p)) {
inRegex = true;
}
}
}
}
if (expression === undefined) {
expression = exp.slice(0, i).trim();
} else if (lastFilterIndex !== 0) {
pushFilter();
}
function pushFilter () {
(filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim());
lastFilterIndex = i + 1;
}
if (filters) {
for (i = 0; i < filters.length; i++) {
expression = wrapFilter(expression, filters[i]);
}
}
return expression
}
function wrapFilter (exp, filter) {
var i = filter.indexOf('(');
if (i < 0) {
// _f: resolveFilter
return ("_f(\"" + filter + "\")(" + exp + ")")
} else {
var name = filter.slice(0, i);
var args = filter.slice(i + 1);
return ("_f(\"" + name + "\")(" + exp + "," + args)
}
}
/* */
function baseWarn (msg) {
console.error(("[Vue compiler]: " + msg));
}
function pluckModuleFunction (
modules,
key
) {
return modules
? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; })
: []
}
function addProp (el, name, value) {
(el.props || (el.props = [])).push({ name: name, value: value });
}
function addAttr (el, name, value) {
(el.attrs || (el.attrs = [])).push({ name: name, value: value });
}
function addDirective (
el,
name,
rawName,
value,
arg,
modifiers
) {
(el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers });
}
function addHandler (
el,
name,
value,
modifiers,
important,
warn
) {
// warn prevent and passive modifier
/* istanbul ignore if */
if (
process.env.NODE_ENV !== 'production' && warn &&
modifiers && modifiers.prevent && modifiers.passive
) {
warn(
'passive and prevent can\'t be used together. ' +
'Passive handler can\'t prevent default event.'
);
}
// check capture modifier
if (modifiers && modifiers.capture) {
delete modifiers.capture;
name = '!' + name; // mark the event as captured
}
if (modifiers && modifiers.once) {
delete modifiers.once;
name = '~' + name; // mark the event as once
}
/* istanbul ignore if */
if (modifiers && modifiers.passive) {
delete modifiers.passive;
name = '&' + name; // mark the event as passive
}
var events;
if (modifiers && modifiers.native) {
delete modifiers.native;
events = el.nativeEvents || (el.nativeEvents = {});
} else {
events = el.events || (el.events = {});
}
var newHandler = { value: value, modifiers: modifiers };
var handlers = events[name];
/* istanbul ignore if */
if (Array.isArray(handlers)) {
important ? handlers.unshift(newHandler) : handlers.push(newHandler);
} else if (handlers) {
events[name] = important ? [newHandler, handlers] : [handlers, newHandler];
} else {
events[name] = newHandler;
}
}
function getBindingAttr (
el,
name,
getStatic
) {
var dynamicValue =
getAndRemoveAttr(el, ':' + name) ||
getAndRemoveAttr(el, 'v-bind:' + name);
if (dynamicValue != null) {
return parseFilters(dynamicValue)
} else if (getStatic !== false) {
var staticValue = getAndRemoveAttr(el, name);
if (staticValue != null) {
return JSON.stringify(staticValue)
}
}
}
function getAndRemoveAttr (el, name) {
var val;
if ((val = el.attrsMap[name]) != null) {
var list = el.attrsList;
for (var i = 0, l = list.length; i < l; i++) {
if (list[i].name === name) {
list.splice(i, 1);
break
}
}
}
return val
}
/* */
/**
* Cross-platform code generation for component v-model
*/
function genComponentModel (
el,
value,
modifiers
) {
var ref = modifiers || {};
var number = ref.number;
var trim = ref.trim;
var baseValueExpression = '$$v';
var valueExpression = baseValueExpression;
if (trim) {
valueExpression =
"(typeof " + baseValueExpression + " === 'string'" +
"? " + baseValueExpression + ".trim()" +
": " + baseValueExpression + ")";
}
if (number) {
valueExpression = "_n(" + valueExpression + ")";
}
var assignment = genAssignmentCode(value, valueExpression);
el.model = {
value: ("(" + value + ")"),
expression: ("\"" + value + "\""),
callback: ("function (" + baseValueExpression + ") {" + assignment + "}")
};
}
/**
* Cross-platform codegen helper for generating v-model value assignment code.
*/
function genAssignmentCode (
value,
assignment
) {
var modelRs = parseModel(value);
if (modelRs.idx === null) {
return (value + "=" + assignment)
} else {
return "var $$exp = " + (modelRs.exp) + ", $$idx = " + (modelRs.idx) + ";" +
"if (!Array.isArray($$exp)){" +
value + "=" + assignment + "}" +
"else{$$exp.splice($$idx, 1, " + assignment + ")}"
}
}
/**
* parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
*
* for loop possible cases:
*
* - test
* - test[idx]
* - test[test1[idx]]
* - test["a"][idx]
* - xxx.test[a[a].test1[idx]]
* - test.xxx.a["asa"][test1[idx]]
*
*/
var len;
var str;
var chr;
var index$1;
var expressionPos;
var expressionEndPos;
function parseModel (val) {
str = val;
len = str.length;
index$1 = expressionPos = expressionEndPos = 0;
if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {
return {
exp: val,
idx: null
}
}
while (!eof()) {
chr = next();
/* istanbul ignore if */
if (isStringStart(chr)) {
parseString(chr);
} else if (chr === 0x5B) {
parseBracket(chr);
}
}
return {
exp: val.substring(0, expressionPos),
idx: val.substring(expressionPos + 1, expressionEndPos)
}
}
function next () {
return str.charCodeAt(++index$1)
}
function eof () {
return index$1 >= len
}
function isStringStart (chr) {
return chr === 0x22 || chr === 0x27
}
function parseBracket (chr) {
var inBracket = 1;
expressionPos = index$1;
while (!eof()) {
chr = next();
if (isStringStart(chr)) {
parseString(chr);
continue
}
if (chr === 0x5B) { inBracket++; }
if (chr === 0x5D) { inBracket--; }
if (inBracket === 0) {
expressionEndPos = index$1;
break
}
}
}
function parseString (chr) {
var stringQuote = chr;
while (!eof()) {
chr = next();
if (chr === stringQuote) {
break
}
}
}
/* */
var warn$1;
// in some cases, the event used has to be determined at runtime
// so we used some reserved tokens during compile.
var RANGE_TOKEN = '__r';
var CHECKBOX_RADIO_TOKEN = '__c';
function model (
el,
dir,
_warn
) {
warn$1 = _warn;
var value = dir.value;
var modifiers = dir.modifiers;
var tag = el.tag;
var type = el.attrsMap.type;
if (process.env.NODE_ENV !== 'production') {
var dynamicType = el.attrsMap['v-bind:type'] || el.attrsMap[':type'];
if (tag === 'input' && dynamicType) {
warn$1(
"<input :type=\"" + dynamicType + "\" v-model=\"" + value + "\">:\n" +
"v-model does not support dynamic input types. Use v-if branches instead."
);
}
// inputs with type="file" are read only and setting the input's
// value will throw an error.
if (tag === 'input' && type === 'file') {
warn$1(
"<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" +
"File inputs are read only. Use a v-on:change listener instead."
);
}
}
if (tag === 'select') {
genSelect(el, value, modifiers);
} else if (tag === 'input' && type === 'checkbox') {
genCheckboxModel(el, value, modifiers);
} else if (tag === 'input' && type === 'radio') {
genRadioModel(el, value, modifiers);
} else if (tag === 'input' || tag === 'textarea') {
genDefaultModel(el, value, modifiers);
} else if (!config.isReservedTag(tag)) {
genComponentModel(el, value, modifiers);
// component v-model doesn't need extra runtime
return false
} else if (process.env.NODE_ENV !== 'production') {
warn$1(
"<" + (el.tag) + " v-model=\"" + value + "\">: " +
"v-model is not supported on this element type. " +
'If you are working with contenteditable, it\'s recommended to ' +
'wrap a library dedicated for that purpose inside a custom component.'
);
}
// ensure runtime directive metadata
return true
}
function genCheckboxModel (
el,
value,
modifiers
) {
var number = modifiers && modifiers.number;
var valueBinding = getBindingAttr(el, 'value') || 'null';
var trueValueBinding = getBindingAttr(el, 'true-value') || 'true';
var falseValueBinding = getBindingAttr(el, 'false-value') || 'false';
addProp(el, 'checked',
"Array.isArray(" + value + ")" +
"?_i(" + value + "," + valueBinding + ")>-1" + (
trueValueBinding === 'true'
? (":(" + value + ")")
: (":_q(" + value + "," + trueValueBinding + ")")
)
);
addHandler(el, CHECKBOX_RADIO_TOKEN,
"var $$a=" + value + "," +
'$$el=$event.target,' +
"$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" +
'if(Array.isArray($$a)){' +
"var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," +
'$$i=_i($$a,$$v);' +
"if($$c){$$i<0&&(" + value + "=$$a.concat($$v))}" +
"else{$$i>-1&&(" + value + "=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}" +
"}else{" + (genAssignmentCode(value, '$$c')) + "}",
null, true
);
}
function genRadioModel (
el,
value,
modifiers
) {
var number = modifiers && modifiers.number;
var valueBinding = getBindingAttr(el, 'value') || 'null';
valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding;
addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")"));
addHandler(el, CHECKBOX_RADIO_TOKEN, genAssignmentCode(value, valueBinding), null, true);
}
function genSelect (
el,
value,
modifiers
) {
var number = modifiers && modifiers.number;
var selectedVal = "Array.prototype.filter" +
".call($event.target.options,function(o){return o.selected})" +
".map(function(o){var val = \"_value\" in o ? o._value : o.value;" +
"return " + (number ? '_n(val)' : 'val') + "})";
var assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]';
var code = "var $$selectedVal = " + selectedVal + ";";
code = code + " " + (genAssignmentCode(value, assignment));
addHandler(el, 'change', code, null, true);
}
function genDefaultModel (
el,
value,
modifiers
) {
var type = el.attrsMap.type;
var ref = modifiers || {};
var lazy = ref.lazy;
var number = ref.number;
var trim = ref.trim;
var needCompositionGuard = !lazy && type !== 'range';
var event = lazy
? 'change'
: type === 'range'
? RANGE_TOKEN
: 'input';
var valueExpression = '$event.target.value';
if (trim) {
valueExpression = "$event.target.value.trim()";
}
if (number) {
valueExpression = "_n(" + valueExpression + ")";
}
var code = genAssignmentCode(value, valueExpression);
if (needCompositionGuard) {
code = "if($event.target.composing)return;" + code;
}
addProp(el, 'value', ("(" + value + ")"));
addHandler(el, event, code, null, true);
if (trim || number || type === 'number') {
addHandler(el, 'blur', '$forceUpdate()');
}
}
/* */
// normalize v-model event tokens that can only be determined at runtime.
// it's important to place the event as the first in the array because
// the whole point is ensuring the v-model callback gets called before
// user-attached handlers.
function normalizeEvents (on) {
var event;
/* istanbul ignore if */
if (isDef(on[RANGE_TOKEN])) {
// IE input[type=range] only supports `change` event
event = isIE ? 'change' : 'input';
on[event] = [].concat(on[RANGE_TOKEN], on[event] || []);
delete on[RANGE_TOKEN];
}
if (isDef(on[CHECKBOX_RADIO_TOKEN])) {
// Chrome fires microtasks in between click/change, leads to #4521
event = isChrome ? 'click' : 'change';
on[event] = [].concat(on[CHECKBOX_RADIO_TOKEN], on[event] || []);
delete on[CHECKBOX_RADIO_TOKEN];
}
}
var target$1;
function add$1 (
event,
handler,
once$$1,
capture,
passive
) {
if (once$$1) {
var oldHandler = handler;
var _target = target$1; // save current target element in closure
handler = function (ev) {
var res = arguments.length === 1
? oldHandler(ev)
: oldHandler.apply(null, arguments);
if (res !== null) {
remove$2(event, handler, capture, _target);
}
};
}
target$1.addEventListener(
event,
handler,
supportsPassive
? { capture: capture, passive: passive }
: capture
);
}
function remove$2 (
event,
handler,
capture,
_target
) {
(_target || target$1).removeEventListener(event, handler, capture);
}
function updateDOMListeners (oldVnode, vnode) {
if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) {
return
}
var on = vnode.data.on || {};
var oldOn = oldVnode.data.on || {};
target$1 = vnode.elm;
normalizeEvents(on);
updateListeners(on, oldOn, add$1, remove$2, vnode.context);
}
var events = {
create: updateDOMListeners,
update: updateDOMListeners
};
/* */
function updateDOMProps (oldVnode, vnode) {
if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) {
return
}
var key, cur;
var elm = vnode.elm;
var oldProps = oldVnode.data.domProps || {};
var props = vnode.data.domProps || {};
// clone observed objects, as the user probably wants to mutate it
if (isDef(props.__ob__)) {
props = vnode.data.domProps = extend({}, props);
}
for (key in oldProps) {
if (isUndef(props[key])) {
elm[key] = '';
}
}
for (key in props) {
cur = props[key];
// ignore children if the node has textContent or innerHTML,
// as these will throw away existing DOM nodes and cause removal errors
// on subsequent patches (#3360)
if (key === 'textContent' || key === 'innerHTML') {
if (vnode.children) { vnode.children.length = 0; }
if (cur === oldProps[key]) { continue }
}
if (key === 'value') {
// store value as _value as well since
// non-string values will be stringified
elm._value = cur;
// avoid resetting cursor position when value is the same
var strCur = isUndef(cur) ? '' : String(cur);
if (shouldUpdateValue(elm, vnode, strCur)) {
elm.value = strCur;
}
} else {
elm[key] = cur;
}
}
}
// check platforms/web/util/attrs.js acceptValue
function shouldUpdateValue (
elm,
vnode,
checkVal
) {
return (!elm.composing && (
vnode.tag === 'option' ||
isDirty(elm, checkVal) ||
isInputChanged(elm, checkVal)
))
}
function isDirty (elm, checkVal) {
// return true when textbox (.number and .trim) loses focus and its value is not equal to the updated value
return document.activeElement !== elm && elm.value !== checkVal
}
function isInputChanged (elm, newVal) {
var value = elm.value;
var modifiers = elm._vModifiers; // injected by v-model runtime
if ((isDef(modifiers) && modifiers.number) || elm.type === 'number') {
return toNumber(value) !== toNumber(newVal)
}
if (isDef(modifiers) && modifiers.trim) {
return value.trim() !== newVal.trim()
}
return value !== newVal
}
var domProps = {
create: updateDOMProps,
update: updateDOMProps
};
/* */
var parseStyleText = cached(function (cssText) {
var res = {};
var listDelimiter = /;(?![^(]*\))/g;
var propertyDelimiter = /:(.+)/;
cssText.split(listDelimiter).forEach(function (item) {
if (item) {
var tmp = item.split(propertyDelimiter);
tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim());
}
});
return res
});
// merge static and dynamic style data on the same vnode
function normalizeStyleData (data) {
var style = normalizeStyleBinding(data.style);
// static style is pre-processed into an object during compilation
// and is always a fresh object, so it's safe to merge into it
return data.staticStyle
? extend(data.staticStyle, style)
: style
}
// normalize possible array / string values into Object
function normalizeStyleBinding (bindingStyle) {
if (Array.isArray(bindingStyle)) {
return toObject(bindingStyle)
}
if (typeof bindingStyle === 'string') {
return parseStyleText(bindingStyle)
}
return bindingStyle
}
/**
* parent component style should be after child's
* so that parent component's style could override it
*/
function getStyle (vnode, checkChild) {
var res = {};
var styleData;
if (checkChild) {
var childNode = vnode;
while (childNode.componentInstance) {
childNode = childNode.componentInstance._vnode;
if (childNode.data && (styleData = normalizeStyleData(childNode.data))) {
extend(res, styleData);
}
}
}
if ((styleData = normalizeStyleData(vnode.data))) {
extend(res, styleData);
}
var parentNode = vnode;
while ((parentNode = parentNode.parent)) {
if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) {
extend(res, styleData);
}
}
return res
}
/* */
var cssVarRE = /^--/;
var importantRE = /\s*!important$/;
var setProp = function (el, name, val) {
/* istanbul ignore if */
if (cssVarRE.test(name)) {
el.style.setProperty(name, val);
} else if (importantRE.test(val)) {
el.style.setProperty(name, val.replace(importantRE, ''), 'important');
} else {
var normalizedName = normalize(name);
if (Array.isArray(val)) {
// Support values array created by autoprefixer, e.g.
// {display: ["-webkit-box", "-ms-flexbox", "flex"]}
// Set them one by one, and the browser will only set those it can recognize
for (var i = 0, len = val.length; i < len; i++) {
el.style[normalizedName] = val[i];
}
} else {
el.style[normalizedName] = val;
}
}
};
var prefixes = ['Webkit', 'Moz', 'ms'];
var testEl;
var normalize = cached(function (prop) {
testEl = testEl || document.createElement('div');
prop = camelize(prop);
if (prop !== 'filter' && (prop in testEl.style)) {
return prop
}
var upper = prop.charAt(0).toUpperCase() + prop.slice(1);
for (var i = 0; i < prefixes.length; i++) {
var prefixed = prefixes[i] + upper;
if (prefixed in testEl.style) {
return prefixed
}
}
});
function updateStyle (oldVnode, vnode) {
var data = vnode.data;
var oldData = oldVnode.data;
if (isUndef(data.staticStyle) && isUndef(data.style) &&
isUndef(oldData.staticStyle) && isUndef(oldData.style)
) {
return
}
var cur, name;
var el = vnode.elm;
var oldStaticStyle = oldData.staticStyle;
var oldStyleBinding = oldData.normalizedStyle || oldData.style || {};
// if static style exists, stylebinding already merged into it when doing normalizeStyleData
var oldStyle = oldStaticStyle || oldStyleBinding;
var style = normalizeStyleBinding(vnode.data.style) || {};
// store normalized style under a different key for next diff
// make sure to clone it if it's reactive, since the user likley wants
// to mutate it.
vnode.data.normalizedStyle = isDef(style.__ob__)
? extend({}, style)
: style;
var newStyle = getStyle(vnode, true);
for (name in oldStyle) {
if (isUndef(newStyle[name])) {
setProp(el, name, '');
}
}
for (name in newStyle) {
cur = newStyle[name];
if (cur !== oldStyle[name]) {
// ie9 setting to null has no effect, must use empty string
setProp(el, name, cur == null ? '' : cur);
}
}
}
var style = {
create: updateStyle,
update: updateStyle
};
/* */
/**
* Add class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function addClass (el, cls) {
/* istanbul ignore if */
if (!cls || !(cls = cls.trim())) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(/\s+/).forEach(function (c) { return el.classList.add(c); });
} else {
el.classList.add(cls);
}
} else {
var cur = " " + (el.getAttribute('class') || '') + " ";
if (cur.indexOf(' ' + cls + ' ') < 0) {
el.setAttribute('class', (cur + cls).trim());
}
}
}
/**
* Remove class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function removeClass (el, cls) {
/* istanbul ignore if */
if (!cls || !(cls = cls.trim())) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); });
} else {
el.classList.remove(cls);
}
} else {
var cur = " " + (el.getAttribute('class') || '') + " ";
var tar = ' ' + cls + ' ';
while (cur.indexOf(tar) >= 0) {
cur = cur.replace(tar, ' ');
}
el.setAttribute('class', cur.trim());
}
}
/* */
function resolveTransition (def$$1) {
if (!def$$1) {
return
}
/* istanbul ignore else */
if (typeof def$$1 === 'object') {
var res = {};
if (def$$1.css !== false) {
extend(res, autoCssTransition(def$$1.name || 'v'));
}
extend(res, def$$1);
return res
} else if (typeof def$$1 === 'string') {
return autoCssTransition(def$$1)
}
}
var autoCssTransition = cached(function (name) {
return {
enterClass: (name + "-enter"),
enterToClass: (name + "-enter-to"),
enterActiveClass: (name + "-enter-active"),
leaveClass: (name + "-leave"),
leaveToClass: (name + "-leave-to"),
leaveActiveClass: (name + "-leave-active")
}
});
var hasTransition = inBrowser && !isIE9;
var TRANSITION = 'transition';
var ANIMATION = 'animation';
// Transition property/event sniffing
var transitionProp = 'transition';
var transitionEndEvent = 'transitionend';
var animationProp = 'animation';
var animationEndEvent = 'animationend';
if (hasTransition) {
/* istanbul ignore if */
if (window.ontransitionend === undefined &&
window.onwebkittransitionend !== undefined
) {
transitionProp = 'WebkitTransition';
transitionEndEvent = 'webkitTransitionEnd';
}
if (window.onanimationend === undefined &&
window.onwebkitanimationend !== undefined
) {
animationProp = 'WebkitAnimation';
animationEndEvent = 'webkitAnimationEnd';
}
}
// binding to window is necessary to make hot reload work in IE in strict mode
var raf = inBrowser && window.requestAnimationFrame
? window.requestAnimationFrame.bind(window)
: setTimeout;
function nextFrame (fn) {
raf(function () {
raf(fn);
});
}
function addTransitionClass (el, cls) {
(el._transitionClasses || (el._transitionClasses = [])).push(cls);
addClass(el, cls);
}
function removeTransitionClass (el, cls) {
if (el._transitionClasses) {
remove(el._transitionClasses, cls);
}
removeClass(el, cls);
}
function whenTransitionEnds (
el,
expectedType,
cb
) {
var ref = getTransitionInfo(el, expectedType);
var type = ref.type;
var timeout = ref.timeout;
var propCount = ref.propCount;
if (!type) { return cb() }
var event = type === TRANSITION ? transitionEndEvent : animationEndEvent;
var ended = 0;
var end = function () {
el.removeEventListener(event, onEnd);
cb();
};
var onEnd = function (e) {
if (e.target === el) {
if (++ended >= propCount) {
end();
}
}
};
setTimeout(function () {
if (ended < propCount) {
end();
}
}, timeout + 1);
el.addEventListener(event, onEnd);
}
var transformRE = /\b(transform|all)(,|$)/;
function getTransitionInfo (el, expectedType) {
var styles = window.getComputedStyle(el);
var transitionDelays = styles[transitionProp + 'Delay'].split(', ');
var transitionDurations = styles[transitionProp + 'Duration'].split(', ');
var transitionTimeout = getTimeout(transitionDelays, transitionDurations);
var animationDelays = styles[animationProp + 'Delay'].split(', ');
var animationDurations = styles[animationProp + 'Duration'].split(', ');
var animationTimeout = getTimeout(animationDelays, animationDurations);
var type;
var timeout = 0;
var propCount = 0;
/* istanbul ignore if */
if (expectedType === TRANSITION) {
if (transitionTimeout > 0) {
type = TRANSITION;
timeout = transitionTimeout;
propCount = transitionDurations.length;
}
} else if (expectedType === ANIMATION) {
if (animationTimeout > 0) {
type = ANIMATION;
timeout = animationTimeout;
propCount = animationDurations.length;
}
} else {
timeout = Math.max(transitionTimeout, animationTimeout);
type = timeout > 0
? transitionTimeout > animationTimeout
? TRANSITION
: ANIMATION
: null;
propCount = type
? type === TRANSITION
? transitionDurations.length
: animationDurations.length
: 0;
}
var hasTransform =
type === TRANSITION &&
transformRE.test(styles[transitionProp + 'Property']);
return {
type: type,
timeout: timeout,
propCount: propCount,
hasTransform: hasTransform
}
}
function getTimeout (delays, durations) {
/* istanbul ignore next */
while (delays.length < durations.length) {
delays = delays.concat(delays);
}
return Math.max.apply(null, durations.map(function (d, i) {
return toMs(d) + toMs(delays[i])
}))
}
function toMs (s) {
return Number(s.slice(0, -1)) * 1000
}
/* */
function enter (vnode, toggleDisplay) {
var el = vnode.elm;
// call leave callback now
if (isDef(el._leaveCb)) {
el._leaveCb.cancelled = true;
el._leaveCb();
}
var data = resolveTransition(vnode.data.transition);
if (isUndef(data)) {
return
}
/* istanbul ignore if */
if (isDef(el._enterCb) || el.nodeType !== 1) {
return
}
var css = data.css;
var type = data.type;
var enterClass = data.enterClass;
var enterToClass = data.enterToClass;
var enterActiveClass = data.enterActiveClass;
var appearClass = data.appearClass;
var appearToClass = data.appearToClass;
var appearActiveClass = data.appearActiveClass;
var beforeEnter = data.beforeEnter;
var enter = data.enter;
var afterEnter = data.afterEnter;
var enterCancelled = data.enterCancelled;
var beforeAppear = data.beforeAppear;
var appear = data.appear;
var afterAppear = data.afterAppear;
var appearCancelled = data.appearCancelled;
var duration = data.duration;
// activeInstance will always be the <transition> component managing this
// transition. One edge case to check is when the <transition> is placed
// as the root node of a child component. In that case we need to check
// <transition>'s parent for appear check.
var context = activeInstance;
var transitionNode = activeInstance.$vnode;
while (transitionNode && transitionNode.parent) {
transitionNode = transitionNode.parent;
context = transitionNode.context;
}
var isAppear = !context._isMounted || !vnode.isRootInsert;
if (isAppear && !appear && appear !== '') {
return
}
var startClass = isAppear && appearClass
? appearClass
: enterClass;
var activeClass = isAppear && appearActiveClass
? appearActiveClass
: enterActiveClass;
var toClass = isAppear && appearToClass
? appearToClass
: enterToClass;
var beforeEnterHook = isAppear
? (beforeAppear || beforeEnter)
: beforeEnter;
var enterHook = isAppear
? (typeof appear === 'function' ? appear : enter)
: enter;
var afterEnterHook = isAppear
? (afterAppear || afterEnter)
: afterEnter;
var enterCancelledHook = isAppear
? (appearCancelled || enterCancelled)
: enterCancelled;
var explicitEnterDuration = toNumber(
isObject(duration)
? duration.enter
: duration
);
if (process.env.NODE_ENV !== 'production' && explicitEnterDuration != null) {
checkDuration(explicitEnterDuration, 'enter', vnode);
}
var expectsCSS = css !== false && !isIE9;
var userWantsControl = getHookArgumentsLength(enterHook);
var cb = el._enterCb = once(function () {
if (expectsCSS) {
removeTransitionClass(el, toClass);
removeTransitionClass(el, activeClass);
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, startClass);
}
enterCancelledHook && enterCancelledHook(el);
} else {
afterEnterHook && afterEnterHook(el);
}
el._enterCb = null;
});
if (!vnode.data.show) {
// remove pending leave element on enter by injecting an insert hook
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function () {
var parent = el.parentNode;
var pendingNode = parent && parent._pending && parent._pending[vnode.key];
if (pendingNode &&
pendingNode.tag === vnode.tag &&
pendingNode.elm._leaveCb
) {
pendingNode.elm._leaveCb();
}
enterHook && enterHook(el, cb);
});
}
// start enter transition
beforeEnterHook && beforeEnterHook(el);
if (expectsCSS) {
addTransitionClass(el, startClass);
addTransitionClass(el, activeClass);
nextFrame(function () {
addTransitionClass(el, toClass);
removeTransitionClass(el, startClass);
if (!cb.cancelled && !userWantsControl) {
if (isValidDuration(explicitEnterDuration)) {
setTimeout(cb, explicitEnterDuration);
} else {
whenTransitionEnds(el, type, cb);
}
}
});
}
if (vnode.data.show) {
toggleDisplay && toggleDisplay();
enterHook && enterHook(el, cb);
}
if (!expectsCSS && !userWantsControl) {
cb();
}
}
function leave (vnode, rm) {
var el = vnode.elm;
// call enter callback now
if (isDef(el._enterCb)) {
el._enterCb.cancelled = true;
el._enterCb();
}
var data = resolveTransition(vnode.data.transition);
if (isUndef(data)) {
return rm()
}
/* istanbul ignore if */
if (isDef(el._leaveCb) || el.nodeType !== 1) {
return
}
var css = data.css;
var type = data.type;
var leaveClass = data.leaveClass;
var leaveToClass = data.leaveToClass;
var leaveActiveClass = data.leaveActiveClass;
var beforeLeave = data.beforeLeave;
var leave = data.leave;
var afterLeave = data.afterLeave;
var leaveCancelled = data.leaveCancelled;
var delayLeave = data.delayLeave;
var duration = data.duration;
var expectsCSS = css !== false && !isIE9;
var userWantsControl = getHookArgumentsLength(leave);
var explicitLeaveDuration = toNumber(
isObject(duration)
? duration.leave
: duration
);
if (process.env.NODE_ENV !== 'production' && isDef(explicitLeaveDuration)) {
checkDuration(explicitLeaveDuration, 'leave', vnode);
}
var cb = el._leaveCb = once(function () {
if (el.parentNode && el.parentNode._pending) {
el.parentNode._pending[vnode.key] = null;
}
if (expectsCSS) {
removeTransitionClass(el, leaveToClass);
removeTransitionClass(el, leaveActiveClass);
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, leaveClass);
}
leaveCancelled && leaveCancelled(el);
} else {
rm();
afterLeave && afterLeave(el);
}
el._leaveCb = null;
});
if (delayLeave) {
delayLeave(performLeave);
} else {
performLeave();
}
function performLeave () {
// the delayed leave may have already been cancelled
if (cb.cancelled) {
return
}
// record leaving element
if (!vnode.data.show) {
(el.parentNode._pending || (el.parentNode._pending = {}))[(vnode.key)] = vnode;
}
beforeLeave && beforeLeave(el);
if (expectsCSS) {
addTransitionClass(el, leaveClass);
addTransitionClass(el, leaveActiveClass);
nextFrame(function () {
addTransitionClass(el, leaveToClass);
removeTransitionClass(el, leaveClass);
if (!cb.cancelled && !userWantsControl) {
if (isValidDuration(explicitLeaveDuration)) {
setTimeout(cb, explicitLeaveDuration);
} else {
whenTransitionEnds(el, type, cb);
}
}
});
}
leave && leave(el, cb);
if (!expectsCSS && !userWantsControl) {
cb();
}
}
}
// only used in dev mode
function checkDuration (val, name, vnode) {
if (typeof val !== 'number') {
warn(
"<transition> explicit " + name + " duration is not a valid number - " +
"got " + (JSON.stringify(val)) + ".",
vnode.context
);
} else if (isNaN(val)) {
warn(
"<transition> explicit " + name + " duration is NaN - " +
'the duration expression might be incorrect.',
vnode.context
);
}
}
function isValidDuration (val) {
return typeof val === 'number' && !isNaN(val)
}
/**
* Normalize a transition hook's argument length. The hook may be:
* - a merged hook (invoker) with the original in .fns
* - a wrapped component method (check ._length)
* - a plain function (.length)
*/
function getHookArgumentsLength (fn) {
if (isUndef(fn)) {
return false
}
var invokerFns = fn.fns;
if (isDef(invokerFns)) {
// invoker
return getHookArgumentsLength(
Array.isArray(invokerFns)
? invokerFns[0]
: invokerFns
)
} else {
return (fn._length || fn.length) > 1
}
}
function _enter (_, vnode) {
if (vnode.data.show !== true) {
enter(vnode);
}
}
var transition = inBrowser ? {
create: _enter,
activate: _enter,
remove: function remove$$1 (vnode, rm) {
/* istanbul ignore else */
if (vnode.data.show !== true) {
leave(vnode, rm);
} else {
rm();
}
}
} : {};
var platformModules = [
attrs,
klass,
events,
domProps,
style,
transition
];
/* */
// the directive module should be applied last, after all
// built-in modules have been applied.
var modules = platformModules.concat(baseModules);
var patch = createPatchFunction({ nodeOps: nodeOps, modules: modules });
/**
* Not type checking this file because flow doesn't like attaching
* properties to Elements.
*/
/* istanbul ignore if */
if (isIE9) {
// http://www.matts411.com/post/internet-explorer-9-oninput/
document.addEventListener('selectionchange', function () {
var el = document.activeElement;
if (el && el.vmodel) {
trigger(el, 'input');
}
});
}
var model$1 = {
inserted: function inserted (el, binding, vnode) {
if (vnode.tag === 'select') {
var cb = function () {
setSelected(el, binding, vnode.context);
};
cb();
/* istanbul ignore if */
if (isIE || isEdge) {
setTimeout(cb, 0);
}
} else if (vnode.tag === 'textarea' || el.type === 'text' || el.type === 'password') {
el._vModifiers = binding.modifiers;
if (!binding.modifiers.lazy) {
// Safari < 10.2 & UIWebView doesn't fire compositionend when
// switching focus before confirming composition choice
// this also fixes the issue where some browsers e.g. iOS Chrome
// fires "change" instead of "input" on autocomplete.
el.addEventListener('change', onCompositionEnd);
if (!isAndroid) {
el.addEventListener('compositionstart', onCompositionStart);
el.addEventListener('compositionend', onCompositionEnd);
}
/* istanbul ignore if */
if (isIE9) {
el.vmodel = true;
}
}
}
},
componentUpdated: function componentUpdated (el, binding, vnode) {
if (vnode.tag === 'select') {
setSelected(el, binding, vnode.context);
// in case the options rendered by v-for have changed,
// it's possible that the value is out-of-sync with the rendered options.
// detect such cases and filter out values that no longer has a matching
// option in the DOM.
var needReset = el.multiple
? binding.value.some(function (v) { return hasNoMatchingOption(v, el.options); })
: binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, el.options);
if (needReset) {
trigger(el, 'change');
}
}
}
};
function setSelected (el, binding, vm) {
var value = binding.value;
var isMultiple = el.multiple;
if (isMultiple && !Array.isArray(value)) {
process.env.NODE_ENV !== 'production' && warn(
"<select multiple v-model=\"" + (binding.expression) + "\"> " +
"expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)),
vm
);
return
}
var selected, option;
for (var i = 0, l = el.options.length; i < l; i++) {
option = el.options[i];
if (isMultiple) {
selected = looseIndexOf(value, getValue(option)) > -1;
if (option.selected !== selected) {
option.selected = selected;
}
} else {
if (looseEqual(getValue(option), value)) {
if (el.selectedIndex !== i) {
el.selectedIndex = i;
}
return
}
}
}
if (!isMultiple) {
el.selectedIndex = -1;
}
}
function hasNoMatchingOption (value, options) {
for (var i = 0, l = options.length; i < l; i++) {
if (looseEqual(getValue(options[i]), value)) {
return false
}
}
return true
}
function getValue (option) {
return '_value' in option
? option._value
: option.value
}
function onCompositionStart (e) {
e.target.composing = true;
}
function onCompositionEnd (e) {
// prevent triggering an input event for no reason
if (!e.target.composing) { return }
e.target.composing = false;
trigger(e.target, 'input');
}
function trigger (el, type) {
var e = document.createEvent('HTMLEvents');
e.initEvent(type, true, true);
el.dispatchEvent(e);
}
/* */
// recursively search for possible transition defined inside the component root
function locateNode (vnode) {
return vnode.componentInstance && (!vnode.data || !vnode.data.transition)
? locateNode(vnode.componentInstance._vnode)
: vnode
}
var show = {
bind: function bind (el, ref, vnode) {
var value = ref.value;
vnode = locateNode(vnode);
var transition = vnode.data && vnode.data.transition;
var originalDisplay = el.__vOriginalDisplay =
el.style.display === 'none' ? '' : el.style.display;
if (value && transition && !isIE9) {
vnode.data.show = true;
enter(vnode, function () {
el.style.display = originalDisplay;
});
} else {
el.style.display = value ? originalDisplay : 'none';
}
},
update: function update (el, ref, vnode) {
var value = ref.value;
var oldValue = ref.oldValue;
/* istanbul ignore if */
if (value === oldValue) { return }
vnode = locateNode(vnode);
var transition = vnode.data && vnode.data.transition;
if (transition && !isIE9) {
vnode.data.show = true;
if (value) {
enter(vnode, function () {
el.style.display = el.__vOriginalDisplay;
});
} else {
leave(vnode, function () {
el.style.display = 'none';
});
}
} else {
el.style.display = value ? el.__vOriginalDisplay : 'none';
}
},
unbind: function unbind (
el,
binding,
vnode,
oldVnode,
isDestroy
) {
if (!isDestroy) {
el.style.display = el.__vOriginalDisplay;
}
}
};
var platformDirectives = {
model: model$1,
show: show
};
/* */
// Provides transition support for a single element/component.
// supports transition mode (out-in / in-out)
var transitionProps = {
name: String,
appear: Boolean,
css: Boolean,
mode: String,
type: String,
enterClass: String,
leaveClass: String,
enterToClass: String,
leaveToClass: String,
enterActiveClass: String,
leaveActiveClass: String,
appearClass: String,
appearActiveClass: String,
appearToClass: String,
duration: [Number, String, Object]
};
// in case the child is also an abstract component, e.g. <keep-alive>
// we want to recursively retrieve the real component to be rendered
function getRealChild (vnode) {
var compOptions = vnode && vnode.componentOptions;
if (compOptions && compOptions.Ctor.options.abstract) {
return getRealChild(getFirstComponentChild(compOptions.children))
} else {
return vnode
}
}
function extractTransitionData (comp) {
var data = {};
var options = comp.$options;
// props
for (var key in options.propsData) {
data[key] = comp[key];
}
// events.
// extract listeners and pass them directly to the transition methods
var listeners = options._parentListeners;
for (var key$1 in listeners) {
data[camelize(key$1)] = listeners[key$1];
}
return data
}
function placeholder (h, rawChild) {
if (/\d-keep-alive$/.test(rawChild.tag)) {
return h('keep-alive', {
props: rawChild.componentOptions.propsData
})
}
}
function hasParentTransition (vnode) {
while ((vnode = vnode.parent)) {
if (vnode.data.transition) {
return true
}
}
}
function isSameChild (child, oldChild) {
return oldChild.key === child.key && oldChild.tag === child.tag
}
var Transition = {
name: 'transition',
props: transitionProps,
abstract: true,
render: function render (h) {
var this$1 = this;
var children = this.$slots.default;
if (!children) {
return
}
// filter out text nodes (possible whitespaces)
children = children.filter(function (c) { return c.tag; });
/* istanbul ignore if */
if (!children.length) {
return
}
// warn multiple elements
if (process.env.NODE_ENV !== 'production' && children.length > 1) {
warn(
'<transition> can only be used on a single element. Use ' +
'<transition-group> for lists.',
this.$parent
);
}
var mode = this.mode;
// warn invalid mode
if (process.env.NODE_ENV !== 'production' &&
mode && mode !== 'in-out' && mode !== 'out-in'
) {
warn(
'invalid <transition> mode: ' + mode,
this.$parent
);
}
var rawChild = children[0];
// if this is a component root node and the component's
// parent container node also has transition, skip.
if (hasParentTransition(this.$vnode)) {
return rawChild
}
// apply transition data to child
// use getRealChild() to ignore abstract components e.g. keep-alive
var child = getRealChild(rawChild);
/* istanbul ignore if */
if (!child) {
return rawChild
}
if (this._leaving) {
return placeholder(h, rawChild)
}
// ensure a key that is unique to the vnode type and to this transition
// component instance. This key will be used to remove pending leaving nodes
// during entering.
var id = "__transition-" + (this._uid) + "-";
child.key = child.key == null
? id + child.tag
: isPrimitive(child.key)
? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key)
: child.key;
var data = (child.data || (child.data = {})).transition = extractTransitionData(this);
var oldRawChild = this._vnode;
var oldChild = getRealChild(oldRawChild);
// mark v-show
// so that the transition module can hand over the control to the directive
if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) {
child.data.show = true;
}
if (oldChild && oldChild.data && !isSameChild(child, oldChild)) {
// replace old child transition data with fresh one
// important for dynamic transitions!
var oldData = oldChild && (oldChild.data.transition = extend({}, data));
// handle transition mode
if (mode === 'out-in') {
// return placeholder node and queue update when leave finishes
this._leaving = true;
mergeVNodeHook(oldData, 'afterLeave', function () {
this$1._leaving = false;
this$1.$forceUpdate();
});
return placeholder(h, rawChild)
} else if (mode === 'in-out') {
var delayedLeave;
var performLeave = function () { delayedLeave(); };
mergeVNodeHook(data, 'afterEnter', performLeave);
mergeVNodeHook(data, 'enterCancelled', performLeave);
mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; });
}
}
return rawChild
}
};
/* */
// Provides transition support for list items.
// supports move transitions using the FLIP technique.
// Because the vdom's children update algorithm is "unstable" - i.e.
// it doesn't guarantee the relative positioning of removed elements,
// we force transition-group to update its children into two passes:
// in the first pass, we remove all nodes that need to be removed,
// triggering their leaving transition; in the second pass, we insert/move
// into the final desired state. This way in the second pass removed
// nodes will remain where they should be.
var props = extend({
tag: String,
moveClass: String
}, transitionProps);
delete props.mode;
var TransitionGroup = {
props: props,
render: function render (h) {
var tag = this.tag || this.$vnode.data.tag || 'span';
var map = Object.create(null);
var prevChildren = this.prevChildren = this.children;
var rawChildren = this.$slots.default || [];
var children = this.children = [];
var transitionData = extractTransitionData(this);
for (var i = 0; i < rawChildren.length; i++) {
var c = rawChildren[i];
if (c.tag) {
if (c.key != null && String(c.key).indexOf('__vlist') !== 0) {
children.push(c);
map[c.key] = c
;(c.data || (c.data = {})).transition = transitionData;
} else if (process.env.NODE_ENV !== 'production') {
var opts = c.componentOptions;
var name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag;
warn(("<transition-group> children must be keyed: <" + name + ">"));
}
}
}
if (prevChildren) {
var kept = [];
var removed = [];
for (var i$1 = 0; i$1 < prevChildren.length; i$1++) {
var c$1 = prevChildren[i$1];
c$1.data.transition = transitionData;
c$1.data.pos = c$1.elm.getBoundingClientRect();
if (map[c$1.key]) {
kept.push(c$1);
} else {
removed.push(c$1);
}
}
this.kept = h(tag, null, kept);
this.removed = removed;
}
return h(tag, null, children)
},
beforeUpdate: function beforeUpdate () {
// force removing pass
this.__patch__(
this._vnode,
this.kept,
false, // hydrating
true // removeOnly (!important, avoids unnecessary moves)
);
this._vnode = this.kept;
},
updated: function updated () {
var children = this.prevChildren;
var moveClass = this.moveClass || ((this.name || 'v') + '-move');
if (!children.length || !this.hasMove(children[0].elm, moveClass)) {
return
}
// we divide the work into three loops to avoid mixing DOM reads and writes
// in each iteration - which helps prevent layout thrashing.
children.forEach(callPendingCbs);
children.forEach(recordPosition);
children.forEach(applyTranslation);
// force reflow to put everything in position
var body = document.body;
var f = body.offsetHeight; // eslint-disable-line
children.forEach(function (c) {
if (c.data.moved) {
var el = c.elm;
var s = el.style;
addTransitionClass(el, moveClass);
s.transform = s.WebkitTransform = s.transitionDuration = '';
el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) {
if (!e || /transform$/.test(e.propertyName)) {
el.removeEventListener(transitionEndEvent, cb);
el._moveCb = null;
removeTransitionClass(el, moveClass);
}
});
}
});
},
methods: {
hasMove: function hasMove (el, moveClass) {
/* istanbul ignore if */
if (!hasTransition) {
return false
}
if (this._hasMove != null) {
return this._hasMove
}
// Detect whether an element with the move class applied has
// CSS transitions. Since the element may be inside an entering
// transition at this very moment, we make a clone of it and remove
// all other transition classes applied to ensure only the move class
// is applied.
var clone = el.cloneNode();
if (el._transitionClasses) {
el._transitionClasses.forEach(function (cls) { removeClass(clone, cls); });
}
addClass(clone, moveClass);
clone.style.display = 'none';
this.$el.appendChild(clone);
var info = getTransitionInfo(clone);
this.$el.removeChild(clone);
return (this._hasMove = info.hasTransform)
}
}
};
function callPendingCbs (c) {
/* istanbul ignore if */
if (c.elm._moveCb) {
c.elm._moveCb();
}
/* istanbul ignore if */
if (c.elm._enterCb) {
c.elm._enterCb();
}
}
function recordPosition (c) {
c.data.newPos = c.elm.getBoundingClientRect();
}
function applyTranslation (c) {
var oldPos = c.data.pos;
var newPos = c.data.newPos;
var dx = oldPos.left - newPos.left;
var dy = oldPos.top - newPos.top;
if (dx || dy) {
c.data.moved = true;
var s = c.elm.style;
s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)";
s.transitionDuration = '0s';
}
}
var platformComponents = {
Transition: Transition,
TransitionGroup: TransitionGroup
};
/* */
// install platform specific utils
Vue$3.config.mustUseProp = mustUseProp;
Vue$3.config.isReservedTag = isReservedTag;
Vue$3.config.isReservedAttr = isReservedAttr;
Vue$3.config.getTagNamespace = getTagNamespace;
Vue$3.config.isUnknownElement = isUnknownElement;
// install platform runtime directives & components
extend(Vue$3.options.directives, platformDirectives);
extend(Vue$3.options.components, platformComponents);
// install platform patch function
Vue$3.prototype.__patch__ = inBrowser ? patch : noop;
// public mount method
Vue$3.prototype.$mount = function (
el,
hydrating
) {
el = el && inBrowser ? query(el) : undefined;
return mountComponent(this, el, hydrating)
};
// devtools global hook
/* istanbul ignore next */
setTimeout(function () {
if (config.devtools) {
if (devtools) {
devtools.emit('init', Vue$3);
} else if (process.env.NODE_ENV !== 'production' && isChrome) {
console[console.info ? 'info' : 'log'](
'Download the Vue Devtools extension for a better development experience:\n' +
'https://github.com/vuejs/vue-devtools'
);
}
}
if (process.env.NODE_ENV !== 'production' &&
config.productionTip !== false &&
inBrowser && typeof console !== 'undefined'
) {
console[console.info ? 'info' : 'log'](
"You are running Vue in development mode.\n" +
"Make sure to turn on production mode when deploying for production.\n" +
"See more tips at https://vuejs.org/guide/deployment.html"
);
}
}, 0);
/* */
// check whether current browser encodes a char inside attribute values
function shouldDecode (content, encoded) {
var div = document.createElement('div');
div.innerHTML = "<div a=\"" + content + "\">";
return div.innerHTML.indexOf(encoded) > 0
}
// #3663
// IE encodes newlines inside attribute values while other browsers don't
var shouldDecodeNewlines = inBrowser ? shouldDecode('\n', ' ') : false;
/* */
var isUnaryTag = makeMap(
'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' +
'link,meta,param,source,track,wbr'
);
// Elements that you can, intentionally, leave open
// (and which close themselves)
var canBeLeftOpenTag = makeMap(
'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source'
);
// HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3
// Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content
var isNonPhrasingTag = makeMap(
'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' +
'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' +
'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' +
'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' +
'title,tr,track'
);
/* */
var decoder;
function decode (html) {
decoder = decoder || document.createElement('div');
decoder.innerHTML = html;
return decoder.textContent
}
/**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
// Regular Expressions for parsing tags and attributes
var singleAttrIdentifier = /([^\s"'<>/=]+)/;
var singleAttrAssign = /(?:=)/;
var singleAttrValues = [
// attr value double quotes
/"([^"]*)"+/.source,
// attr value, single quotes
/'([^']*)'+/.source,
// attr value, no quotes
/([^\s"'=<>`]+)/.source
];
var attribute = new RegExp(
'^\\s*' + singleAttrIdentifier.source +
'(?:\\s*(' + singleAttrAssign.source + ')' +
'\\s*(?:' + singleAttrValues.join('|') + '))?'
);
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
var ncname = '[a-zA-Z_][\\w\\-\\.]*';
var qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')';
var startTagOpen = new RegExp('^<' + qnameCapture);
var startTagClose = /^\s*(\/?)>/;
var endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>');
var doctype = /^<!DOCTYPE [^>]+>/i;
var comment = /^<!--/;
var conditionalComment = /^<!\[/;
var IS_REGEX_CAPTURING_BROKEN = false;
'x'.replace(/x(.)?/g, function (m, g) {
IS_REGEX_CAPTURING_BROKEN = g === '';
});
// Special Elements (can contain anything)
var isPlainTextElement = makeMap('script,style,textarea', true);
var reCache = {};
var decodingMap = {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
' ': '\n'
};
var encodedAttr = /&(?:lt|gt|quot|amp);/g;
var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g;
function decodeAttr (value, shouldDecodeNewlines) {
var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr;
return value.replace(re, function (match) { return decodingMap[match]; })
}
function parseHTML (html, options) {
var stack = [];
var expectHTML = options.expectHTML;
var isUnaryTag$$1 = options.isUnaryTag || no;
var canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no;
var index = 0;
var last, lastTag;
while (html) {
last = html;
// Make sure we're not in a plaintext content element like script/style
if (!lastTag || !isPlainTextElement(lastTag)) {
var textEnd = html.indexOf('<');
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
var commentEnd = html.indexOf('-->');
if (commentEnd >= 0) {
advance(commentEnd + 3);
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
var conditionalEnd = html.indexOf(']>');
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2);
continue
}
}
// Doctype:
var doctypeMatch = html.match(doctype);
if (doctypeMatch) {
advance(doctypeMatch[0].length);
continue
}
// End tag:
var endTagMatch = html.match(endTag);
if (endTagMatch) {
var curIndex = index;
advance(endTagMatch[0].length);
parseEndTag(endTagMatch[1], curIndex, index);
continue
}
// Start tag:
var startTagMatch = parseStartTag();
if (startTagMatch) {
handleStartTag(startTagMatch);
continue
}
}
var text = (void 0), rest$1 = (void 0), next = (void 0);
if (textEnd >= 0) {
rest$1 = html.slice(textEnd);
while (
!endTag.test(rest$1) &&
!startTagOpen.test(rest$1) &&
!comment.test(rest$1) &&
!conditionalComment.test(rest$1)
) {
// < in plain text, be forgiving and treat it as text
next = rest$1.indexOf('<', 1);
if (next < 0) { break }
textEnd += next;
rest$1 = html.slice(textEnd);
}
text = html.substring(0, textEnd);
advance(textEnd);
}
if (textEnd < 0) {
text = html;
html = '';
}
if (options.chars && text) {
options.chars(text);
}
} else {
var stackedTag = lastTag.toLowerCase();
var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'));
var endTagLength = 0;
var rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length;
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(/<!--([\s\S]*?)-->/g, '$1')
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1');
}
if (options.chars) {
options.chars(text);
}
return ''
});
index += html.length - rest.length;
html = rest;
parseEndTag(stackedTag, index - endTagLength, index);
}
if (html === last) {
options.chars && options.chars(html);
if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) {
options.warn(("Mal-formatted tag at end of template: \"" + html + "\""));
}
break
}
}
// Clean up any remaining tags
parseEndTag();
function advance (n) {
index += n;
html = html.substring(n);
}
function parseStartTag () {
var start = html.match(startTagOpen);
if (start) {
var match = {
tagName: start[1],
attrs: [],
start: index
};
advance(start[0].length);
var end, attr;
while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
advance(attr[0].length);
match.attrs.push(attr);
}
if (end) {
match.unarySlash = end[1];
advance(end[0].length);
match.end = index;
return match
}
}
}
function handleStartTag (match) {
var tagName = match.tagName;
var unarySlash = match.unarySlash;
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag);
}
if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) {
parseEndTag(tagName);
}
}
var unary = isUnaryTag$$1(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash;
var l = match.attrs.length;
var attrs = new Array(l);
for (var i = 0; i < l; i++) {
var args = match.attrs[i];
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3]; }
if (args[4] === '') { delete args[4]; }
if (args[5] === '') { delete args[5]; }
}
var value = args[3] || args[4] || args[5] || '';
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
};
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs });
lastTag = tagName;
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end);
}
}
function parseEndTag (tagName, start, end) {
var pos, lowerCasedTagName;
if (start == null) { start = index; }
if (end == null) { end = index; }
if (tagName) {
lowerCasedTagName = tagName.toLowerCase();
}
// Find the closest opened tag of the same type
if (tagName) {
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0;
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (var i = stack.length - 1; i >= pos; i--) {
if (process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn
) {
options.warn(
("tag <" + (stack[i].tag) + "> has no matching end tag.")
);
}
if (options.end) {
options.end(stack[i].tag, start, end);
}
}
// Remove the open elements from the stack
stack.length = pos;
lastTag = pos && stack[pos - 1].tag;
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end);
}
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end);
}
if (options.end) {
options.end(tagName, start, end);
}
}
}
}
/* */
var defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g;
var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g;
var buildRegex = cached(function (delimiters) {
var open = delimiters[0].replace(regexEscapeRE, '\\$&');
var close = delimiters[1].replace(regexEscapeRE, '\\$&');
return new RegExp(open + '((?:.|\\n)+?)' + close, 'g')
});
function parseText (
text,
delimiters
) {
var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE;
if (!tagRE.test(text)) {
return
}
var tokens = [];
var lastIndex = tagRE.lastIndex = 0;
var match, index;
while ((match = tagRE.exec(text))) {
index = match.index;
// push text token
if (index > lastIndex) {
tokens.push(JSON.stringify(text.slice(lastIndex, index)));
}
// tag token
var exp = parseFilters(match[1].trim());
tokens.push(("_s(" + exp + ")"));
lastIndex = index + match[0].length;
}
if (lastIndex < text.length) {
tokens.push(JSON.stringify(text.slice(lastIndex)));
}
return tokens.join('+')
}
/* */
var onRE = /^@|^v-on:/;
var dirRE = /^v-|^@|^:/;
var forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/;
var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/;
var argRE = /:(.*)$/;
var bindRE = /^:|^v-bind:/;
var modifierRE = /\.[^.]+/g;
var decodeHTMLCached = cached(decode);
// configurable state
var warn$2;
var delimiters;
var transforms;
var preTransforms;
var postTransforms;
var platformIsPreTag;
var platformMustUseProp;
var platformGetTagNamespace;
/**
* Convert HTML string to AST.
*/
function parse (
template,
options
) {
warn$2 = options.warn || baseWarn;
platformGetTagNamespace = options.getTagNamespace || no;
platformMustUseProp = options.mustUseProp || no;
platformIsPreTag = options.isPreTag || no;
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode');
transforms = pluckModuleFunction(options.modules, 'transformNode');
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode');
delimiters = options.delimiters;
var stack = [];
var preserveWhitespace = options.preserveWhitespace !== false;
var root;
var currentParent;
var inVPre = false;
var inPre = false;
var warned = false;
function warnOnce (msg) {
if (!warned) {
warned = true;
warn$2(msg);
}
}
function endPre (element) {
// check pre state
if (element.pre) {
inVPre = false;
}
if (platformIsPreTag(element.tag)) {
inPre = false;
}
}
parseHTML(template, {
warn: warn$2,
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
canBeLeftOpenTag: options.canBeLeftOpenTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
start: function start (tag, attrs, unary) {
// check namespace.
// inherit parent ns if there is one
var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag);
// handle IE svg bug
/* istanbul ignore if */
if (isIE && ns === 'svg') {
attrs = guardIESVGBug(attrs);
}
var element = {
type: 1,
tag: tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
parent: currentParent,
children: []
};
if (ns) {
element.ns = ns;
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true;
process.env.NODE_ENV !== 'production' && warn$2(
'Templates should only be responsible for mapping the state to the ' +
'UI. Avoid placing tags with side-effects in your templates, such as ' +
"<" + tag + ">" + ', as they will not be parsed.'
);
}
// apply pre-transforms
for (var i = 0; i < preTransforms.length; i++) {
preTransforms[i](element, options);
}
if (!inVPre) {
processPre(element);
if (element.pre) {
inVPre = true;
}
}
if (platformIsPreTag(element.tag)) {
inPre = true;
}
if (inVPre) {
processRawAttrs(element);
} else {
processFor(element);
processIf(element);
processOnce(element);
processKey(element);
// determine whether this is a plain element after
// removing structural attributes
element.plain = !element.key && !attrs.length;
processRef(element);
processSlot(element);
processComponent(element);
for (var i$1 = 0; i$1 < transforms.length; i$1++) {
transforms[i$1](element, options);
}
processAttrs(element);
}
function checkRootConstraints (el) {
if (process.env.NODE_ENV !== 'production') {
if (el.tag === 'slot' || el.tag === 'template') {
warnOnce(
"Cannot use <" + (el.tag) + "> as component root element because it may " +
'contain multiple nodes.'
);
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warnOnce(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements.'
);
}
}
}
// tree management
if (!root) {
root = element;
checkRootConstraints(root);
} else if (!stack.length) {
// allow root elements with v-if, v-else-if and v-else
if (root.if && (element.elseif || element.else)) {
checkRootConstraints(element);
addIfCondition(root, {
exp: element.elseif,
block: element
});
} else if (process.env.NODE_ENV !== 'production') {
warnOnce(
"Component template should contain exactly one root element. " +
"If you are using v-if on multiple elements, " +
"use v-else-if to chain them instead."
);
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent);
} else if (element.slotScope) { // scoped slot
currentParent.plain = false;
var name = element.slotTarget || '"default"';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element;
} else {
currentParent.children.push(element);
element.parent = currentParent;
}
}
if (!unary) {
currentParent = element;
stack.push(element);
} else {
endPre(element);
}
// apply post-transforms
for (var i$2 = 0; i$2 < postTransforms.length; i$2++) {
postTransforms[i$2](element, options);
}
},
end: function end () {
// remove trailing whitespace
var element = stack[stack.length - 1];
var lastNode = element.children[element.children.length - 1];
if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) {
element.children.pop();
}
// pop stack
stack.length -= 1;
currentParent = stack[stack.length - 1];
endPre(element);
},
chars: function chars (text) {
if (!currentParent) {
if (process.env.NODE_ENV !== 'production') {
if (text === template) {
warnOnce(
'Component template requires a root element, rather than just text.'
);
} else if ((text = text.trim())) {
warnOnce(
("text \"" + text + "\" outside root element will be ignored.")
);
}
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text
) {
return
}
var children = currentParent.children;
text = inPre || text.trim()
? isTextTag(currentParent) ? text : decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && children.length ? ' ' : '';
if (text) {
var expression;
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
children.push({
type: 2,
expression: expression,
text: text
});
} else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {
children.push({
type: 3,
text: text
});
}
}
}
});
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true;
}
}
function processRawAttrs (el) {
var l = el.attrsList.length;
if (l) {
var attrs = el.attrs = new Array(l);
for (var i = 0; i < l; i++) {
attrs[i] = {
name: el.attrsList[i].name,
value: JSON.stringify(el.attrsList[i].value)
};
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true;
}
}
function processKey (el) {
var exp = getBindingAttr(el, 'key');
if (exp) {
if (process.env.NODE_ENV !== 'production' && el.tag === 'template') {
warn$2("<template> cannot be keyed. Place the key on real elements instead.");
}
el.key = exp;
}
}
function processRef (el) {
var ref = getBindingAttr(el, 'ref');
if (ref) {
el.ref = ref;
el.refInFor = checkInFor(el);
}
}
function processFor (el) {
var exp;
if ((exp = getAndRemoveAttr(el, 'v-for'))) {
var inMatch = exp.match(forAliasRE);
if (!inMatch) {
process.env.NODE_ENV !== 'production' && warn$2(
("Invalid v-for expression: " + exp)
);
return
}
el.for = inMatch[2].trim();
var alias = inMatch[1].trim();
var iteratorMatch = alias.match(forIteratorRE);
if (iteratorMatch) {
el.alias = iteratorMatch[1].trim();
el.iterator1 = iteratorMatch[2].trim();
if (iteratorMatch[3]) {
el.iterator2 = iteratorMatch[3].trim();
}
} else {
el.alias = alias;
}
}
}
function processIf (el) {
var exp = getAndRemoveAttr(el, 'v-if');
if (exp) {
el.if = exp;
addIfCondition(el, {
exp: exp,
block: el
});
} else {
if (getAndRemoveAttr(el, 'v-else') != null) {
el.else = true;
}
var elseif = getAndRemoveAttr(el, 'v-else-if');
if (elseif) {
el.elseif = elseif;
}
}
}
function processIfConditions (el, parent) {
var prev = findPrevElement(parent.children);
if (prev && prev.if) {
addIfCondition(prev, {
exp: el.elseif,
block: el
});
} else if (process.env.NODE_ENV !== 'production') {
warn$2(
"v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " +
"used on element <" + (el.tag) + "> without corresponding v-if."
);
}
}
function findPrevElement (children) {
var i = children.length;
while (i--) {
if (children[i].type === 1) {
return children[i]
} else {
if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') {
warn$2(
"text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " +
"will be ignored."
);
}
children.pop();
}
}
}
function addIfCondition (el, condition) {
if (!el.ifConditions) {
el.ifConditions = [];
}
el.ifConditions.push(condition);
}
function processOnce (el) {
var once$$1 = getAndRemoveAttr(el, 'v-once');
if (once$$1 != null) {
el.once = true;
}
}
function processSlot (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name');
if (process.env.NODE_ENV !== 'production' && el.key) {
warn$2(
"`key` does not work on <slot> because slots are abstract outlets " +
"and can possibly expand into multiple elements. " +
"Use the key on a wrapping element instead."
);
}
} else {
var slotTarget = getBindingAttr(el, 'slot');
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget;
}
if (el.tag === 'template') {
el.slotScope = getAndRemoveAttr(el, 'scope');
}
}
}
function processComponent (el) {
var binding;
if ((binding = getBindingAttr(el, 'is'))) {
el.component = binding;
}
if (getAndRemoveAttr(el, 'inline-template') != null) {
el.inlineTemplate = true;
}
}
function processAttrs (el) {
var list = el.attrsList;
var i, l, name, rawName, value, modifiers, isProp;
for (i = 0, l = list.length; i < l; i++) {
name = rawName = list[i].name;
value = list[i].value;
if (dirRE.test(name)) {
// mark element as dynamic
el.hasBindings = true;
// modifiers
modifiers = parseModifiers(name);
if (modifiers) {
name = name.replace(modifierRE, '');
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '');
value = parseFilters(value);
isProp = false;
if (modifiers) {
if (modifiers.prop) {
isProp = true;
name = camelize(name);
if (name === 'innerHtml') { name = 'innerHTML'; }
}
if (modifiers.camel) {
name = camelize(name);
}
if (modifiers.sync) {
addHandler(
el,
("update:" + (camelize(name))),
genAssignmentCode(value, "$event")
);
}
}
if (isProp || platformMustUseProp(el.tag, el.attrsMap.type, name)) {
addProp(el, name, value);
} else {
addAttr(el, name, value);
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '');
addHandler(el, name, value, modifiers, false, warn$2);
} else { // normal directives
name = name.replace(dirRE, '');
// parse arg
var argMatch = name.match(argRE);
var arg = argMatch && argMatch[1];
if (arg) {
name = name.slice(0, -(arg.length + 1));
}
addDirective(el, name, rawName, value, arg, modifiers);
if (process.env.NODE_ENV !== 'production' && name === 'model') {
checkForAliasModel(el, value);
}
}
} else {
// literal attribute
if (process.env.NODE_ENV !== 'production') {
var expression = parseText(value, delimiters);
if (expression) {
warn$2(
name + "=\"" + value + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div id="{{ val }}">, use <div :id="val">.'
);
}
}
addAttr(el, name, JSON.stringify(value));
}
}
}
function checkInFor (el) {
var parent = el;
while (parent) {
if (parent.for !== undefined) {
return true
}
parent = parent.parent;
}
return false
}
function parseModifiers (name) {
var match = name.match(modifierRE);
if (match) {
var ret = {};
match.forEach(function (m) { ret[m.slice(1)] = true; });
return ret
}
}
function makeAttrsMap (attrs) {
var map = {};
for (var i = 0, l = attrs.length; i < l; i++) {
if (
process.env.NODE_ENV !== 'production' &&
map[attrs[i].name] && !isIE && !isEdge
) {
warn$2('duplicate attribute: ' + attrs[i].name);
}
map[attrs[i].name] = attrs[i].value;
}
return map
}
// for script (e.g. type="x/template") or style, do not decode content
function isTextTag (el) {
return el.tag === 'script' || el.tag === 'style'
}
function isForbiddenTag (el) {
return (
el.tag === 'style' ||
(el.tag === 'script' && (
!el.attrsMap.type ||
el.attrsMap.type === 'text/javascript'
))
)
}
var ieNSBug = /^xmlns:NS\d+/;
var ieNSPrefix = /^NS\d+:/;
/* istanbul ignore next */
function guardIESVGBug (attrs) {
var res = [];
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
if (!ieNSBug.test(attr.name)) {
attr.name = attr.name.replace(ieNSPrefix, '');
res.push(attr);
}
}
return res
}
function checkForAliasModel (el, value) {
var _el = el;
while (_el) {
if (_el.for && _el.alias === value) {
warn$2(
"<" + (el.tag) + " v-model=\"" + value + "\">: " +
"You are binding v-model directly to a v-for iteration alias. " +
"This will not be able to modify the v-for source array because " +
"writing to the alias is like modifying a function local variable. " +
"Consider using an array of objects and use v-model on an object property instead."
);
}
_el = _el.parent;
}
}
/* */
var isStaticKey;
var isPlatformReservedTag;
var genStaticKeysCached = cached(genStaticKeys$1);
/**
* Goal of the optimizer: walk the generated template AST tree
* and detect sub-trees that are purely static, i.e. parts of
* the DOM that never needs to change.
*
* Once we detect these sub-trees, we can:
*
* 1. Hoist them into constants, so that we no longer need to
* create fresh nodes for them on each re-render;
* 2. Completely skip them in the patching process.
*/
function optimize (root, options) {
if (!root) { return }
isStaticKey = genStaticKeysCached(options.staticKeys || '');
isPlatformReservedTag = options.isReservedTag || no;
// first pass: mark all non-static nodes.
markStatic$1(root);
// second pass: mark static roots.
markStaticRoots(root, false);
}
function genStaticKeys$1 (keys) {
return makeMap(
'type,tag,attrsList,attrsMap,plain,parent,children,attrs' +
(keys ? ',' + keys : '')
)
}
function markStatic$1 (node) {
node.static = isStatic(node);
if (node.type === 1) {
// do not make component slot content static. this avoids
// 1. components not able to mutate slot nodes
// 2. static slot content fails for hot-reloading
if (
!isPlatformReservedTag(node.tag) &&
node.tag !== 'slot' &&
node.attrsMap['inline-template'] == null
) {
return
}
for (var i = 0, l = node.children.length; i < l; i++) {
var child = node.children[i];
markStatic$1(child);
if (!child.static) {
node.static = false;
}
}
}
}
function markStaticRoots (node, isInFor) {
if (node.type === 1) {
if (node.static || node.once) {
node.staticInFor = isInFor;
}
// For a node to qualify as a static root, it should have children that
// are not just static text. Otherwise the cost of hoisting out will
// outweigh the benefits and it's better off to just always render it fresh.
if (node.static && node.children.length && !(
node.children.length === 1 &&
node.children[0].type === 3
)) {
node.staticRoot = true;
return
} else {
node.staticRoot = false;
}
if (node.children) {
for (var i = 0, l = node.children.length; i < l; i++) {
markStaticRoots(node.children[i], isInFor || !!node.for);
}
}
if (node.ifConditions) {
walkThroughConditionsBlocks(node.ifConditions, isInFor);
}
}
}
function walkThroughConditionsBlocks (conditionBlocks, isInFor) {
for (var i = 1, len = conditionBlocks.length; i < len; i++) {
markStaticRoots(conditionBlocks[i].block, isInFor);
}
}
function isStatic (node) {
if (node.type === 2) { // expression
return false
}
if (node.type === 3) { // text
return true
}
return !!(node.pre || (
!node.hasBindings && // no dynamic bindings
!node.if && !node.for && // not v-if or v-for or v-else
!isBuiltInTag(node.tag) && // not a built-in
isPlatformReservedTag(node.tag) && // not a component
!isDirectChildOfTemplateFor(node) &&
Object.keys(node).every(isStaticKey)
))
}
function isDirectChildOfTemplateFor (node) {
while (node.parent) {
node = node.parent;
if (node.tag !== 'template') {
return false
}
if (node.for) {
return true
}
}
return false
}
/* */
var fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/;
var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/;
// keyCode aliases
var keyCodes = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
up: 38,
left: 37,
right: 39,
down: 40,
'delete': [8, 46]
};
// #4868: modifiers that prevent the execution of the listener
// need to explicitly return null so that we can determine whether to remove
// the listener for .once
var genGuard = function (condition) { return ("if(" + condition + ")return null;"); };
var modifierCode = {
stop: '$event.stopPropagation();',
prevent: '$event.preventDefault();',
self: genGuard("$event.target !== $event.currentTarget"),
ctrl: genGuard("!$event.ctrlKey"),
shift: genGuard("!$event.shiftKey"),
alt: genGuard("!$event.altKey"),
meta: genGuard("!$event.metaKey"),
left: genGuard("'button' in $event && $event.button !== 0"),
middle: genGuard("'button' in $event && $event.button !== 1"),
right: genGuard("'button' in $event && $event.button !== 2")
};
function genHandlers (
events,
isNative,
warn
) {
var res = isNative ? 'nativeOn:{' : 'on:{';
for (var name in events) {
var handler = events[name];
// #5330: warn click.right, since right clicks do not actually fire click events.
if (process.env.NODE_ENV !== 'production' &&
name === 'click' &&
handler && handler.modifiers && handler.modifiers.right
) {
warn(
"Use \"contextmenu\" instead of \"click.right\" since right clicks " +
"do not actually fire \"click\" events."
);
}
res += "\"" + name + "\":" + (genHandler(name, handler)) + ",";
}
return res.slice(0, -1) + '}'
}
function genHandler (
name,
handler
) {
if (!handler) {
return 'function(){}'
}
if (Array.isArray(handler)) {
return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]")
}
var isMethodPath = simplePathRE.test(handler.value);
var isFunctionExpression = fnExpRE.test(handler.value);
if (!handler.modifiers) {
return isMethodPath || isFunctionExpression
? handler.value
: ("function($event){" + (handler.value) + "}") // inline statement
} else {
var code = '';
var genModifierCode = '';
var keys = [];
for (var key in handler.modifiers) {
if (modifierCode[key]) {
genModifierCode += modifierCode[key];
// left/right
if (keyCodes[key]) {
keys.push(key);
}
} else {
keys.push(key);
}
}
if (keys.length) {
code += genKeyFilter(keys);
}
// Make sure modifiers like prevent and stop get executed after key filtering
if (genModifierCode) {
code += genModifierCode;
}
var handlerCode = isMethodPath
? handler.value + '($event)'
: isFunctionExpression
? ("(" + (handler.value) + ")($event)")
: handler.value;
return ("function($event){" + code + handlerCode + "}")
}
}
function genKeyFilter (keys) {
return ("if(!('button' in $event)&&" + (keys.map(genFilterCode).join('&&')) + ")return null;")
}
function genFilterCode (key) {
var keyVal = parseInt(key, 10);
if (keyVal) {
return ("$event.keyCode!==" + keyVal)
}
var alias = keyCodes[key];
return ("_k($event.keyCode," + (JSON.stringify(key)) + (alias ? ',' + JSON.stringify(alias) : '') + ")")
}
/* */
function bind$1 (el, dir) {
el.wrapData = function (code) {
return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + (dir.modifiers && dir.modifiers.prop ? ',true' : '') + ")")
};
}
/* */
var baseDirectives = {
bind: bind$1,
cloak: noop
};
/* */
// configurable state
var warn$3;
var transforms$1;
var dataGenFns;
var platformDirectives$1;
var isPlatformReservedTag$1;
var staticRenderFns;
var onceCount;
var currentOptions;
function generate (
ast,
options
) {
// save previous staticRenderFns so generate calls can be nested
var prevStaticRenderFns = staticRenderFns;
var currentStaticRenderFns = staticRenderFns = [];
var prevOnceCount = onceCount;
onceCount = 0;
currentOptions = options;
warn$3 = options.warn || baseWarn;
transforms$1 = pluckModuleFunction(options.modules, 'transformCode');
dataGenFns = pluckModuleFunction(options.modules, 'genData');
platformDirectives$1 = options.directives || {};
isPlatformReservedTag$1 = options.isReservedTag || no;
var code = ast ? genElement(ast) : '_c("div")';
staticRenderFns = prevStaticRenderFns;
onceCount = prevOnceCount;
return {
render: ("with(this){return " + code + "}"),
staticRenderFns: currentStaticRenderFns
}
}
function genElement (el) {
if (el.staticRoot && !el.staticProcessed) {
return genStatic(el)
} else if (el.once && !el.onceProcessed) {
return genOnce(el)
} else if (el.for && !el.forProcessed) {
return genFor(el)
} else if (el.if && !el.ifProcessed) {
return genIf(el)
} else if (el.tag === 'template' && !el.slotTarget) {
return genChildren(el) || 'void 0'
} else if (el.tag === 'slot') {
return genSlot(el)
} else {
// component or element
var code;
if (el.component) {
code = genComponent(el.component, el);
} else {
var data = el.plain ? undefined : genData(el);
var children = el.inlineTemplate ? null : genChildren(el, true);
code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")";
}
// module transforms
for (var i = 0; i < transforms$1.length; i++) {
code = transforms$1[i](el, code);
}
return code
}
}
// hoist static sub-trees out
function genStatic (el) {
el.staticProcessed = true;
staticRenderFns.push(("with(this){return " + (genElement(el)) + "}"));
return ("_m(" + (staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")")
}
// v-once
function genOnce (el) {
el.onceProcessed = true;
if (el.if && !el.ifProcessed) {
return genIf(el)
} else if (el.staticInFor) {
var key = '';
var parent = el.parent;
while (parent) {
if (parent.for) {
key = parent.key;
break
}
parent = parent.parent;
}
if (!key) {
process.env.NODE_ENV !== 'production' && warn$3(
"v-once can only be used inside v-for that is keyed. "
);
return genElement(el)
}
return ("_o(" + (genElement(el)) + "," + (onceCount++) + (key ? ("," + key) : "") + ")")
} else {
return genStatic(el)
}
}
function genIf (el) {
el.ifProcessed = true; // avoid recursion
return genIfConditions(el.ifConditions.slice())
}
function genIfConditions (conditions) {
if (!conditions.length) {
return '_e()'
}
var condition = conditions.shift();
if (condition.exp) {
return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions)))
} else {
return ("" + (genTernaryExp(condition.block)))
}
// v-if with v-once should generate code like (a)?_m(0):_m(1)
function genTernaryExp (el) {
return el.once ? genOnce(el) : genElement(el)
}
}
function genFor (el) {
var exp = el.for;
var alias = el.alias;
var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : '';
var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : '';
if (
process.env.NODE_ENV !== 'production' &&
maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key
) {
warn$3(
"<" + (el.tag) + " v-for=\"" + alias + " in " + exp + "\">: component lists rendered with " +
"v-for should have explicit keys. " +
"See https://vuejs.org/guide/list.html#key for more info.",
true /* tip */
);
}
el.forProcessed = true; // avoid recursion
return "_l((" + exp + ")," +
"function(" + alias + iterator1 + iterator2 + "){" +
"return " + (genElement(el)) +
'})'
}
function genData (el) {
var data = '{';
// directives first.
// directives may mutate the el's other properties before they are generated.
var dirs = genDirectives(el);
if (dirs) { data += dirs + ','; }
// key
if (el.key) {
data += "key:" + (el.key) + ",";
}
// ref
if (el.ref) {
data += "ref:" + (el.ref) + ",";
}
if (el.refInFor) {
data += "refInFor:true,";
}
// pre
if (el.pre) {
data += "pre:true,";
}
// record original tag name for components using "is" attribute
if (el.component) {
data += "tag:\"" + (el.tag) + "\",";
}
// module data generation functions
for (var i = 0; i < dataGenFns.length; i++) {
data += dataGenFns[i](el);
}
// attributes
if (el.attrs) {
data += "attrs:{" + (genProps(el.attrs)) + "},";
}
// DOM props
if (el.props) {
data += "domProps:{" + (genProps(el.props)) + "},";
}
// event handlers
if (el.events) {
data += (genHandlers(el.events, false, warn$3)) + ",";
}
if (el.nativeEvents) {
data += (genHandlers(el.nativeEvents, true, warn$3)) + ",";
}
// slot target
if (el.slotTarget) {
data += "slot:" + (el.slotTarget) + ",";
}
// scoped slots
if (el.scopedSlots) {
data += (genScopedSlots(el.scopedSlots)) + ",";
}
// component v-model
if (el.model) {
data += "model:{value:" + (el.model.value) + ",callback:" + (el.model.callback) + ",expression:" + (el.model.expression) + "},";
}
// inline-template
if (el.inlineTemplate) {
var inlineTemplate = genInlineTemplate(el);
if (inlineTemplate) {
data += inlineTemplate + ",";
}
}
data = data.replace(/,$/, '') + '}';
// v-bind data wrap
if (el.wrapData) {
data = el.wrapData(data);
}
return data
}
function genDirectives (el) {
var dirs = el.directives;
if (!dirs) { return }
var res = 'directives:[';
var hasRuntime = false;
var i, l, dir, needRuntime;
for (i = 0, l = dirs.length; i < l; i++) {
dir = dirs[i];
needRuntime = true;
var gen = platformDirectives$1[dir.name] || baseDirectives[dir.name];
if (gen) {
// compile-time directive that manipulates AST.
// returns true if it also needs a runtime counterpart.
needRuntime = !!gen(el, dir, warn$3);
}
if (needRuntime) {
hasRuntime = true;
res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:\"" + (dir.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},";
}
}
if (hasRuntime) {
return res.slice(0, -1) + ']'
}
}
function genInlineTemplate (el) {
var ast = el.children[0];
if (process.env.NODE_ENV !== 'production' && (
el.children.length > 1 || ast.type !== 1
)) {
warn$3('Inline-template components must have exactly one child element.');
}
if (ast.type === 1) {
var inlineRenderFns = generate(ast, currentOptions);
return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}")
}
}
function genScopedSlots (slots) {
return ("scopedSlots:_u([" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key]); }).join(',')) + "])")
}
function genScopedSlot (key, el) {
if (el.for && !el.forProcessed) {
return genForScopedSlot(key, el)
}
return "{key:" + key + ",fn:function(" + (String(el.attrsMap.scope)) + "){" +
"return " + (el.tag === 'template'
? genChildren(el) || 'void 0'
: genElement(el)) + "}}"
}
function genForScopedSlot (key, el) {
var exp = el.for;
var alias = el.alias;
var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : '';
var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : '';
el.forProcessed = true; // avoid recursion
return "_l((" + exp + ")," +
"function(" + alias + iterator1 + iterator2 + "){" +
"return " + (genScopedSlot(key, el)) +
'})'
}
function genChildren (el, checkSkip) {
var children = el.children;
if (children.length) {
var el$1 = children[0];
// optimize single v-for
if (children.length === 1 &&
el$1.for &&
el$1.tag !== 'template' &&
el$1.tag !== 'slot'
) {
return genElement(el$1)
}
var normalizationType = checkSkip ? getNormalizationType(children) : 0;
return ("[" + (children.map(genNode).join(',')) + "]" + (normalizationType ? ("," + normalizationType) : ''))
}
}
// determine the normalization needed for the children array.
// 0: no normalization needed
// 1: simple normalization needed (possible 1-level deep nested array)
// 2: full normalization needed
function getNormalizationType (children) {
var res = 0;
for (var i = 0; i < children.length; i++) {
var el = children[i];
if (el.type !== 1) {
continue
}
if (needsNormalization(el) ||
(el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) {
res = 2;
break
}
if (maybeComponent(el) ||
(el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) {
res = 1;
}
}
return res
}
function needsNormalization (el) {
return el.for !== undefined || el.tag === 'template' || el.tag === 'slot'
}
function maybeComponent (el) {
return !isPlatformReservedTag$1(el.tag)
}
function genNode (node) {
if (node.type === 1) {
return genElement(node)
} else {
return genText(node)
}
}
function genText (text) {
return ("_v(" + (text.type === 2
? text.expression // no need for () because already wrapped in _s()
: transformSpecialNewlines(JSON.stringify(text.text))) + ")")
}
function genSlot (el) {
var slotName = el.slotName || '"default"';
var children = genChildren(el);
var res = "_t(" + slotName + (children ? ("," + children) : '');
var attrs = el.attrs && ("{" + (el.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}");
var bind$$1 = el.attrsMap['v-bind'];
if ((attrs || bind$$1) && !children) {
res += ",null";
}
if (attrs) {
res += "," + attrs;
}
if (bind$$1) {
res += (attrs ? '' : ',null') + "," + bind$$1;
}
return res + ')'
}
// componentName is el.component, take it as argument to shun flow's pessimistic refinement
function genComponent (componentName, el) {
var children = el.inlineTemplate ? null : genChildren(el, true);
return ("_c(" + componentName + "," + (genData(el)) + (children ? ("," + children) : '') + ")")
}
function genProps (props) {
var res = '';
for (var i = 0; i < props.length; i++) {
var prop = props[i];
res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ",";
}
return res.slice(0, -1)
}
// #3895, #4268
function transformSpecialNewlines (text) {
return text
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}
/* */
// these keywords should not appear inside expressions, but operators like
// typeof, instanceof and in are allowed
var prohibitedKeywordRE = new RegExp('\\b' + (
'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
'super,throw,while,yield,delete,export,import,return,switch,default,' +
'extends,finally,continue,debugger,function,arguments'
).split(',').join('\\b|\\b') + '\\b');
// these unary operators should not be used as property/method names
var unaryOperatorsRE = new RegExp('\\b' + (
'delete,typeof,void'
).split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)');
// check valid identifier for v-for
var identRE = /[A-Za-z_$][\w$]*/;
// strip strings in expressions
var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
// detect problematic expressions in a template
function detectErrors (ast) {
var errors = [];
if (ast) {
checkNode(ast, errors);
}
return errors
}
function checkNode (node, errors) {
if (node.type === 1) {
for (var name in node.attrsMap) {
if (dirRE.test(name)) {
var value = node.attrsMap[name];
if (value) {
if (name === 'v-for') {
checkFor(node, ("v-for=\"" + value + "\""), errors);
} else if (onRE.test(name)) {
checkEvent(value, (name + "=\"" + value + "\""), errors);
} else {
checkExpression(value, (name + "=\"" + value + "\""), errors);
}
}
}
}
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
checkNode(node.children[i], errors);
}
}
} else if (node.type === 2) {
checkExpression(node.expression, node.text, errors);
}
}
function checkEvent (exp, text, errors) {
var stipped = exp.replace(stripStringRE, '');
var keywordMatch = stipped.match(unaryOperatorsRE);
if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') {
errors.push(
"avoid using JavaScript unary operator as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + (text.trim())
);
}
checkExpression(exp, text, errors);
}
function checkFor (node, text, errors) {
checkExpression(node.for || '', text, errors);
checkIdentifier(node.alias, 'v-for alias', text, errors);
checkIdentifier(node.iterator1, 'v-for iterator', text, errors);
checkIdentifier(node.iterator2, 'v-for iterator', text, errors);
}
function checkIdentifier (ident, type, text, errors) {
if (typeof ident === 'string' && !identRE.test(ident)) {
errors.push(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim())));
}
}
function checkExpression (exp, text, errors) {
try {
new Function(("return " + exp));
} catch (e) {
var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);
if (keywordMatch) {
errors.push(
"avoid using JavaScript keyword as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + (text.trim())
);
} else {
errors.push(("invalid expression: " + (text.trim())));
}
}
}
/* */
function baseCompile (
template,
options
) {
var ast = parse(template.trim(), options);
optimize(ast, options);
var code = generate(ast, options);
return {
ast: ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
}
function makeFunction (code, errors) {
try {
return new Function(code)
} catch (err) {
errors.push({ err: err, code: code });
return noop
}
}
function createCompiler (baseOptions) {
var functionCompileCache = Object.create(null);
function compile (
template,
options
) {
var finalOptions = Object.create(baseOptions);
var errors = [];
var tips = [];
finalOptions.warn = function (msg, tip$$1) {
(tip$$1 ? tips : errors).push(msg);
};
if (options) {
// merge custom modules
if (options.modules) {
finalOptions.modules = (baseOptions.modules || []).concat(options.modules);
}
// merge custom directives
if (options.directives) {
finalOptions.directives = extend(
Object.create(baseOptions.directives),
options.directives
);
}
// copy other options
for (var key in options) {
if (key !== 'modules' && key !== 'directives') {
finalOptions[key] = options[key];
}
}
}
var compiled = baseCompile(template, finalOptions);
if (process.env.NODE_ENV !== 'production') {
errors.push.apply(errors, detectErrors(compiled.ast));
}
compiled.errors = errors;
compiled.tips = tips;
return compiled
}
function compileToFunctions (
template,
options,
vm
) {
options = options || {};
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
// detect possible CSP restriction
try {
new Function('return 1');
} catch (e) {
if (e.toString().match(/unsafe-eval|CSP/)) {
warn(
'It seems you are using the standalone build of Vue.js in an ' +
'environment with Content Security Policy that prohibits unsafe-eval. ' +
'The template compiler cannot work in this environment. Consider ' +
'relaxing the policy to allow unsafe-eval or pre-compiling your ' +
'templates into render functions.'
);
}
}
}
// check cache
var key = options.delimiters
? String(options.delimiters) + template
: template;
if (functionCompileCache[key]) {
return functionCompileCache[key]
}
// compile
var compiled = compile(template, options);
// check compilation errors/tips
if (process.env.NODE_ENV !== 'production') {
if (compiled.errors && compiled.errors.length) {
warn(
"Error compiling template:\n\n" + template + "\n\n" +
compiled.errors.map(function (e) { return ("- " + e); }).join('\n') + '\n',
vm
);
}
if (compiled.tips && compiled.tips.length) {
compiled.tips.forEach(function (msg) { return tip(msg, vm); });
}
}
// turn code into functions
var res = {};
var fnGenErrors = [];
res.render = makeFunction(compiled.render, fnGenErrors);
var l = compiled.staticRenderFns.length;
res.staticRenderFns = new Array(l);
for (var i = 0; i < l; i++) {
res.staticRenderFns[i] = makeFunction(compiled.staticRenderFns[i], fnGenErrors);
}
// check function generation errors.
// this should only happen if there is a bug in the compiler itself.
// mostly for codegen development use
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) {
warn(
"Failed to generate render function:\n\n" +
fnGenErrors.map(function (ref) {
var err = ref.err;
var code = ref.code;
return ((err.toString()) + " in\n\n" + code + "\n");
}).join('\n'),
vm
);
}
}
return (functionCompileCache[key] = res)
}
return {
compile: compile,
compileToFunctions: compileToFunctions
}
}
/* */
function transformNode (el, options) {
var warn = options.warn || baseWarn;
var staticClass = getAndRemoveAttr(el, 'class');
if (process.env.NODE_ENV !== 'production' && staticClass) {
var expression = parseText(staticClass, options.delimiters);
if (expression) {
warn(
"class=\"" + staticClass + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div class="{{ val }}">, use <div :class="val">.'
);
}
}
if (staticClass) {
el.staticClass = JSON.stringify(staticClass);
}
var classBinding = getBindingAttr(el, 'class', false /* getStatic */);
if (classBinding) {
el.classBinding = classBinding;
}
}
function genData$1 (el) {
var data = '';
if (el.staticClass) {
data += "staticClass:" + (el.staticClass) + ",";
}
if (el.classBinding) {
data += "class:" + (el.classBinding) + ",";
}
return data
}
var klass$1 = {
staticKeys: ['staticClass'],
transformNode: transformNode,
genData: genData$1
};
/* */
function transformNode$1 (el, options) {
var warn = options.warn || baseWarn;
var staticStyle = getAndRemoveAttr(el, 'style');
if (staticStyle) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
var expression = parseText(staticStyle, options.delimiters);
if (expression) {
warn(
"style=\"" + staticStyle + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div style="{{ val }}">, use <div :style="val">.'
);
}
}
el.staticStyle = JSON.stringify(parseStyleText(staticStyle));
}
var styleBinding = getBindingAttr(el, 'style', false /* getStatic */);
if (styleBinding) {
el.styleBinding = styleBinding;
}
}
function genData$2 (el) {
var data = '';
if (el.staticStyle) {
data += "staticStyle:" + (el.staticStyle) + ",";
}
if (el.styleBinding) {
data += "style:(" + (el.styleBinding) + "),";
}
return data
}
var style$1 = {
staticKeys: ['staticStyle'],
transformNode: transformNode$1,
genData: genData$2
};
var modules$1 = [
klass$1,
style$1
];
/* */
function text (el, dir) {
if (dir.value) {
addProp(el, 'textContent', ("_s(" + (dir.value) + ")"));
}
}
/* */
function html (el, dir) {
if (dir.value) {
addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")"));
}
}
var directives$1 = {
model: model,
text: text,
html: html
};
/* */
var baseOptions = {
expectHTML: true,
modules: modules$1,
directives: directives$1,
isPreTag: isPreTag,
isUnaryTag: isUnaryTag,
mustUseProp: mustUseProp,
canBeLeftOpenTag: canBeLeftOpenTag,
isReservedTag: isReservedTag,
getTagNamespace: getTagNamespace,
staticKeys: genStaticKeys(modules$1)
};
var ref$1 = createCompiler(baseOptions);
var compileToFunctions = ref$1.compileToFunctions;
/* */
var idToTemplate = cached(function (id) {
var el = query(id);
return el && el.innerHTML
});
var mount = Vue$3.prototype.$mount;
Vue$3.prototype.$mount = function (
el,
hydrating
) {
el = el && query(el);
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
process.env.NODE_ENV !== 'production' && warn(
"Do not mount Vue to <html> or <body> - mount to normal elements instead."
);
return this
}
var options = this.$options;
// resolve template/el and convert to render function
if (!options.render) {
var template = options.template;
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template);
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !template) {
warn(
("Template element not found or is empty: " + (options.template)),
this
);
}
}
} else if (template.nodeType) {
template = template.innerHTML;
} else {
if (process.env.NODE_ENV !== 'production') {
warn('invalid template option:' + template, this);
}
return this
}
} else if (el) {
template = getOuterHTML(el);
}
if (template) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile');
}
var ref = compileToFunctions(template, {
shouldDecodeNewlines: shouldDecodeNewlines,
delimiters: options.delimiters
}, this);
var render = ref.render;
var staticRenderFns = ref.staticRenderFns;
options.render = render;
options.staticRenderFns = staticRenderFns;
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile end');
measure(((this._name) + " compile"), 'compile', 'compile end');
}
}
}
return mount.call(this, el, hydrating)
};
/**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/
function getOuterHTML (el) {
if (el.outerHTML) {
return el.outerHTML
} else {
var container = document.createElement('div');
container.appendChild(el.cloneNode(true));
return container.innerHTML
}
}
Vue$3.compile = compileToFunctions;
/* harmony default export */ __webpack_exports__["default"] = (Vue$3);
/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(0), __webpack_require__(5)))
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _vue = __webpack_require__(3);
var _vue2 = _interopRequireDefault(_vue);
var _vueRouter = __webpack_require__(2);
var _vueRouter2 = _interopRequireDefault(_vueRouter);
var _vueResource = __webpack_require__(1);
var _vueResource2 = _interopRequireDefault(_vueResource);
var _header = __webpack_require__(7);
var _header2 = _interopRequireDefault(_header);
var _chain = __webpack_require__(21);
var _chain2 = _interopRequireDefault(_chain);
var _english = __webpack_require__(22);
var _english2 = _interopRequireDefault(_english);
var _jp = __webpack_require__(25);
var _jp2 = _interopRequireDefault(_jp);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
//引入vue-resource,类似ajax
var Foo = { template: '<div>foo</div>' };
var Bar = { template: '<div>bar</div>' };
console.log(Foo);
_vue2.default.use(_vueRouter2.default);
_vue2.default.use(_vueResource2.default);
var router = new _vueRouter2.default({
routes: [{
path: '/',
name: 'headHtml',
component: _header2.default,
redirect: '/Ch'
},
// { path: '/Ch', component: Ch, name: "Ch" },
{ path: '/En', component: _english2.default }, { path: '/Jp', component: _jp2.default }]
});
var vm = new _vue2.default({
el: "#app",
router: router,
data: function data() {
return {};
},
template: '<div><headHtml /></div>',
components: {
'headHtml': _header2.default
}
});
/***/ }),
/* 5 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
// This works if the window reference is available
if(typeof window === "object")
g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 6 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 7 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_header_vue__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_bec82480_node_modules_vue_loader_lib_selector_type_template_index_0_header_vue__ = __webpack_require__(12);
var disposed = false
function injectStyle (ssrContext) {
if (disposed) return
__webpack_require__(13)
}
var normalizeComponent = __webpack_require__(11)
/* script */
/* template */
/* styles */
var __vue_styles__ = injectStyle
/* scopeId */
var __vue_scopeId__ = null
/* moduleIdentifier (server only) */
var __vue_module_identifier__ = null
var Component = normalizeComponent(
__WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_header_vue__["a" /* default */],
__WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_bec82480_node_modules_vue_loader_lib_selector_type_template_index_0_header_vue__["a" /* default */],
__vue_styles__,
__vue_scopeId__,
__vue_module_identifier__
)
Component.options.__file = "myGit/vue/components/header.vue"
if (Component.esModule && Object.keys(Component.esModule).some(function (key) {return key !== "default" && key.substr(0, 2) !== "__"})) {console.error("named exports are not supported in *.vue files.")}
if (Component.options.functional) {console.error("[vue-loader] header.vue: functional components are not supported with templates, they should use render functions.")}
/* hot reload */
if (false) {(function () {
var hotAPI = require("vue-hot-reload-api")
hotAPI.install(require("vue"), false)
if (!hotAPI.compatible) return
module.hot.accept()
if (!module.hot.data) {
hotAPI.createRecord("data-v-bec82480", Component.options)
} else {
hotAPI.reload("data-v-bec82480", Component.options)
}
module.hot.dispose(function (data) {
disposed = true
})
})()}
/* harmony default export */ __webpack_exports__["default"] = (Component.exports);
/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
//
//
//
//
//
//
//
//
//
/* harmony default export */ __webpack_exports__["a"] = ({});
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(10)();
// imports
// module
exports.push([module.i, "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", ""]);
// exports
/***/ }),
/* 10 */
/***/ (function(module, exports) {
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
module.exports = function() {
var list = [];
// return the list of modules as css string
list.toString = function toString() {
var result = [];
for(var i = 0; i < this.length; i++) {
var item = this[i];
if(item[2]) {
result.push("@media " + item[2] + "{" + item[1] + "}");
} else {
result.push(item[1]);
}
}
return result.join("");
};
// import a list of modules into the list
list.i = function(modules, mediaQuery) {
if(typeof modules === "string")
modules = [[null, modules, ""]];
var alreadyImportedModules = {};
for(var i = 0; i < this.length; i++) {
var id = this[i][0];
if(typeof id === "number")
alreadyImportedModules[id] = true;
}
for(i = 0; i < modules.length; i++) {
var item = modules[i];
// skip already imported module
// this implementation is not 100% perfect for weird media query combinations
// when a module is imported multiple times with different media queries.
// I hope this will never occur (Hey this way we have smaller bundles)
if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) {
if(mediaQuery && !item[2]) {
item[2] = mediaQuery;
} else if(mediaQuery) {
item[2] = "(" + item[2] + ") and (" + mediaQuery + ")";
}
list.push(item);
}
}
};
return list;
};
/***/ }),
/* 11 */
/***/ (function(module, exports) {
/* globals __VUE_SSR_CONTEXT__ */
// this module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle
module.exports = function normalizeComponent (
rawScriptExports,
compiledTemplate,
injectStyles,
scopeId,
moduleIdentifier /* server only */
) {
var esModule
var scriptExports = rawScriptExports = rawScriptExports || {}
// ES6 modules interop
var type = typeof rawScriptExports.default
if (type === 'object' || type === 'function') {
esModule = rawScriptExports
scriptExports = rawScriptExports.default
}
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (compiledTemplate) {
options.render = compiledTemplate.render
options.staticRenderFns = compiledTemplate.staticRenderFns
}
// scopedId
if (scopeId) {
options._scopeId = scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = injectStyles
}
if (hook) {
var functional = options.functional
var existing = functional
? options.render
: options.beforeCreate
if (!functional) {
// inject component registration as beforeCreate hook
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
} else {
// register for functioal component in vue file
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return existing(h, context)
}
}
}
return {
esModule: esModule,
exports: scriptExports,
options: options
}
}
/***/ }),
/* 12 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('aside', [_c('router-link', {
attrs: {
"to": "/Ch"
}
}, [_vm._v("汉语")]), _vm._v(" "), _c('router-link', {
attrs: {
"to": "/En"
}
}, [_vm._v("英语课")]), _vm._v(" "), _c('router-link', {
attrs: {
"to": "/Jp"
}
}, [_vm._v("日语")]), _vm._v(" "), _c('router-view')], 1)
}
var staticRenderFns = []
render._withStripped = true
/* harmony default export */ __webpack_exports__["a"] = ({ render: render, staticRenderFns: staticRenderFns });
if (false) {
module.hot.accept()
if (module.hot.data) {
require("vue-hot-reload-api").rerender("data-v-bec82480", module.exports)
}
}
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__(9);
if(typeof content === 'string') content = [[module.i, content, '']];
if(content.locals) module.exports = content.locals;
// add the styles to the DOM
var update = __webpack_require__(14)("37f4116b", content, false);
// Hot Module Replacement
if(false) {
// When the styles change, update the <style> tags
if(!content.locals) {
module.hot.accept("!!../../../node_modules/css-loader/index.js!../../../node_modules/vue-loader/lib/style-compiler/index.js?{\"vue\":true,\"id\":\"data-v-bec82480\",\"scoped\":false,\"hasInlineConfig\":false}!../../../node_modules/vue-loader/lib/selector.js?type=styles&index=0!./header.vue", function() {
var newContent = require("!!../../../node_modules/css-loader/index.js!../../../node_modules/vue-loader/lib/style-compiler/index.js?{\"vue\":true,\"id\":\"data-v-bec82480\",\"scoped\":false,\"hasInlineConfig\":false}!../../../node_modules/vue-loader/lib/selector.js?type=styles&index=0!./header.vue");
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
update(newContent);
});
}
// When the module is disposed, remove the <style> tags
module.hot.dispose(function() { update(); });
}
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
Modified by Evan You @yyx990803
*/
var hasDocument = typeof document !== 'undefined'
if (typeof DEBUG !== 'undefined' && DEBUG) {
if (!hasDocument) {
throw new Error(
'vue-style-loader cannot be used in a non-browser environment. ' +
"Use { target: 'node' } in your Webpack config to indicate a server-rendering environment."
) }
}
var listToStyles = __webpack_require__(15)
/*
type StyleObject = {
id: number;
parts: Array<StyleObjectPart>
}
type StyleObjectPart = {
css: string;
media: string;
sourceMap: ?string
}
*/
var stylesInDom = {/*
[id: number]: {
id: number,
refs: number,
parts: Array<(obj?: StyleObjectPart) => void>
}
*/}
var head = hasDocument && (document.head || document.getElementsByTagName('head')[0])
var singletonElement = null
var singletonCounter = 0
var isProduction = false
var noop = function () {}
// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
// tags it will allow on a page
var isOldIE = typeof navigator !== 'undefined' && /msie [6-9]\b/.test(navigator.userAgent.toLowerCase())
module.exports = function (parentId, list, _isProduction) {
isProduction = _isProduction
var styles = listToStyles(parentId, list)
addStylesToDom(styles)
return function update (newList) {
var mayRemove = []
for (var i = 0; i < styles.length; i++) {
var item = styles[i]
var domStyle = stylesInDom[item.id]
domStyle.refs--
mayRemove.push(domStyle)
}
if (newList) {
styles = listToStyles(parentId, newList)
addStylesToDom(styles)
} else {
styles = []
}
for (var i = 0; i < mayRemove.length; i++) {
var domStyle = mayRemove[i]
if (domStyle.refs === 0) {
for (var j = 0; j < domStyle.parts.length; j++) {
domStyle.parts[j]()
}
delete stylesInDom[domStyle.id]
}
}
}
}
function addStylesToDom (styles /* Array<StyleObject> */) {
for (var i = 0; i < styles.length; i++) {
var item = styles[i]
var domStyle = stylesInDom[item.id]
if (domStyle) {
domStyle.refs++
for (var j = 0; j < domStyle.parts.length; j++) {
domStyle.parts[j](item.parts[j])
}
for (; j < item.parts.length; j++) {
domStyle.parts.push(addStyle(item.parts[j]))
}
if (domStyle.parts.length > item.parts.length) {
domStyle.parts.length = item.parts.length
}
} else {
var parts = []
for (var j = 0; j < item.parts.length; j++) {
parts.push(addStyle(item.parts[j]))
}
stylesInDom[item.id] = { id: item.id, refs: 1, parts: parts }
}
}
}
function createStyleElement () {
var styleElement = document.createElement('style')
styleElement.type = 'text/css'
head.appendChild(styleElement)
return styleElement
}
function addStyle (obj /* StyleObjectPart */) {
var update, remove
var styleElement = document.querySelector('style[data-vue-ssr-id~="' + obj.id + '"]')
if (styleElement) {
if (isProduction) {
// has SSR styles and in production mode.
// simply do nothing.
return noop
} else {
// has SSR styles but in dev mode.
// for some reason Chrome can't handle source map in server-rendered
// style tags - source maps in <style> only works if the style tag is
// created and inserted dynamically. So we remove the server rendered
// styles and inject new ones.
styleElement.parentNode.removeChild(styleElement)
}
}
if (isOldIE) {
// use singleton mode for IE9.
var styleIndex = singletonCounter++
styleElement = singletonElement || (singletonElement = createStyleElement())
update = applyToSingletonTag.bind(null, styleElement, styleIndex, false)
remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true)
} else {
// use multi-style-tag mode in all other cases
styleElement = createStyleElement()
update = applyToTag.bind(null, styleElement)
remove = function () {
styleElement.parentNode.removeChild(styleElement)
}
}
update(obj)
return function updateStyle (newObj /* StyleObjectPart */) {
if (newObj) {
if (newObj.css === obj.css &&
newObj.media === obj.media &&
newObj.sourceMap === obj.sourceMap) {
return
}
update(obj = newObj)
} else {
remove()
}
}
}
var replaceText = (function () {
var textStore = []
return function (index, replacement) {
textStore[index] = replacement
return textStore.filter(Boolean).join('\n')
}
})()
function applyToSingletonTag (styleElement, index, remove, obj) {
var css = remove ? '' : obj.css
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = replaceText(index, css)
} else {
var cssNode = document.createTextNode(css)
var childNodes = styleElement.childNodes
if (childNodes[index]) styleElement.removeChild(childNodes[index])
if (childNodes.length) {
styleElement.insertBefore(cssNode, childNodes[index])
} else {
styleElement.appendChild(cssNode)
}
}
}
function applyToTag (styleElement, obj) {
var css = obj.css
var media = obj.media
var sourceMap = obj.sourceMap
if (media) {
styleElement.setAttribute('media', media)
}
if (sourceMap) {
// https://developer.chrome.com/devtools/docs/javascript-debugging
// this makes source maps inside style tags work properly in Chrome
css += '\n/*# sourceURL=' + sourceMap.sources[0] + ' */'
// http://stackoverflow.com/a/26603875
css += '\n/*# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + ' */'
}
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = css
} else {
while (styleElement.firstChild) {
styleElement.removeChild(styleElement.firstChild)
}
styleElement.appendChild(document.createTextNode(css))
}
}
/***/ }),
/* 15 */
/***/ (function(module, exports) {
/**
* Translates the list format produced by css-loader into something
* easier to manipulate.
*/
module.exports = function listToStyles (parentId, list) {
var styles = []
var newStyles = {}
for (var i = 0; i < list.length; i++) {
var item = list[i]
var id = item[0]
var css = item[1]
var media = item[2]
var sourceMap = item[3]
var part = {
id: parentId + ':' + i,
css: css,
media: media,
sourceMap: sourceMap
}
if (!newStyles[id]) {
styles.push(newStyles[id] = { id: id, parts: [part] })
} else {
newStyles[id].parts.push(part)
}
}
return styles
}
/***/ }),
/* 16 */,
/* 17 */,
/* 18 */,
/* 19 */,
/* 20 */,
/* 21 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_template_compiler_index_id_data_v_373d7a9c_node_modules_vue_loader_lib_selector_type_template_index_0_chain_vue__ = __webpack_require__(23);
var disposed = false
var normalizeComponent = __webpack_require__(11)
/* script */
var __vue_script__ = null
/* template */
/* styles */
var __vue_styles__ = null
/* scopeId */
var __vue_scopeId__ = null
/* moduleIdentifier (server only) */
var __vue_module_identifier__ = null
var Component = normalizeComponent(
__vue_script__,
__WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_template_compiler_index_id_data_v_373d7a9c_node_modules_vue_loader_lib_selector_type_template_index_0_chain_vue__["a" /* default */],
__vue_styles__,
__vue_scopeId__,
__vue_module_identifier__
)
Component.options.__file = "myGit/vue/components/header/chain.vue"
if (Component.esModule && Object.keys(Component.esModule).some(function (key) {return key !== "default" && key.substr(0, 2) !== "__"})) {console.error("named exports are not supported in *.vue files.")}
if (Component.options.functional) {console.error("[vue-loader] chain.vue: functional components are not supported with templates, they should use render functions.")}
/* hot reload */
if (false) {(function () {
var hotAPI = require("vue-hot-reload-api")
hotAPI.install(require("vue"), false)
if (!hotAPI.compatible) return
module.hot.accept()
if (!module.hot.data) {
hotAPI.createRecord("data-v-373d7a9c", Component.options)
} else {
hotAPI.reload("data-v-373d7a9c", Component.options)
}
module.hot.dispose(function (data) {
disposed = true
})
})()}
/* harmony default export */ __webpack_exports__["default"] = (Component.exports);
/***/ }),
/* 22 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_english_vue__ = __webpack_require__(27);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_523584a1_node_modules_vue_loader_lib_selector_type_template_index_0_english_vue__ = __webpack_require__(24);
var disposed = false
var normalizeComponent = __webpack_require__(11)
/* script */
/* template */
/* styles */
var __vue_styles__ = null
/* scopeId */
var __vue_scopeId__ = null
/* moduleIdentifier (server only) */
var __vue_module_identifier__ = null
var Component = normalizeComponent(
__WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_english_vue__["a" /* default */],
__WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_523584a1_node_modules_vue_loader_lib_selector_type_template_index_0_english_vue__["a" /* default */],
__vue_styles__,
__vue_scopeId__,
__vue_module_identifier__
)
Component.options.__file = "myGit/vue/components/header/english.vue"
if (Component.esModule && Object.keys(Component.esModule).some(function (key) {return key !== "default" && key.substr(0, 2) !== "__"})) {console.error("named exports are not supported in *.vue files.")}
if (Component.options.functional) {console.error("[vue-loader] english.vue: functional components are not supported with templates, they should use render functions.")}
/* hot reload */
if (false) {(function () {
var hotAPI = require("vue-hot-reload-api")
hotAPI.install(require("vue"), false)
if (!hotAPI.compatible) return
module.hot.accept()
if (!module.hot.data) {
hotAPI.createRecord("data-v-523584a1", Component.options)
} else {
hotAPI.reload("data-v-523584a1", Component.options)
}
module.hot.dispose(function (data) {
disposed = true
})
})()}
/* harmony default export */ __webpack_exports__["default"] = (Component.exports);
/***/ }),
/* 23 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('div', [_vm._v("1")])
}
var staticRenderFns = []
render._withStripped = true
/* harmony default export */ __webpack_exports__["a"] = ({ render: render, staticRenderFns: staticRenderFns });
if (false) {
module.hot.accept()
if (module.hot.data) {
require("vue-hot-reload-api").rerender("data-v-373d7a9c", module.exports)
}
}
/***/ }),
/* 24 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('div', [_vm._v("2")])
}
var staticRenderFns = []
render._withStripped = true
/* harmony default export */ __webpack_exports__["a"] = ({ render: render, staticRenderFns: staticRenderFns });
if (false) {
module.hot.accept()
if (module.hot.data) {
require("vue-hot-reload-api").rerender("data-v-523584a1", module.exports)
}
}
/***/ }),
/* 25 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_template_compiler_index_id_data_v_61a6a1a5_node_modules_vue_loader_lib_selector_type_template_index_0_jp_vue__ = __webpack_require__(26);
var disposed = false
var normalizeComponent = __webpack_require__(11)
/* script */
var __vue_script__ = null
/* template */
/* styles */
var __vue_styles__ = null
/* scopeId */
var __vue_scopeId__ = null
/* moduleIdentifier (server only) */
var __vue_module_identifier__ = null
var Component = normalizeComponent(
__vue_script__,
__WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_template_compiler_index_id_data_v_61a6a1a5_node_modules_vue_loader_lib_selector_type_template_index_0_jp_vue__["a" /* default */],
__vue_styles__,
__vue_scopeId__,
__vue_module_identifier__
)
Component.options.__file = "myGit/vue/components/header/jp.vue"
if (Component.esModule && Object.keys(Component.esModule).some(function (key) {return key !== "default" && key.substr(0, 2) !== "__"})) {console.error("named exports are not supported in *.vue files.")}
if (Component.options.functional) {console.error("[vue-loader] jp.vue: functional components are not supported with templates, they should use render functions.")}
/* hot reload */
if (false) {(function () {
var hotAPI = require("vue-hot-reload-api")
hotAPI.install(require("vue"), false)
if (!hotAPI.compatible) return
module.hot.accept()
if (!module.hot.data) {
hotAPI.createRecord("data-v-61a6a1a5", Component.options)
} else {
hotAPI.reload("data-v-61a6a1a5", Component.options)
}
module.hot.dispose(function (data) {
disposed = true
})
})()}
/* harmony default export */ __webpack_exports__["default"] = (Component.exports);
/***/ }),
/* 26 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('div', [_vm._v("3")])
}
var staticRenderFns = []
render._withStripped = true
/* harmony default export */ __webpack_exports__["a"] = ({ render: render, staticRenderFns: staticRenderFns });
if (false) {
module.hot.accept()
if (module.hot.data) {
require("vue-hot-reload-api").rerender("data-v-61a6a1a5", module.exports)
}
}
/***/ }),
/* 27 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
//
//
//
/* harmony default export */ __webpack_exports__["a"] = ({});
/***/ })
/******/ ]); | appqian/vue | src/index.js | JavaScript | gpl-2.0 | 390,912 |
<?php
/**
* OG behavior handler.
*/
class OgBehaviorHandler extends EntityReference_BehaviorHandler_Abstract {
/**
* Implements EntityReference_BehaviorHandler_Abstract::access().
*/
public function access($field, $instance) {
return $field['settings']['handler'] == 'og' || strpos($field['settings']['handler'], 'og_') === 0;
}
/**
* Implements EntityReference_BehaviorHandler_Abstract::load().
*/
public function load($entity_type, $entities, $field, $instances, $langcode, &$items) {
// Get the OG memberships from the field.
$field_name = $field['field_name'];
$target_type = $field['settings']['target_type'];
foreach ($entities as $entity) {
$wrapper = entity_metadata_wrapper($entity_type, $entity);
if (empty($wrapper->{$field_name})) {
// If the entity belongs to a bundle that was deleted, return early.
continue;
}
$id = $wrapper->getIdentifier();
$items[$id] = array();
$gids = og_get_entity_groups($entity_type, $entity, array(), $field_name);
if (empty($gids[$target_type])) {
continue;
}
foreach ($gids[$target_type] as $gid) {
$items[$id][] = array(
'target_id' => $gid,
);
}
}
}
/**
* Implements EntityReference_BehaviorHandler_Abstract::insert().
*/
public function insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
if (!empty($entity->skip_og_membership)) {
return;
}
$this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items);
$items = array();
}
/**
* Implements EntityReference_BehaviorHandler_Abstract::access().
*/
public function update($entity_type, $entity, $field, $instance, $langcode, &$items) {
if (!empty($entity->skip_og_membership)) {
return;
}
$this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items);
$items = array();
}
/**
* Implements EntityReference_BehaviorHandler_Abstract::Delete()
*
* CRUD memberships from field, or if entity is marked for deleteing,
* delete all the OG membership related to it.
*
* @see og_entity_delete().
*/
public function delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
if (!empty($entity->skip_og_membership)) {
return;
}
if (!empty($entity->delete_og_membership)) {
// Delete all OG memberships related to this entity.
$og_memberships = array();
foreach (og_get_entity_groups($entity_type, $entity) as $group_type => $ids) {
$og_memberships = array_merge($og_memberships, array_keys($ids));
}
if ($og_memberships) {
og_membership_delete_multiple($og_memberships);
}
}
else {
$this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items);
}
}
/**
* Create, update or delete OG membership based on field values.
*/
public function OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, &$items) {
if (!user_access('administer group') && !field_access('edit', $field, $entity_type, $entity)) {
// User has no access to field.
return;
}
if (!$diff = $this->groupAudiencegetDiff($entity_type, $entity, $field, $instance, $langcode, $items)) {
return;
}
$field_name = $field['field_name'];
$group_type = $field['settings']['target_type'];
$diff += array('insert' => array(), 'delete' => array());
// Delete first, so we don't trigger cardinality errors.
if ($diff['delete']) {
og_membership_delete_multiple($diff['delete']);
}
if (!$diff['insert']) {
return;
}
// Prepare an array with the membership state, if it was provided in the widget.
$states = array();
foreach ($items as $item) {
$gid = $item['target_id'];
if (empty($item['state']) || !in_array($gid, $diff['insert'])) {
// State isn't provided, or not an "insert" operation.
continue;
}
$states[$gid] = $item['state'];
}
foreach ($diff['insert'] as $gid) {
$values = array(
'entity_type' => $entity_type,
'entity' => $entity,
'field_name' => $field_name,
);
if (!empty($states[$gid])) {
$values['state'] = $states[$gid];
}
og_group($group_type, $gid, $values);
}
}
/**
* Get the difference in group audience for a saved field.
*
* @return
* Array with all the differences, or an empty array if none found.
*/
public function groupAudiencegetDiff($entity_type, $entity, $field, $instance, $langcode, $items) {
$return = FALSE;
$field_name = $field['field_name'];
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$og_memberships = $wrapper->{$field_name . '__og_membership'}->value();
$new_memberships = array();
foreach ($items as $item) {
$new_memberships[$item['target_id']] = TRUE;
}
foreach ($og_memberships as $og_membership) {
$gid = $og_membership->gid;
if (empty($new_memberships[$gid])) {
// Membership was deleted.
if ($og_membership->entity_type == 'user') {
// Make sure this is not the group manager, if exists.
$group = entity_load_single($og_membership->group_type, $og_membership->gid);
if (!empty($group->uid) && $group->uid == $og_membership->etid) {
continue;
}
}
$return['delete'][] = $og_membership->id;
unset($new_memberships[$gid]);
}
else {
// Existing membership.
unset($new_memberships[$gid]);
}
}
if ($new_memberships) {
// New memberships.
$return['insert'] = array_keys($new_memberships);
}
return $return;
}
/**
* Implements EntityReference_BehaviorHandler_Abstract::views_data_alter().
*/
public function views_data_alter(&$data, $field) {
// We need to override the default EntityReference table settings when OG
// behavior is being used.
if (og_is_group_audience_field($field['field_name'])) {
$entity_types = array_keys($field['bundles']);
// We need to join the base table for the entities
// that this field is attached to.
foreach ($entity_types as $entity_type) {
$entity_info = entity_get_info($entity_type);
$data['og_membership'] = array(
'table' => array(
'join' => array(
$entity_info['base table'] => array(
// Join entity base table on its id field with left_field.
'left_field' => $entity_info['entity keys']['id'],
'field' => 'etid',
'extra' => array(
0 => array(
'field' => 'entity_type',
'value' => $entity_type,
),
),
),
),
),
// Copy the original config from the table definition.
$field['field_name'] => $data['field_data_' . $field['field_name']][$field['field_name']],
$field['field_name'] . '_target_id' => $data['field_data_' . $field['field_name']][$field['field_name'] . '_target_id'],
);
// Change config with settings from og_membership table.
foreach (array('filter', 'argument', 'sort') as $op) {
$data['og_membership'][$field['field_name'] . '_target_id'][$op]['field'] = 'gid';
$data['og_membership'][$field['field_name'] . '_target_id'][$op]['table'] = 'og_membership';
unset($data['og_membership'][$field['field_name'] . '_target_id'][$op]['additional fields']);
}
}
// Get rid of the original table configs.
unset($data['field_data_' . $field['field_name']]);
unset($data['field_revision_' . $field['field_name']]);
}
}
/**
* Implements EntityReference_BehaviorHandler_Abstract::validate().
*
* Re-build $errors array to be keyed correctly by "default" and "admin" field
* modes.
*
* @todo: Try to get the correct delta so we can highlight the invalid
* reference.
*
* @see entityreference_field_validate().
*/
public function validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
$new_errors = array();
$values = array('default' => array(), 'admin' => array());
$item = reset($items);
if (!empty($item['field_mode'])) {
// This is a complex widget with "default" and "admin" field modes.
foreach ($items as $item) {
$values[$item['field_mode']][] = $item['target_id'];
}
}
else {
foreach ($items as $item) {
if (!entityreference_field_is_empty($item, $field) && $item['target_id'] !== NULL) {
$values['default'][] = $item['target_id'];
}
}
}
$field_name = $field['field_name'];
foreach ($values as $field_mode => $ids) {
if (!$ids) {
continue;
}
if ($field_mode == 'admin' && !user_access('administer group')) {
// No need to validate the admin, as the user has no access to it.
continue;
}
$instance['field_mode'] = $field_mode;
$valid_ids = entityreference_get_selection_handler($field, $instance, $entity_type, $entity)->validateReferencableEntities($ids);
if ($invalid_entities = array_diff($ids, $valid_ids)) {
foreach ($invalid_entities as $id) {
$new_errors[$field_mode][] = array(
'error' => 'og_invalid_entity',
'message' => t('The referenced group (@type: @id) is invalid.', array('@type' => $field['settings']['target_type'], '@id' => $id)),
);
}
}
}
if ($new_errors) {
og_field_widget_register_errors($field_name, $new_errors);
// We throw an exception ourself, as we unset the $errors array.
throw new FieldValidationException($new_errors);
}
// Errors for this field now handled, removing from the referenced array.
unset($errors[$field_name]);
}
}
| codifi/mukurtucms | sites/all/modules/contrib/og/plugins/entityreference/behavior/OgBehaviorHandler.class.php | PHP | gpl-2.0 | 10,070 |
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Spoodle
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'Bern'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
end
| ASE-2014/spoodle | config/application.rb | Ruby | gpl-2.0 | 954 |
using System;
using System.Diagnostics;
namespace Lumpn.Profiling
{
public sealed class Recorder
{
private readonly Stopwatch stopwatch = new Stopwatch();
private readonly string name;
public Recorder(string name)
{
this.name = name;
}
public void Reset()
{
stopwatch.Reset();
}
public void Begin()
{
stopwatch.Start();
}
public void End()
{
stopwatch.Stop();
}
public void Submit()
{
Profiler.AddSample(name, stopwatch.ElapsedTicks);
}
}
}
| lumpn/infinite-zelda | Lumpn.Profiling/Recorder.cs | C# | gpl-2.0 | 658 |
<?php
/**
*
*
*/
/**
* Import SQL data.
*
* @param string $args as the queries of sql data , you could use file get contents to read data args
* @param string/array $tables_whitelist 'all' = all tables; array('tbl1',...) = only listet tables
* @param string $dbhost database host
* @param string $dbuser database user
* @param string $dbpass database password
* @param string $dbname database name
*
* @return string complete if complete
*/
function database_import( $args, $tables_whitelist, $dbhost, $dbuser, $dbpass, $dbname ) {
// check mysqli extension installed
if ( !function_exists('mysqli_connect') ) {
die('This scripts need mysql extension to be running properly! Please resolve!');
}
$mysqli = @new mysqli( $dbhost, $dbuser, $dbpass, $dbname );
if ( $mysqli->connect_error ) {
print_r( $mysqli->connect_error );
return false;
}
// DROP all tables (be carefull...)
$mysqli->query('SET foreign_key_checks = 0');
if ( $result = $mysqli->query("SHOW TABLES") ) {
while ( $row = $result->fetch_array(MYSQLI_NUM) ) {
if ( $tables_whitelist=='all' || in_array($row[0], (array)$tables_whitelist) ) {
$mysqli->query('DROP TABLE IF EXISTS '.$row[0]);
}
}
}
$mysqli->query('SET foreign_key_checks = 1');
$querycount = 11;
$queryerrors = '';
$lines = (array) $args;
if ( is_string( $args ) ) {
$lines = array( $args ) ;
}
if ( ! $lines ) {
return 'cannot execute ' . $args;
}
$scriptfile = false;
foreach ($lines as $line) {
$line = trim( $line );
// if have -- comments add enters
if (substr( $line, 0, 2 ) == '--') {
$line = "\n" . $line;
}
if (substr( $line, 0, 2 ) != '--') {
$scriptfile .= ' ' . $line;
continue;
}
}
$queries = explode( ';', $scriptfile );
foreach ($queries as $query) {
$query = trim( $query );
++$querycount;
if ( $query == '' ) {
continue;
}
if ( ! $mysqli->query( $query ) ) {
$queryerrors .= 'Line ' . $querycount . ' - ' . $mysqli->error . '<br />';
continue;
}
}
if ( $queryerrors ) {
return 'There was an error on File: ' . $filename . '<br />' . $queryerrors;
}
if( $mysqli && ! $mysqli->error ) {
@$mysqli->close();
}
return 'Complete dumping database!';
}
/**
* Export SQL data.
*
* if directory writable will be make directory inside of directory if not exist, else will be die
*
* @param string directory, as the directory to put file
* @param string $outname as file name just the name
* @param string/array $tables_whitelist 'all' = all tables; array('tbl1',...) = only listet tables
* @param string $dbhost database host
* @param string $dbuser database user
* @param string $dbpass database password
* @param string $dbname database name
*
*/
function database_backup( $directory, $outname, $tables_whitelist, $dbhost, $dbuser, $dbpass, $dbname ) {
// check mysqli extension installed
if ( !function_exists('mysqli_connect') ) {
die('This scripts need mysql extension to be running properly! Please resolve!');
}
$mysqli = @new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ( $mysqli->connect_error ) {
print_r( $mysqli->connect_error );
return false;
}
$dir = $directory;
$result = '<p>Could not create backup directory on :'.$dir.' Please Please make sure you have set Directory on 755 or 777 for a while.</p>';
$res = true;
if ( !is_dir( $dir ) ) {
if( !@mkdir( $dir, 755 ) ) {
$res = false;
}
}
$n = 1;
if ( $res ) {
$name = $outname.'_'.date('Y-m-d-H-i-s');
$fullname = $dir.'/'.$name.'.sql'; # full structures
if ( !$mysqli->error ) {
$sql = "SHOW TABLES";
$show = $mysqli->query($sql);
while ( $row = $show->fetch_array() ) {
if ( $tables_whitelist=='all' || in_array($row[0], (array)$tables_whitelist) ) {
$tables[] = $row[0];
}
}
if ( !empty( $tables ) ) {
// Cycle through
$return = '';
foreach ( $tables as $table )
{
$result = $mysqli->query('SELECT * FROM '.$table);
$num_fields = $result->field_count;
$row2 = $mysqli->query('SHOW CREATE TABLE '.$table );
$row2 = $row2->fetch_row();
$return .=
"\n
-- ---------------------------------------------------------
--
-- Table structure for table : `{$table}`
--
-- ---------------------------------------------------------
".$row2[1].";\n";
for ($i = 0; $i < $num_fields; $i++)
{
$n = 1 ;
while ( $row = $result->fetch_row() )
{
if ( $n++ == 1 ) { # set the first statements
$return .=
"
--
-- Dumping data for table `{$table}`
--
";
/**
* Get structural of fields each tables
*/
$array_field = array(); #reset ! important to resetting when loop
while ( $field = $result->fetch_field() ) # get field
{
$array_field[] = '`'.$field->name.'`';
}
$array_f[$table] = $array_field;
// $array_f = $array_f;
# endwhile
$array_field = implode(', ', $array_f[$table]); #implode arrays
$return .= "INSERT INTO `{$table}` ({$array_field}) VALUES\n(";
} else {
$return .= '(';
}
for ($j=0; $j<$num_fields; $j++)
{
$row[$j] = str_replace('\'','\'\'', preg_replace("/\n/","\\n", $row[$j] ) );
if ( isset( $row[$j] ) ) { $return .= is_numeric( $row[$j] ) ? $row[$j] : '\''.$row[$j].'\'' ; } else { $return.= '\'\''; }
if ( $j<($num_fields-1) ) { $return.= ', '; }
}
$return.= "),\n";
}
# check matching
@preg_match("/\),\n/", $return, $match, false, -3); # check match
if ( isset( $match[0] ) )
{
$return = substr_replace( $return, ";\n", -2);
}
}
$return .= "\n";
}
$return =
"-- ---------------------------------------------------------
--
-- Simple SQL Dump
--
--
-- Host Connection Info: ".$mysqli->host_info."
-- Generation Time: ".date('F d, Y \a\t H:i A ( e )')."
-- Server version: ".$mysqli->server_info."
-- PHP Version: ".PHP_VERSION."
--
-- ---------------------------------------------------------\n\n
SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";
SET time_zone = \"+00:00\";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
".$return."
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
# end values result
if( @file_put_contents( $fullname, $return ) ) { # 9 as compression levels
$result = $name.'.sql'; # show the name
} else {
$result = '<p>Error when saving the export.</p>';
}
} else {
$result = '<p>Error when executing database query to export.</p>'.$mysqli->error;
}
}
} else {
$result = '<p>Wrong mysqli input</p>';
}
if( $mysqli && ! $mysqli->error ) {
@$mysqli->close();
}
return $result;
} | Vegvisir/Nami | tools/db/database.func.php | PHP | gpl-2.0 | 6,970 |
<?php
/**
* Uses the Porter Stemmer algorithm to find word roots.
*
* Adapted from Joomla com_finder component.
* Based on the Porter stemmer algorithm:
* <https://tartarus.org/martin/PorterStemmer/c.txt>
*
* @author Lee Garner <lee@leegarner.com>
* @copyright Copyright (C) 2017 Lee Garner <lee@leegarner.com>
* @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
* @package searcher
* @version 0.0.1
* @license http://opensource.org/licenses/gpl-2.0.php
* GNU Public License v2 or later
* @filesource
*/
namespace Searcher;
/**
* Porter English stemmer class for the Finder indexer package.
*
* This class was adapted from one written by Richard Heyes.
* See copyright and link information above.
*/
class StemmerPorter_en extends Stemmer
{
/**
* Regex for matching a consonant.
* @var string
*/
private static $regex_consonant = '(?:[bcdfghjklmnpqrstvwxz]|(?<=[aeiou])y|^y)';
/**
* Regex for matching a vowel
* @var string
*/
private static $regex_vowel = '(?:[aeiou]|(?<![aeiou])y)';
/**
* Method to stem a token and return the root.
*
* @param string $token The token to stem.
* @param string $lang The language of the token.
* @return string The root token.
*/
public function stem($token, $lang='en')
{
global $_CONF;
// Check if the token is long enough to merit stemming.
if (strlen($token) <= self::$min_word_len) {
return $token;
}
// Check if the language is English or All.
/*if ($lang !== 'en' && $lang != '*')
{
return $token;
}*/
// Stem the token if it is not in the cache.
if (!isset($this->cache[$lang][$token]))
{
// Stem the token.
$result = trim($token);
$result = self::step1ab($result);
$result = self::step1c($result);
$result = self::step2($result);
$result = self::step3($result);
$result = self::step4($result);
$result = self::step5($result);
$result = trim($result);
// Add the token to the cache.
$this->cache[$lang][$token] = $result;
}
return $this->cache[$lang][$token];
}
/**
* step1ab() gets rid of plurals and -ed or -ing. e.g.
*
* caresses -> caress
* ponies -> poni
* ties -> ti
* caress -> caress
* cats -> cat
*
* feed -> feed
* agreed -> agree
* disabled -> disable
*
* matting -> mat
* mating -> mate
* meeting -> meet
* milling -> mill
* messing -> mess
* meetings -> meet
*
* @param string $word The token to stem.
* @return string
*/
private static function step1ab($word)
{
// Part a
if (substr($word, -1) == 's')
{
self::replace($word, 'sses', 'ss')
or self::replace($word, 'ies', 'i')
or self::replace($word, 'ss', 'ss')
or self::replace($word, 's', '');
}
// Part b
if (substr($word, -2, 1) != 'e' or !self::replace($word, 'eed', 'ee', 0))
{
// First rule
$v = self::$regex_vowel;
// Words ending with ing and ed
// Note use of && and OR, for precedence reasons
if (preg_match("#$v+#", substr($word, 0, -3)) && self::replace($word, 'ing', '')
or preg_match("#$v+#", substr($word, 0, -2)) && self::replace($word, 'ed', ''))
{
// If one of above two test successful
if (!self::replace($word, 'at', 'ate') and !self::replace($word, 'bl', 'ble') and !self::replace($word, 'iz', 'ize'))
{
// Double consonant ending
if (self::doubleConsonant($word) and substr($word, -2) != 'll' and substr($word, -2) != 'ss' and substr($word, -2) != 'zz')
{
$word = substr($word, 0, -1);
}
elseif (self::m($word) == 1 and self::cvc($word))
{
$word .= 'e';
}
}
}
}
return $word;
}
/**
* step1c() turns terminal y to i when there is another vowel in the stem.
*
* @param string $word The token to stem.
* @return string
*/
private static function step1c($word)
{
$v = self::$regex_vowel;
if (substr($word, -1) == 'y' && preg_match("#$v+#", substr($word, 0, -1)))
{
self::replace($word, 'y', 'i');
}
return $word;
}
/**
* step2() maps double suffices to single ones. so -izationi
* ( = -ize plus -ation) maps to -ize etc.
* Note that the string before the suffix must give m() > 0.
*
* @param string $word The token to stem.
* @return string
*/
private static function step2($word)
{
switch (substr($word, -2, 1))
{
case 'a':
self::replace($word, 'ational', 'ate', 0)
or self::replace($word, 'tional', 'tion', 0);
break;
case 'c':
self::replace($word, 'enci', 'ence', 0)
or self::replace($word, 'anci', 'ance', 0);
break;
case 'e':
self::replace($word, 'izer', 'ize', 0);
break;
case 'g':
self::replace($word, 'logi', 'log', 0);
break;
case 'l':
self::replace($word, 'entli', 'ent', 0)
or self::replace($word, 'ousli', 'ous', 0)
or self::replace($word, 'alli', 'al', 0)
or self::replace($word, 'bli', 'ble', 0)
or self::replace($word, 'eli', 'e', 0);
break;
case 'o':
self::replace($word, 'ization', 'ize', 0)
or self::replace($word, 'ation', 'ate', 0)
or self::replace($word, 'ator', 'ate', 0);
break;
case 's':
self::replace($word, 'iveness', 'ive', 0)
or self::replace($word, 'fulness', 'ful', 0)
or self::replace($word, 'ousness', 'ous', 0)
or self::replace($word, 'alism', 'al', 0);
break;
case 't':
self::replace($word, 'biliti', 'ble', 0)
or self::replace($word, 'aliti', 'al', 0)
or self::replace($word, 'iviti', 'ive', 0);
break;
}
return $word;
}
/**
* step3() deals with -ic-, -full, -ness etc. similar strategy to step2.
*
* @param string $word The token to stem.
* @return string
*/
private static function step3($word)
{
switch (substr($word, -2, 1))
{
case 'a':
self::replace($word, 'ical', 'ic', 0);
break;
case 's':
self::replace($word, 'ness', '', 0);
break;
case 't':
self::replace($word, 'icate', 'ic', 0)
or self::replace($word, 'iciti', 'ic', 0);
break;
case 'u':
self::replace($word, 'ful', '', 0);
break;
case 'v':
self::replace($word, 'ative', '', 0);
break;
case 'z':
self::replace($word, 'alize', 'al', 0);
break;
}
return $word;
}
/**
* step4() takes off -ant, -ence etc., in context <c>vcvc<v>.
*
* @param string $word The token to stem.
* @return string
*/
private static function step4($word)
{
switch (substr($word, -2, 1))
{
case 'a':
self::replace($word, 'al', '', 1);
break;
case 'c':
self::replace($word, 'ance', '', 1)
or self::replace($word, 'ence', '', 1);
break;
case 'e':
self::replace($word, 'er', '', 1);
break;
case 'i':
self::replace($word, 'ic', '', 1);
break;
case 'l':
self::replace($word, 'able', '', 1)
or self::replace($word, 'ible', '', 1);
break;
case 'n':
self::replace($word, 'ant', '', 1)
or self::replace($word, 'ement', '', 1)
or self::replace($word, 'ment', '', 1)
or self::replace($word, 'ent', '', 1);
break;
case 'o':
if (substr($word, -4) == 'tion' or substr($word, -4) == 'sion')
{
self::replace($word, 'ion', '', 1);
}
else
{
self::replace($word, 'ou', '', 1);
}
break;
case 's':
self::replace($word, 'ism', '', 1);
break;
case 't':
self::replace($word, 'ate', '', 1)
or self::replace($word, 'iti', '', 1);
break;
case 'u':
self::replace($word, 'ous', '', 1);
break;
case 'v':
self::replace($word, 'ive', '', 1);
break;
case 'z':
self::replace($word, 'ize', '', 1);
break;
}
return $word;
}
/**
* step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1.
*
* @param string $word The token to stem.
* @return string
*/
private static function step5($word)
{
// Part a
if (substr($word, -1) == 'e')
{
if (self::m(substr($word, 0, -1)) > 1)
{
self::replace($word, 'e', '');
}
elseif (self::m(substr($word, 0, -1)) == 1)
{
if (!self::cvc(substr($word, 0, -1)))
{
self::replace($word, 'e', '');
}
}
}
// Part b
if (self::m($word) > 1 and self::doubleConsonant($word) and substr($word, -1) == 'l')
{
$word = substr($word, 0, -1);
}
return $word;
}
/**
* Replaces the first string with the second, at the end of the string. If
* third arg is given, then the preceding string must match that m count
* at least.
*
* @param string &$str String to check
* @param string $check Ending to check for
* @param string $repl Replacement string
* @param integer $m Optional minimum number of m() to meet
*
* @return boolean Whether the $check string was at the end
* of the $str string. True does not necessarily mean
* that it was replaced.
*/
private static function replace(&$str, $check, $repl, $m = null)
{
$len = 0 - strlen($check);
if (substr($str, $len) == $check) {
$substr = substr($str, 0, $len);
if (is_null($m) or self::m($substr) > $m) {
$str = $substr . $repl;
}
return true;
}
return false;
}
/**
* m() - measures the number of consonant sequences in $str. if c is
* a consonant sequence and v a vowel sequence, and <..> indicates
* arbitrary presence,
*
* <c><v> gives 0
* <c>vc<v> gives 1
* <c>vcvc<v> gives 2
* <c>vcvcvc<v> gives 3
*
* @param string $str The string to return the m count for
* @return integer The m count
*/
private static function m($str)
{
$c = self::$regex_consonant;
$v = self::$regex_vowel;
$str = preg_replace("#^$c+#", '', $str);
$str = preg_replace("#$v+$#", '', $str);
preg_match_all("#($v+$c+)#", $str, $matches);
return count($matches[1]);
}
/**
* Returns true/false as to whether the given string contains two
* of the same consonant next to each other at the end of the string.
*
* @param string $str String to check
* @return boolean Result
*/
private static function doubleConsonant($str)
{
$c = self::$regex_consonant;
return preg_match("#$c{2}$#", $str, $matches) and $matches[0]{0} == $matches[0]{1};
}
/**
* Checks for ending CVC sequence where second C is not W, X or Y
*
* @param string $str String to check
* @return boolean Result
*/
private static function cvc($str)
{
$c = self::$regex_consonant;
$v = self::$regex_vowel;
return preg_match("#($c$v$c)$#", $str, $matches)
&& strlen($matches[1]) == 3
&& $matches[1]{2} != 'w'
&& $matches[1]{2} != 'x'
&& $matches[1]{2} != 'y';
}
}
?>
| glFusion/searcher | classes/stemmer/Porter_en.class.php | PHP | gpl-2.0 | 13,378 |
package ch.logixisland.anuto.view.game;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;
import ch.logixisland.anuto.AnutoApplication;
import ch.logixisland.anuto.GameFactory;
import ch.logixisland.anuto.R;
import ch.logixisland.anuto.business.tower.TowerControl;
import ch.logixisland.anuto.business.tower.TowerInfo;
import ch.logixisland.anuto.business.tower.TowerSelector;
import ch.logixisland.anuto.entity.tower.TowerInfoValue;
import ch.logixisland.anuto.entity.tower.TowerStrategy;
import ch.logixisland.anuto.util.StringUtils;
import ch.logixisland.anuto.view.AnutoFragment;
public class TowerInfoFragment extends AnutoFragment implements View.OnClickListener,
TowerSelector.TowerInfoView {
private final TowerSelector mTowerSelector;
private final TowerControl mTowerControl;
private Handler mHandler;
private TextView txt_level;
private TextView[] txt_property = new TextView[5];
private TextView[] txt_property_text = new TextView[5];
private Button btn_strategy;
private Button btn_lock_target;
private Button btn_enhance;
private Button btn_upgrade;
private Button btn_sell;
private boolean mVisible = true;
public TowerInfoFragment() {
GameFactory factory = AnutoApplication.getInstance().getGameFactory();
mTowerSelector = factory.getTowerSelector();
mTowerControl = factory.getTowerControl();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_tower_info, container, false);
txt_level = (TextView) v.findViewById(R.id.txt_level);
txt_property[0] = (TextView) v.findViewById(R.id.txt_property1);
txt_property[1] = (TextView) v.findViewById(R.id.txt_property2);
txt_property[2] = (TextView) v.findViewById(R.id.txt_property3);
txt_property[3] = (TextView) v.findViewById(R.id.txt_property4);
txt_property[4] = (TextView) v.findViewById(R.id.txt_property5);
TextView txt_level_text = (TextView) v.findViewById(R.id.txt_level_text);
txt_level_text.setText(getResources().getString(R.string.level) + ":");
txt_property_text[0] = (TextView) v.findViewById(R.id.txt_property_text1);
txt_property_text[1] = (TextView) v.findViewById(R.id.txt_property_text2);
txt_property_text[2] = (TextView) v.findViewById(R.id.txt_property_text3);
txt_property_text[3] = (TextView) v.findViewById(R.id.txt_property_text4);
txt_property_text[4] = (TextView) v.findViewById(R.id.txt_property_text5);
btn_strategy = (Button) v.findViewById(R.id.btn_strategy);
btn_lock_target = (Button) v.findViewById(R.id.btn_lock_target);
btn_upgrade = (Button) v.findViewById(R.id.btn_upgrade);
btn_enhance = (Button) v.findViewById(R.id.btn_enhance);
btn_sell = (Button) v.findViewById(R.id.btn_sell);
btn_strategy.setOnClickListener(this);
btn_lock_target.setOnClickListener(this);
btn_enhance.setOnClickListener(this);
btn_upgrade.setOnClickListener(this);
btn_sell.setOnClickListener(this);
mHandler = new Handler();
return v;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TowerInfo towerInfo = mTowerSelector.getTowerInfo();
if (towerInfo != null) {
refresh(towerInfo);
show();
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mTowerSelector.setTowerInfoView(this);
hide();
}
@Override
public void onDetach() {
super.onDetach();
mTowerSelector.setTowerInfoView(null);
mHandler.removeCallbacksAndMessages(null);
}
@Override
public void onClick(View v) {
if (v == btn_strategy) {
mTowerControl.cycleTowerStrategy();
}
if (v == btn_lock_target) {
mTowerControl.toggleLockTarget();
}
if (v == btn_enhance) {
mTowerControl.enhanceTower();
}
if (v == btn_upgrade) {
mTowerControl.upgradeTower();
}
if (v == btn_sell) {
mTowerControl.sellTower();
}
}
@Override
public void showTowerInfo(final TowerInfo towerInfo) {
mHandler.post(new Runnable() {
@Override
public void run() {
show();
refresh(towerInfo);
}
});
}
@Override
public void hideTowerInfo() {
mHandler.post(new Runnable() {
@Override
public void run() {
hide();
}
});
}
private void show() {
if (!mVisible) {
updateMenuTransparency();
getFragmentManager().beginTransaction()
.show(this)
.commitAllowingStateLoss();
mVisible = true;
}
}
private void hide() {
if (mVisible) {
getFragmentManager().beginTransaction()
.hide(this)
.commitAllowingStateLoss();
mVisible = false;
}
}
private void refresh(TowerInfo towerInfo) {
txt_level.setText(towerInfo.getLevel() + " / " + towerInfo.getLevelMax());
List<TowerInfoValue> properties = towerInfo.getProperties();
for (int i = 0; i < properties.size(); i++) {
TowerInfoValue property = properties.get(i);
txt_property_text[i].setText(getString(property.getTextId()) + ":");
txt_property[i].setText(StringUtils.formatSuffix(property.getValue()));
}
for (int i = properties.size(); i < txt_property.length; i++) {
txt_property_text[i].setText("");
txt_property[i].setText("");
}
if (towerInfo.getEnhanceCost() > 0) {
btn_enhance.setText(StringUtils.formatSwitchButton(
getString(R.string.enhance),
StringUtils.formatSuffix(towerInfo.getEnhanceCost()))
);
} else {
btn_enhance.setText(getString(R.string.enhance));
}
if (towerInfo.getUpgradeCost() > 0) {
btn_upgrade.setText(StringUtils.formatSwitchButton(
getString(R.string.upgrade),
StringUtils.formatSuffix(towerInfo.getUpgradeCost()))
);
} else {
btn_upgrade.setText(getString(R.string.upgrade));
}
btn_sell.setText(StringUtils.formatSwitchButton(
getString(R.string.sell),
StringUtils.formatSuffix(towerInfo.getValue()))
);
btn_upgrade.setEnabled(towerInfo.isUpgradeable());
btn_enhance.setEnabled(towerInfo.isEnhanceable());
btn_sell.setEnabled(towerInfo.isSellable());
if (towerInfo.canLockTarget()) {
btn_lock_target.setText(StringUtils.formatSwitchButton(
getString(R.string.lock_target),
StringUtils.formatBoolean(towerInfo.doesLockTarget(), getResources()))
);
btn_lock_target.setEnabled(true);
} else {
btn_lock_target.setText(getString(R.string.lock_target));
btn_lock_target.setEnabled(false);
}
if (towerInfo.hasStrategy()) {
btn_strategy.setText(StringUtils.formatSwitchButton(
getString(R.string.strategy),
getStrategyString(towerInfo.getStrategy()))
);
btn_strategy.setEnabled(true);
} else {
btn_strategy.setText(getString(R.string.strategy));
btn_strategy.setEnabled(false);
}
}
private String getStrategyString(TowerStrategy strategy) {
switch (strategy) {
case Closest:
return getString(R.string.strategy_closest);
case Weakest:
return getString(R.string.strategy_weakest);
case Strongest:
return getString(R.string.strategy_strongest);
case First:
return getString(R.string.strategy_first);
case Last:
return getString(R.string.strategy_last);
}
throw new RuntimeException("Unknown strategy!");
}
}
| oojeiph/android-anuto | app/src/main/java/ch/logixisland/anuto/view/game/TowerInfoFragment.java | Java | gpl-2.0 | 8,699 |
<?php
/**
* Created by PhpStorm.
* User: mglaman
* Date: 9/2/15
* Time: 12:39 AM
*/
namespace mglaman\Docker;
/**
* Class Docker
* @package mglaman\Docker
*/
class Docker extends DockerBase
{
/**
* {@inheritdoc}
*/
public static function command()
{
return 'docker';
}
/**
* @return bool
*/
public static function exists()
{
return self::runCommand('-v')->isSuccessful();
}
/**
* @return bool
* @throws \Exception
*/
public static function available()
{
return self::runCommand('ps')->isSuccessful();
}
/**
* @param $name
* @param $port
* @param string $protocol
*
* @return string
*/
public static function getContainerPort($name, $port, $protocol = 'tcp')
{
// Easier to run this than dig through JSON object.
$cmd = self::runCommand('inspect', [
"--format='{{(index (index .NetworkSettings.Ports \"{$port}/{$protocol}\") 0).HostPort}}",
$name
]);
return preg_replace('/[^0-9,.]+/i', '', $cmd->getOutput());
}
/**
* Run a command in a new container.
*
* @param array $args
* @param null $callback
* @return \Symfony\Component\Process\Process
* @throws \Exception
*/
public static function run(array $args, $callback = null)
{
return self::runCommand('run', $args, $callback);
}
/**
* Start one or more stopped containers.
*
* @param array $args
* @param null $callback
* @return \Symfony\Component\Process\Process
* @throws \Exception
*/
public static function start(array $args, $callback = null)
{
return self::runCommand('start', $args, $callback);
}
/**
* Stop a running container.
*
* @param array $args
* @param null $callback
* @return \Symfony\Component\Process\Process
* @throws \Exception
*/
public static function stop(array $args, $callback = null)
{
return self::runCommand('stop', $args, $callback);
}
/**
* Removes a container.
*
* @param array $args
* @param null $callback
*
* @return \Symfony\Component\Process\Process
* @throws \Exception
*/
public static function rm(array $args, $callback = null)
{
return self::runCommand('rm', $args, $callback);
}
/**
* Pull image or repository from registry.
*
* @param array $args
* @param null $callback
*
* @return \Symfony\Component\Process\Process
* @throws \Exception
*/
public static function pull(array $args, $callback = null)
{
return self::runCommand('pull', $args, $callback);
}
/**
* Return low-level information on a container or image.
*
* @param array $args
* @param bool|false $raw
* @param null $callback
* @return mixed|\Symfony\Component\Process\Process
* @throws \Exception
*/
public static function inspect(array $args, $raw = false, $callback = null)
{
$process = self::runCommand('inspect', $args, $callback);
if ($process->isSuccessful() && !$raw) {
$decoded = json_decode($process->getOutput());
return reset($decoded);
}
return $process;
}
}
| mglaman/docker-helper | src/Docker.php | PHP | gpl-2.0 | 3,379 |
/*
* Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.nodes.cfg;
import com.oracle.graal.compiler.common.LocationIdentity;
import com.oracle.graal.compiler.common.cfg.Loop;
import com.oracle.graal.nodes.LoopBeginNode;
public final class HIRLoop extends Loop<Block> {
private LocationSet killLocations;
protected HIRLoop(Loop<Block> parent, int index, Block header) {
super(parent, index, header);
}
@Override
public long numBackedges() {
return ((LoopBeginNode) getHeader().getBeginNode()).loopEnds().count();
}
public LocationSet getKillLocations() {
if (killLocations == null) {
killLocations = new LocationSet();
for (Block b : this.getBlocks()) {
if (b.getLoop() == this) {
killLocations.addAll(b.getKillLocations());
if (killLocations.isAny()) {
break;
}
}
}
}
for (Loop<Block> child : this.getChildren()) {
if (killLocations.isAny()) {
break;
}
killLocations.addAll(((HIRLoop) child).getKillLocations());
}
return killLocations;
}
public boolean canKill(LocationIdentity location) {
return getKillLocations().contains(location);
}
}
| zapster/graal-core | graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/cfg/HIRLoop.java | Java | gpl-2.0 | 2,382 |
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qpainter.h"
#include "qevent.h"
#include "qdrawutil.h"
#include "qapplication.h"
#include "qabstractbutton.h"
#include "qstyle.h"
#include "qstyleoption.h"
#include <limits.h>
#include "qaction.h"
#include "qclipboard.h"
#include <qdebug.h>
#include <qurl.h>
#include "qlabel_p.h"
#include "private/qstylesheetstyle_p.h"
QT_BEGIN_NAMESPACE
/*!
\class QLabel
\brief The QLabel widget provides a text or image display.
\ingroup basicwidgets
\ingroup text
\mainclass
QLabel is used for displaying text or an image. No user
interaction functionality is provided. The visual appearance of
the label can be configured in various ways, and it can be used
for specifying a focus mnemonic key for another widget.
A QLabel can contain any of the following content types:
\table
\header \o Content \o Setting
\row \o Plain text
\o Pass a QString to setText().
\row \o Rich text
\o Pass a QString that contains rich text to setText().
\row \o A pixmap
\o Pass a QPixmap to setPixmap().
\row \o A movie
\o Pass a QMovie to setMovie().
\row \o A number
\o Pass an \e int or a \e double to setNum(), which converts
the number to plain text.
\row \o Nothing
\o The same as an empty plain text. This is the default. Set
by clear().
\endtable
When the content is changed using any of these functions, any
previous content is cleared.
By default, labels display \l{alignment}{left-aligned, vertically-centered}
text and images, where any tabs in the text to be displayed are
\l{Qt::TextExpandTabs}{automatically expanded}. However, the look
of a QLabel can be adjusted and fine-tuned in several ways.
The positioning of the content within the QLabel widget area can
be tuned with setAlignment() and setIndent(). Text content can
also wrap lines along word boundaries with setWordWrap(). For
example, this code sets up a sunken panel with a two-line text in
the bottom right corner (both lines being flush with the right
side of the label):
\snippet doc/src/snippets/code/src_gui_widgets_qlabel.cpp 0
The properties and functions QLabel inherits from QFrame can also
be used to specify the widget frame to be used for any given label.
A QLabel is often used as a label for an interactive widget. For
this use QLabel provides a useful mechanism for adding an
mnemonic (see QKeySequence) that will set the keyboard focus to
the other widget (called the QLabel's "buddy"). For example:
\snippet doc/src/snippets/code/src_gui_widgets_qlabel.cpp 1
In this example, keyboard focus is transferred to the label's
buddy (the QLineEdit) when the user presses Alt+P. If the buddy
was a button (inheriting from QAbstractButton), triggering the
mnemonic would emulate a button click.
\table 100%
\row
\o \inlineimage macintosh-label.png Screenshot of a Macintosh style label
\o A label shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}.
\row
\o \inlineimage plastique-label.png Screenshot of a Plastique style label
\o A label shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}.
\row
\o \inlineimage windowsxp-label.png Screenshot of a Windows XP style label
\o A label shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}.
\endtable
\sa QLineEdit, QTextEdit, QPixmap, QMovie,
{fowler}{GUI Design Handbook: Label}
*/
#ifndef QT_NO_PICTURE
/*!
Returns the label's picture or 0 if the label doesn't have a
picture.
*/
const QPicture *QLabel::picture() const
{
Q_D(const QLabel);
return d->picture;
}
#endif
/*!
Constructs an empty label.
The \a parent and widget flag \a f, arguments are passed
to the QFrame constructor.
\sa setAlignment(), setFrameStyle(), setIndent()
*/
QLabel::QLabel(QWidget *parent, Qt::WindowFlags f)
: QFrame(*new QLabelPrivate(), parent, f)
{
Q_D(QLabel);
d->init();
}
/*!
Constructs a label that displays the text, \a text.
The \a parent and widget flag \a f, arguments are passed
to the QFrame constructor.
\sa setText(), setAlignment(), setFrameStyle(), setIndent()
*/
QLabel::QLabel(const QString &text, QWidget *parent, Qt::WindowFlags f)
: QFrame(*new QLabelPrivate(), parent, f)
{
Q_D(QLabel);
d->init();
setText(text);
}
#ifdef QT3_SUPPORT
/*! \obsolete
Constructs an empty label.
The \a parent, \a name and widget flag \a f, arguments are passed
to the QFrame constructor.
\sa setAlignment(), setFrameStyle(), setIndent()
*/
QLabel::QLabel(QWidget *parent, const char *name, Qt::WindowFlags f)
: QFrame(*new QLabelPrivate(), parent, f)
{
Q_D(QLabel);
if (name)
setObjectName(QString::fromAscii(name));
d->init();
}
/*! \obsolete
Constructs a label that displays the text, \a text.
The \a parent, \a name and widget flag \a f, arguments are passed
to the QFrame constructor.
\sa setText(), setAlignment(), setFrameStyle(), setIndent()
*/
QLabel::QLabel(const QString &text, QWidget *parent, const char *name,
Qt::WindowFlags f)
: QFrame(*new QLabelPrivate(), parent, f)
{
Q_D(QLabel);
if (name)
setObjectName(QString::fromAscii(name));
d->init();
setText(text);
}
/*! \obsolete
Constructs a label that displays the text \a text. The label has a
buddy widget, \a buddy.
If the \a text contains an underlined letter (a letter preceded by
an ampersand, \&), when the user presses Alt+ the underlined letter,
focus is passed to the buddy widget.
The \a parent, \a name and widget flag, \a f, arguments are passed
to the QFrame constructor.
\sa setText(), setBuddy(), setAlignment(), setFrameStyle(),
setIndent()
*/
QLabel::QLabel(QWidget *buddy, const QString &text,
QWidget *parent, const char *name, Qt::WindowFlags f)
: QFrame(*new QLabelPrivate(), parent, f)
{
Q_D(QLabel);
if (name)
setObjectName(QString::fromAscii(name));
d->init();
#ifndef QT_NO_SHORTCUT
setBuddy(buddy);
#endif
setText(text);
}
#endif //QT3_SUPPORT
/*!
Destroys the label.
*/
QLabel::~QLabel()
{
Q_D(QLabel);
d->clearContents();
}
void QLabelPrivate::init()
{
Q_Q(QLabel);
valid_hints = false;
margin = 0;
#ifndef QT_NO_MOVIE
movie = 0;
#endif
#ifndef QT_NO_SHORTCUT
shortcutId = 0;
#endif
pixmap = 0;
scaledpixmap = 0;
cachedimage = 0;
#ifndef QT_NO_PICTURE
picture = 0;
#endif
align = Qt::AlignLeft | Qt::AlignVCenter | Qt::TextExpandTabs;
indent = -1;
scaledcontents = false;
textLayoutDirty = false;
textDirty = false;
textformat = Qt::AutoText;
control = 0;
textInteractionFlags = Qt::LinksAccessibleByMouse;
isRichText = false;
isTextLabel = false;
q->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred,
QSizePolicy::Label));
#ifndef QT_NO_CURSOR
validCursor = false;
onAnchor = false;
#endif
openExternalLinks = false;
setLayoutItemMargins(QStyle::SE_LabelLayoutItem);
}
/*!
\property QLabel::text
\brief the label's text
If no text has been set this will return an empty string. Setting
the text clears any previous content.
The text will be interpreted either as plain text or as rich
text, depending on the text format setting; see setTextFormat().
The default setting is Qt::AutoText; i.e. QLabel will try to
auto-detect the format of the text set.
If a buddy has been set, the buddy mnemonic key is updated
from the new text.
Note that QLabel is well-suited to display small rich text
documents, such as small documents that get their document
specific settings (font, text color, link color) from the label's
palette and font properties. For large documents, use QTextEdit
in read-only mode instead. QTextEdit can also provide a scroll bar
when necessary.
\note This function enables mouse tracking if \a text contains rich
text.
\sa setTextFormat(), setBuddy(), alignment
*/
void QLabel::setText(const QString &text)
{
Q_D(QLabel);
if (d->text == text)
return;
QTextControl *oldControl = d->control;
d->control = 0;
d->clearContents();
d->text = text;
d->isTextLabel = true;
d->textDirty = true;
d->isRichText = d->textformat == Qt::RichText
|| (d->textformat == Qt::AutoText && Qt::mightBeRichText(d->text));
d->control = oldControl;
if (d->needTextControl()) {
d->ensureTextControl();
} else {
delete d->control;
d->control = 0;
}
if (d->isRichText) {
setMouseTracking(true);
} else {
// Note: mouse tracking not disabled intentionally
}
#ifndef QT_NO_SHORTCUT
if (d->buddy)
d->updateShortcut();
#endif
d->updateLabel();
}
QString QLabel::text() const
{
Q_D(const QLabel);
return d->text;
}
/*!
Clears any label contents.
*/
void QLabel::clear()
{
Q_D(QLabel);
d->clearContents();
d->updateLabel();
}
/*!
\property QLabel::pixmap
\brief the label's pixmap
If no pixmap has been set this will return 0.
Setting the pixmap clears any previous content. The buddy
shortcut, if any, is disabled.
*/
void QLabel::setPixmap(const QPixmap &pixmap)
{
Q_D(QLabel);
if (!d->pixmap || d->pixmap->cacheKey() != pixmap.cacheKey()) {
d->clearContents();
d->pixmap = new QPixmap(pixmap);
}
if (d->pixmap->depth() == 1 && !d->pixmap->mask())
d->pixmap->setMask(*((QBitmap *)d->pixmap));
d->updateLabel();
}
const QPixmap *QLabel::pixmap() const
{
Q_D(const QLabel);
return d->pixmap;
}
#ifndef QT_NO_PICTURE
/*!
Sets the label contents to \a picture. Any previous content is
cleared.
The buddy shortcut, if any, is disabled.
\sa picture(), setBuddy()
*/
void QLabel::setPicture(const QPicture &picture)
{
Q_D(QLabel);
d->clearContents();
d->picture = new QPicture(picture);
d->updateLabel();
}
#endif // QT_NO_PICTURE
/*!
Sets the label contents to plain text containing the textual
representation of integer \a num. Any previous content is cleared.
Does nothing if the integer's string representation is the same as
the current contents of the label.
The buddy shortcut, if any, is disabled.
\sa setText(), QString::setNum(), setBuddy()
*/
void QLabel::setNum(int num)
{
QString str;
str.setNum(num);
setText(str);
}
/*!
\overload
Sets the label contents to plain text containing the textual
representation of double \a num. Any previous content is cleared.
Does nothing if the double's string representation is the same as
the current contents of the label.
The buddy shortcut, if any, is disabled.
\sa setText(), QString::setNum(), setBuddy()
*/
void QLabel::setNum(double num)
{
QString str;
str.setNum(num);
setText(str);
}
/*!
\property QLabel::alignment
\brief the alignment of the label's contents
By default, the contents of the label are left-aligned and vertically-centered.
\sa text
*/
void QLabel::setAlignment(Qt::Alignment alignment)
{
Q_D(QLabel);
if (alignment == (d->align & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask)))
return;
d->align = (d->align & ~(Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask))
| (alignment & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask));
d->updateLabel();
}
#ifdef QT3_SUPPORT
/*!
Use setAlignment(Qt::Alignment) instead.
If \a alignment specifies text flags as well, use setTextFormat()
to set those.
*/
void QLabel::setAlignment(int alignment)
{
Q_D(QLabel);
d->align = alignment & ~(Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask|Qt::TextWordWrap);
setAlignment(Qt::Alignment(QFlag(alignment)));
}
#endif
Qt::Alignment QLabel::alignment() const
{
Q_D(const QLabel);
return QFlag(d->align & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask));
}
/*!
\property QLabel::wordWrap
\brief the label's word-wrapping policy
If this property is true then label text is wrapped where
necessary at word-breaks; otherwise it is not wrapped at all.
By default, word wrap is disabled.
\sa text
*/
void QLabel::setWordWrap(bool on)
{
Q_D(QLabel);
if (on)
d->align |= Qt::TextWordWrap;
else
d->align &= ~Qt::TextWordWrap;
d->updateLabel();
}
bool QLabel::wordWrap() const
{
Q_D(const QLabel);
return d->align & Qt::TextWordWrap;
}
/*!
\property QLabel::indent
\brief the label's text indent in pixels
If a label displays text, the indent applies to the left edge if
alignment() is Qt::AlignLeft, to the right edge if alignment() is
Qt::AlignRight, to the top edge if alignment() is Qt::AlignTop, and
to to the bottom edge if alignment() is Qt::AlignBottom.
If indent is negative, or if no indent has been set, the label
computes the effective indent as follows: If frameWidth() is 0,
the effective indent becomes 0. If frameWidth() is greater than 0,
the effective indent becomes half the width of the "x" character
of the widget's current font().
By default, the indent is -1, meaning that an effective indent is
calculating in the manner described above.
\sa alignment, margin, frameWidth(), font()
*/
void QLabel::setIndent(int indent)
{
Q_D(QLabel);
d->indent = indent;
d->updateLabel();
}
int QLabel::indent() const
{
Q_D(const QLabel);
return d->indent;
}
/*!
\property QLabel::margin
\brief the width of the margin
The margin is the distance between the innermost pixel of the
frame and the outermost pixel of contents.
The default margin is 0.
\sa indent
*/
int QLabel::margin() const
{
Q_D(const QLabel);
return d->margin;
}
void QLabel::setMargin(int margin)
{
Q_D(QLabel);
if (d->margin == margin)
return;
d->margin = margin;
d->updateLabel();
}
/*!
Returns the size that will be used if the width of the label is \a
w. If \a w is -1, the sizeHint() is returned. If \a w is 0 minimumSizeHint() is returned
*/
QSize QLabelPrivate::sizeForWidth(int w) const
{
Q_Q(const QLabel);
if(q->minimumWidth() > 0)
w = qMax(w, q->minimumWidth());
QSize contentsMargin(leftmargin + rightmargin, topmargin + bottommargin);
QRect br;
int hextra = 2 * margin;
int vextra = hextra;
QFontMetrics fm = q->fontMetrics();
if (pixmap && !pixmap->isNull())
br = pixmap->rect();
#ifndef QT_NO_PICTURE
else if (picture && !picture->isNull())
br = picture->boundingRect();
#endif
#ifndef QT_NO_MOVIE
else if (movie && !movie->currentPixmap().isNull())
br = movie->currentPixmap().rect();
#endif
else if (isTextLabel) {
int align = QStyle::visualAlignment(q->layoutDirection(), QFlag(this->align));
// Add indentation
int m = indent;
if (m < 0 && q->frameWidth()) // no indent, but we do have a frame
m = fm.width(QLatin1Char('x')) - margin*2;
if (m > 0) {
if ((align & Qt::AlignLeft) || (align & Qt::AlignRight))
hextra += m;
if ((align & Qt::AlignTop) || (align & Qt::AlignBottom))
vextra += m;
}
if (control) {
ensureTextLayouted();
const qreal oldTextWidth = control->textWidth();
// Calculate the length of document if w is the width
if (align & Qt::TextWordWrap) {
if (w >= 0) {
w = qMax(w-hextra-contentsMargin.width(), 0); // strip margin and indent
control->setTextWidth(w);
} else {
control->adjustSize();
}
} else {
control->setTextWidth(-1);
}
br = QRect(QPoint(0, 0), control->size().toSize());
// restore state
control->setTextWidth(oldTextWidth);
} else {
// Turn off center alignment in order to avoid rounding errors for centering,
// since centering involves a division by 2. At the end, all we want is the size.
int flags = align & ~(Qt::AlignVCenter | Qt::AlignHCenter);
if (hasShortcut) {
flags |= Qt::TextShowMnemonic;
QStyleOption opt;
opt.initFrom(q);
if (!q->style()->styleHint(QStyle::SH_UnderlineShortcut, &opt, q))
flags |= Qt::TextHideMnemonic;
}
bool tryWidth = (w < 0) && (align & Qt::TextWordWrap);
if (tryWidth)
w = fm.averageCharWidth() * 80;
else if (w < 0)
w = 2000;
w -= (hextra + contentsMargin.width());
br = fm.boundingRect(0, 0, w ,2000, flags, text);
if (tryWidth && br.height() < 4*fm.lineSpacing() && br.width() > w/2)
br = fm.boundingRect(0, 0, w/2, 2000, flags, text);
if (tryWidth && br.height() < 2*fm.lineSpacing() && br.width() > w/4)
br = fm.boundingRect(0, 0, w/4, 2000, flags, text);
}
} else {
br = QRect(QPoint(0, 0), QSize(fm.averageCharWidth(), fm.lineSpacing()));
}
const QSize contentsSize(br.width() + hextra, br.height() + vextra);
return (contentsSize + contentsMargin).expandedTo(q->minimumSize());
}
/*!
\reimp
*/
int QLabel::heightForWidth(int w) const
{
Q_D(const QLabel);
if (d->isTextLabel)
return d->sizeForWidth(w).height();
return QWidget::heightForWidth(w);
}
/*!
\property QLabel::openExternalLinks
\since 4.2
Specifies whether QLabel should automatically open links using
QDesktopServices::openUrl() instead of emitting the
linkActivated() signal.
\bold{Note:} The textInteractionFlags set on the label need to include
either LinksAccessibleByMouse or LinksAccessibleByKeyboard.
The default value is false.
\sa textInteractionFlags()
*/
bool QLabel::openExternalLinks() const
{
Q_D(const QLabel);
return d->openExternalLinks;
}
void QLabel::setOpenExternalLinks(bool open)
{
Q_D(QLabel);
d->openExternalLinks = open;
if (d->control)
d->control->setOpenExternalLinks(open);
}
/*!
\property QLabel::textInteractionFlags
\since 4.2
Specifies how the label should interact with user input if it displays text.
If the flags contain Qt::LinksAccessibleByKeyboard the focus policy is also
automatically set to Qt::StrongFocus. If Qt::TextSelectableByKeyboard is set
then the focus policy is set to Qt::ClickFocus.
The default value is Qt::LinksAccessibleByMouse.
*/
void QLabel::setTextInteractionFlags(Qt::TextInteractionFlags flags)
{
Q_D(QLabel);
if (d->textInteractionFlags == flags)
return;
d->textInteractionFlags = flags;
if (flags & Qt::LinksAccessibleByKeyboard)
setFocusPolicy(Qt::StrongFocus);
else if (flags & (Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse))
setFocusPolicy(Qt::ClickFocus);
else
setFocusPolicy(Qt::NoFocus);
if (d->needTextControl()) {
d->ensureTextControl();
} else {
delete d->control;
d->control = 0;
}
if (d->control)
d->control->setTextInteractionFlags(d->textInteractionFlags);
}
Qt::TextInteractionFlags QLabel::textInteractionFlags() const
{
Q_D(const QLabel);
return d->textInteractionFlags;
}
/*!\reimp
*/
QSize QLabel::sizeHint() const
{
Q_D(const QLabel);
if (!d->valid_hints)
(void) QLabel::minimumSizeHint();
return d->sh;
}
/*!
\reimp
*/
QSize QLabel::minimumSizeHint() const
{
Q_D(const QLabel);
if (d->valid_hints) {
if (d->sizePolicy == sizePolicy())
return d->msh;
}
ensurePolished();
d->valid_hints = true;
d->sh = d->sizeForWidth(-1); // wrap ? golden ratio : min doc size
QSize msh(-1, -1);
if (!d->isTextLabel) {
msh = d->sh;
} else {
msh.rheight() = d->sizeForWidth(QWIDGETSIZE_MAX).height(); // height for one line
msh.rwidth() = d->sizeForWidth(0).width(); // wrap ? size of biggest word : min doc size
if (d->sh.height() < msh.height())
msh.rheight() = d->sh.height();
}
d->msh = msh;
d->sizePolicy = sizePolicy();
return msh;
}
/*!\reimp
*/
void QLabel::mousePressEvent(QMouseEvent *ev)
{
Q_D(QLabel);
d->sendControlEvent(ev);
}
/*!\reimp
*/
void QLabel::mouseMoveEvent(QMouseEvent *ev)
{
Q_D(QLabel);
d->sendControlEvent(ev);
}
/*!\reimp
*/
void QLabel::mouseReleaseEvent(QMouseEvent *ev)
{
Q_D(QLabel);
d->sendControlEvent(ev);
}
/*!\reimp
*/
void QLabel::contextMenuEvent(QContextMenuEvent *ev)
{
#ifdef QT_NO_CONTEXTMENU
Q_UNUSED(ev);
#else
Q_D(QLabel);
if (!d->isTextLabel) {
ev->ignore();
return;
}
QMenu *menu = d->createStandardContextMenu(ev->pos());
if (!menu) {
ev->ignore();
return;
}
ev->accept();
menu->exec(ev->globalPos());
delete menu;
#endif
}
/*!
\reimp
*/
void QLabel::focusInEvent(QFocusEvent *ev)
{
Q_D(QLabel);
if (d->isTextLabel) {
d->ensureTextControl();
d->sendControlEvent(ev);
}
QFrame::focusInEvent(ev);
}
/*!
\reimp
*/
void QLabel::focusOutEvent(QFocusEvent *ev)
{
Q_D(QLabel);
d->sendControlEvent(ev);
QFrame::focusOutEvent(ev);
}
/*!\reimp
*/
bool QLabel::focusNextPrevChild(bool next)
{
Q_D(QLabel);
if (d->control && d->control->setFocusToNextOrPreviousAnchor(next))
return true;
return QFrame::focusNextPrevChild(next);
}
/*!\reimp
*/
void QLabel::keyPressEvent(QKeyEvent *ev)
{
Q_D(QLabel);
d->sendControlEvent(ev);
}
/*!\reimp
*/
bool QLabel::event(QEvent *e)
{
Q_D(QLabel);
QEvent::Type type = e->type();
#ifndef QT_NO_SHORTCUT
if (type == QEvent::Shortcut) {
QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
if (se->shortcutId() == d->shortcutId) {
QWidget * w = d->buddy;
QAbstractButton *button = qobject_cast<QAbstractButton *>(w);
if (w->focusPolicy() != Qt::NoFocus)
w->setFocus(Qt::ShortcutFocusReason);
if (button && !se->isAmbiguous())
button->animateClick();
else
window()->setAttribute(Qt::WA_KeyboardFocusChange);
return true;
}
} else
#endif
if (type == QEvent::Resize) {
if (d->control)
d->textLayoutDirty = true;
} else if (e->type() == QEvent::StyleChange
#ifdef Q_WS_MAC
|| e->type() == QEvent::MacSizeChange
#endif
) {
d->setLayoutItemMargins(QStyle::SE_LabelLayoutItem);
d->updateLabel();
}
return QFrame::event(e);
}
/*!\reimp
*/
void QLabel::paintEvent(QPaintEvent *)
{
Q_D(QLabel);
QStyle *style = QWidget::style();
QPainter painter(this);
drawFrame(&painter);
QRect cr = contentsRect();
cr.adjust(d->margin, d->margin, -d->margin, -d->margin);
int align = QStyle::visualAlignment(layoutDirection(), QFlag(d->align));
#ifndef QT_NO_MOVIE
if (d->movie) {
if (d->scaledcontents)
style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap().scaled(cr.size()));
else
style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap());
}
else
#endif
if (d->isTextLabel) {
QRectF lr = d->layoutRect();
if (d->control) {
#ifndef QT_NO_SHORTCUT
const bool underline = (bool)style->styleHint(QStyle::SH_UnderlineShortcut, 0, this, 0);
if (d->shortcutId != 0
&& underline != d->shortcutCursor.charFormat().fontUnderline()) {
QTextCharFormat fmt;
fmt.setFontUnderline(underline);
d->shortcutCursor.mergeCharFormat(fmt);
}
#endif
d->ensureTextLayouted();
QAbstractTextDocumentLayout::PaintContext context;
QStyleOption opt(0);
opt.init(this);
if (!isEnabled() && style->styleHint(QStyle::SH_EtchDisabledText, &opt, this)) {
context.palette = palette();
context.palette.setColor(QPalette::Text, context.palette.light().color());
painter.save();
painter.translate(lr.x() + 1, lr.y() + 1);
painter.setClipRect(lr.translated(-lr.x() - 1, -lr.y() - 1));
QAbstractTextDocumentLayout *layout = d->control->document()->documentLayout();
layout->draw(&painter, context);
painter.restore();
}
// Adjust the palette
context.palette = palette();
#ifndef QT_NO_STYLE_STYLESHEET
if (QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(style)) {
cssStyle->focusPalette(this, &opt, &context.palette);
}
#endif
if (foregroundRole() != QPalette::Text && isEnabled())
context.palette.setColor(QPalette::Text, context.palette.color(foregroundRole()));
painter.save();
painter.translate(lr.topLeft());
painter.setClipRect(lr.translated(-lr.x(), -lr.y()));
d->control->setPalette(context.palette);
d->control->drawContents(&painter, QRectF(), this);
painter.restore();
} else {
int flags = align;
if (d->hasShortcut) {
flags |= Qt::TextShowMnemonic;
QStyleOption opt;
opt.initFrom(this);
if (!style->styleHint(QStyle::SH_UnderlineShortcut, &opt, this))
flags |= Qt::TextHideMnemonic;
}
style->drawItemText(&painter, lr.toRect(), flags, palette(), isEnabled(), d->text, foregroundRole());
}
} else
#ifndef QT_NO_PICTURE
if (d->picture) {
QRect br = d->picture->boundingRect();
int rw = br.width();
int rh = br.height();
if (d->scaledcontents) {
painter.save();
painter.translate(cr.x(), cr.y());
painter.scale((double)cr.width()/rw, (double)cr.height()/rh);
painter.drawPicture(-br.x(), -br.y(), *d->picture);
painter.restore();
} else {
int xo = 0;
int yo = 0;
if (align & Qt::AlignVCenter)
yo = (cr.height()-rh)/2;
else if (align & Qt::AlignBottom)
yo = cr.height()-rh;
if (align & Qt::AlignRight)
xo = cr.width()-rw;
else if (align & Qt::AlignHCenter)
xo = (cr.width()-rw)/2;
painter.drawPicture(cr.x()+xo-br.x(), cr.y()+yo-br.y(), *d->picture);
}
} else
#endif
if (d->pixmap && !d->pixmap->isNull()) {
QPixmap pix;
if (d->scaledcontents) {
if (!d->scaledpixmap || d->scaledpixmap->size() != cr.size()) {
if (!d->cachedimage)
d->cachedimage = new QImage(d->pixmap->toImage());
delete d->scaledpixmap;
d->scaledpixmap = new QPixmap(QPixmap::fromImage(d->cachedimage->scaled(cr.size(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation)));
}
pix = *d->scaledpixmap;
} else
pix = *d->pixmap;
QStyleOption opt;
opt.initFrom(this);
if (!isEnabled())
pix = style->generatedIconPixmap(QIcon::Disabled, pix, &opt);
style->drawItemPixmap(&painter, cr, align, pix);
}
}
/*!
Updates the label, but not the frame.
*/
void QLabelPrivate::updateLabel()
{
Q_Q(QLabel);
valid_hints = false;
if (isTextLabel) {
QSizePolicy policy = q->sizePolicy();
const bool wrap = align & Qt::TextWordWrap;
policy.setHeightForWidth(wrap);
if (policy != q->sizePolicy()) // ### should be replaced by WA_WState_OwnSizePolicy idiom
q->setSizePolicy(policy);
textLayoutDirty = true;
}
q->updateGeometry();
q->update(q->contentsRect());
}
#ifndef QT_NO_SHORTCUT
/*!
Sets this label's buddy to \a buddy.
When the user presses the shortcut key indicated by this label,
the keyboard focus is transferred to the label's buddy widget.
The buddy mechanism is only available for QLabels that contain
text in which one character is prefixed with an ampersand, '&'.
This character is set as the shortcut key. See the \l
QKeySequence::mnemonic() documentation for details (to display an
actual ampersand, use '&&').
In a dialog, you might create two data entry widgets and a label
for each, and set up the geometry layout so each label is just to
the left of its data entry widget (its "buddy"), for example:
\snippet doc/src/snippets/code/src_gui_widgets_qlabel.cpp 2
With the code above, the focus jumps to the Name field when the
user presses Alt+N, and to the Phone field when the user presses
Alt+P.
To unset a previously set buddy, call this function with \a buddy
set to 0.
\sa buddy(), setText(), QShortcut, setAlignment()
*/
void QLabel::setBuddy(QWidget *buddy)
{
Q_D(QLabel);
d->buddy = buddy;
if (d->isTextLabel) {
if (d->shortcutId)
releaseShortcut(d->shortcutId);
d->shortcutId = 0;
d->textDirty = true;
if (buddy)
d->updateShortcut(); // grab new shortcut
d->updateLabel();
}
}
/*!
Returns this label's buddy, or 0 if no buddy is currently set.
\sa setBuddy()
*/
QWidget * QLabel::buddy() const
{
Q_D(const QLabel);
return d->buddy;
}
void QLabelPrivate::updateShortcut()
{
Q_Q(QLabel);
Q_ASSERT(shortcutId == 0);
// Introduce an extra boolean to indicate the presence of a shortcut in the
// text. We cannot use the shortcutId itself because on the mac mnemonics are
// off by default, so QKeySequence::mnemonic always returns an empty sequence.
// But then we do want to hide the ampersands, so we can't use shortcutId.
hasShortcut = false;
if (control) {
ensureTextPopulated();
// Underline the first character that follows an ampersand
shortcutCursor = control->document()->find(QLatin1String("&"));
if (shortcutCursor.isNull())
return;
hasShortcut = true;
shortcutId = q->grabShortcut(QKeySequence::mnemonic(text));
shortcutCursor.deleteChar(); // remove the ampersand
shortcutCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
} else {
if (!text.contains(QLatin1String("&")))
return;
hasShortcut = true;
shortcutId = q->grabShortcut(QKeySequence::mnemonic(text));
}
}
#endif // QT_NO_SHORTCUT
#ifndef QT_NO_MOVIE
void QLabelPrivate::_q_movieUpdated(const QRect& rect)
{
Q_Q(QLabel);
if (movie && movie->isValid()) {
QRect r;
if (scaledcontents) {
QRect cr = q->contentsRect();
QRect pixmapRect(cr.topLeft(), movie->currentPixmap().size());
if (pixmapRect.isEmpty())
return;
r.setRect(cr.left(), cr.top(),
(rect.width() * cr.width()) / pixmapRect.width(),
(rect.height() * cr.height()) / pixmapRect.height());
} else {
r = q->style()->itemPixmapRect(q->contentsRect(), align, movie->currentPixmap());
r.translate(rect.x(), rect.y());
r.setWidth(qMin(r.width(), rect.width()));
r.setHeight(qMin(r.height(), rect.height()));
}
q->update(r);
}
}
void QLabelPrivate::_q_movieResized(const QSize& size)
{
Q_Q(QLabel);
q->update(); //we need to refresh the whole background in case the new size is smaler
valid_hints = false;
_q_movieUpdated(QRect(QPoint(0,0), size));
q->updateGeometry();
}
/*!
Sets the label contents to \a movie. Any previous content is
cleared. The label does NOT take ownership of the movie.
The buddy shortcut, if any, is disabled.
\sa movie(), setBuddy()
*/
void QLabel::setMovie(QMovie *movie)
{
Q_D(QLabel);
d->clearContents();
if (!movie)
return;
d->movie = movie;
connect(movie, SIGNAL(resized(QSize)), this, SLOT(_q_movieResized(QSize)));
connect(movie, SIGNAL(updated(QRect)), this, SLOT(_q_movieUpdated(QRect)));
// Assume that if the movie is running,
// resize/update signals will come soon enough
if (movie->state() != QMovie::Running)
d->updateLabel();
}
#endif // QT_NO_MOVIE
/*!
\internal
Clears any contents, without updating/repainting the label.
*/
void QLabelPrivate::clearContents()
{
delete control;
control = 0;
isTextLabel = false;
hasShortcut = false;
#ifndef QT_NO_PICTURE
delete picture;
picture = 0;
#endif
delete scaledpixmap;
scaledpixmap = 0;
delete cachedimage;
cachedimage = 0;
delete pixmap;
pixmap = 0;
text.clear();
Q_Q(QLabel);
#ifndef QT_NO_SHORTCUT
if (shortcutId)
q->releaseShortcut(shortcutId);
shortcutId = 0;
#endif
#ifndef QT_NO_MOVIE
if (movie) {
QObject::disconnect(movie, SIGNAL(resized(QSize)), q, SLOT(_q_movieResized(QSize)));
QObject::disconnect(movie, SIGNAL(updated(QRect)), q, SLOT(_q_movieUpdated(QRect)));
}
movie = 0;
#endif
#ifndef QT_NO_CURSOR
if (onAnchor) {
if (validCursor)
q->setCursor(cursor);
else
q->unsetCursor();
}
validCursor = false;
onAnchor = false;
#endif
}
#ifndef QT_NO_MOVIE
/*!
Returns a pointer to the label's movie, or 0 if no movie has been
set.
\sa setMovie()
*/
QMovie *QLabel::movie() const
{
Q_D(const QLabel);
return d->movie;
}
#endif // QT_NO_MOVIE
/*!
\property QLabel::textFormat
\brief the label's text format
See the Qt::TextFormat enum for an explanation of the possible
options.
The default format is Qt::AutoText.
\sa text()
*/
Qt::TextFormat QLabel::textFormat() const
{
Q_D(const QLabel);
return d->textformat;
}
void QLabel::setTextFormat(Qt::TextFormat format)
{
Q_D(QLabel);
if (format != d->textformat) {
d->textformat = format;
QString t = d->text;
if (!t.isNull()) {
d->text.clear();
setText(t);
}
}
}
/*!
\reimp
*/
void QLabel::changeEvent(QEvent *ev)
{
Q_D(QLabel);
if(ev->type() == QEvent::FontChange || ev->type() == QEvent::ApplicationFontChange) {
if (d->isTextLabel) {
if (d->control)
d->control->document()->setDefaultFont(font());
d->updateLabel();
}
} else if (ev->type() == QEvent::PaletteChange && d->control) {
d->control->setPalette(palette());
} else if (ev->type() == QEvent::ContentsRectChange) {
d->updateLabel();
} else if (ev->type() == QEvent::LayoutDirectionChange) {
if (d->isTextLabel && d->control) {
d->sendControlEvent(ev);
}
}
QFrame::changeEvent(ev);
}
/*!
\property QLabel::scaledContents
\brief whether the label will scale its contents to fill all
available space.
When enabled and the label shows a pixmap, it will scale the
pixmap to fill the available space.
This property's default is false.
*/
bool QLabel::hasScaledContents() const
{
Q_D(const QLabel);
return d->scaledcontents;
}
void QLabel::setScaledContents(bool enable)
{
Q_D(QLabel);
if ((bool)d->scaledcontents == enable)
return;
d->scaledcontents = enable;
if (!enable) {
delete d->scaledpixmap;
d->scaledpixmap = 0;
delete d->cachedimage;
d->cachedimage = 0;
}
update(contentsRect());
}
/*!
\fn void QLabel::setAlignment(Qt::AlignmentFlag flag)
\internal
Without this function, a call to e.g. setAlignment(Qt::AlignTop)
results in the \c QT3_SUPPORT function setAlignment(int) being called,
rather than setAlignment(Qt::Alignment).
*/
// Returns the rect that is available for us to draw the document
QRect QLabelPrivate::documentRect() const
{
Q_Q(const QLabel);
Q_ASSERT_X(isTextLabel, "documentRect", "document rect called for label that is not a text label!");
QRect cr = q->contentsRect();
cr.adjust(margin, margin, -margin, -margin);
const int align = QStyle::visualAlignment(q->layoutDirection(), QFlag(this->align));
int m = indent;
if (m < 0 && q->frameWidth()) // no indent, but we do have a frame
m = q->fontMetrics().width(QLatin1Char('x')) / 2 - margin;
if (m > 0) {
if (align & Qt::AlignLeft)
cr.setLeft(cr.left() + m);
if (align & Qt::AlignRight)
cr.setRight(cr.right() - m);
if (align & Qt::AlignTop)
cr.setTop(cr.top() + m);
if (align & Qt::AlignBottom)
cr.setBottom(cr.bottom() - m);
}
return cr;
}
void QLabelPrivate::ensureTextPopulated() const
{
if (!textDirty)
return;
if (control) {
QTextDocument *doc = control->document();
if (textDirty) {
#ifndef QT_NO_TEXTHTMLPARSER
if (isRichText)
doc->setHtml(text);
else
doc->setPlainText(text);
#else
doc->setPlainText(text);
#endif
doc->setUndoRedoEnabled(false);
}
}
textDirty = false;
}
void QLabelPrivate::ensureTextLayouted() const
{
if (!textLayoutDirty)
return;
ensureTextPopulated();
Q_Q(const QLabel);
if (control) {
QTextDocument *doc = control->document();
QTextOption opt = doc->defaultTextOption();
opt.setAlignment(QFlag(this->align));
if (this->align & Qt::TextWordWrap)
opt.setWrapMode(QTextOption::WordWrap);
else
opt.setWrapMode(QTextOption::ManualWrap);
opt.setTextDirection(q->layoutDirection());
doc->setDefaultTextOption(opt);
QTextFrameFormat fmt = doc->rootFrame()->frameFormat();
fmt.setMargin(0);
doc->rootFrame()->setFrameFormat(fmt);
doc->setTextWidth(documentRect().width());
}
textLayoutDirty = false;
}
void QLabelPrivate::ensureTextControl() const
{
Q_Q(const QLabel);
if (!isTextLabel)
return;
if (!control) {
control = new QTextControl(const_cast<QLabel *>(q));
control->document()->setUndoRedoEnabled(false);
control->document()->setDefaultFont(q->font());
control->setTextInteractionFlags(textInteractionFlags);
control->setOpenExternalLinks(openExternalLinks);
control->setPalette(q->palette());
control->setFocus(q->hasFocus());
QObject::connect(control, SIGNAL(updateRequest(QRectF)),
q, SLOT(update()));
QObject::connect(control, SIGNAL(linkHovered(QString)),
q, SLOT(_q_linkHovered(QString)));
QObject::connect(control, SIGNAL(linkActivated(QString)),
q, SIGNAL(linkActivated(QString)));
textLayoutDirty = true;
textDirty = true;
}
}
void QLabelPrivate::sendControlEvent(QEvent *e)
{
Q_Q(QLabel);
if (!isTextLabel || !control || textInteractionFlags == Qt::NoTextInteraction) {
e->ignore();
return;
}
control->processEvent(e, -layoutRect().topLeft(), q);
}
void QLabelPrivate::_q_linkHovered(const QString &anchor)
{
Q_Q(QLabel);
#ifndef QT_NO_CURSOR
if (anchor.isEmpty()) { // restore cursor
if (validCursor)
q->setCursor(cursor);
else
q->unsetCursor();
onAnchor = false;
} else if (!onAnchor) {
validCursor = q->testAttribute(Qt::WA_SetCursor);
if (validCursor) {
cursor = q->cursor();
}
q->setCursor(Qt::PointingHandCursor);
onAnchor = true;
}
#endif
emit q->linkHovered(anchor);
}
// Return the layout rect - this is the rect that is given to the layout painting code
// This may be different from the document rect since vertical alignment is not
// done by the text layout code
QRectF QLabelPrivate::layoutRect() const
{
QRectF cr = documentRect();
if (!control)
return cr;
ensureTextLayouted();
// Caculate y position manually
qreal rh = control->document()->documentLayout()->documentSize().height();
qreal yo = 0;
if (align & Qt::AlignVCenter)
yo = qMax((cr.height()-rh)/2, qreal(0));
else if (align & Qt::AlignBottom)
yo = qMax(cr.height()-rh, qreal(0));
return QRectF(cr.x(), yo + cr.y(), cr.width(), cr.height());
}
// Returns the point in the document rect adjusted with p
QPoint QLabelPrivate::layoutPoint(const QPoint& p) const
{
QRect lr = layoutRect().toRect();
return p - lr.topLeft();
}
#ifndef QT_NO_CONTEXTMENU
QMenu *QLabelPrivate::createStandardContextMenu(const QPoint &pos)
{
QString linkToCopy;
QPoint p;
if (control && isRichText) {
p = layoutPoint(pos);
linkToCopy = control->document()->documentLayout()->anchorAt(p);
}
if (linkToCopy.isEmpty() && !control)
return 0;
return control->createStandardContextMenu(p, q_func());
}
#endif
/*!
\fn void QLabel::linkHovered(const QString &link)
\since 4.2
This signal is emitted when the user hovers over a link. The URL
referred to by the anchor is passed in \a link.
\sa linkActivated()
*/
/*!
\fn void QLabel::linkActivated(const QString &link)
\since 4.2
This signal is emitted when the user clicks a link. The URL
referred to by the anchor is passed in \a link.
\sa linkHovered()
*/
QT_END_NAMESPACE
#include "moc_qlabel.cpp"
| librelab/qtmoko-test | qtopiacore/qt/src/gui/widgets/qlabel.cpp | C++ | gpl-2.0 | 44,261 |
<?php
/**
* DmMediaTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class DmMediaTable extends PluginDmMediaTable
{
/**
* Returns an instance of this class.
*
* @return DmMediaTable The table object
*/
public static function getInstance()
{
return Doctrine_Core::getTable('DmMedia');
}
} | Teplitsa/bquest.ru | lib/model/doctrine/dmCorePlugin/DmMediaTable.class.php | PHP | gpl-2.0 | 366 |
/*
* Copyright by iNet Solutions 2008.
*
* http://www.truthinet.com.vn/licenses
*/
Ext.onReady(function(){
var activeMenu;
function createMenu(name){
var el = Ext.get(name+'-link');
if (!el)
return;
var tid = 0, menu, doc = Ext.getDoc();
var handleOver = function(e, t){
if(t != el.dom && t != menu.dom && !e.within(el) && !e.within(menu)){
hideMenu();
}
};
var hideMenu = function(){
if(menu){
menu.hide();
el.setStyle('text-decoration', '');
doc.un('mouseover', handleOver);
doc.un('mousedown', handleDown);
}
}
var handleDown = function(e){
if(!e.within(menu)){
hideMenu();
}
}
var showMenu = function(){
clearTimeout(tid);
tid = 0;
if (!menu) {
menu = new Ext.Layer({shadow:'sides',hideMode: 'display'}, name+'-menu');
}
menu.hideMenu = hideMenu;
menu.el = el;
if(activeMenu && menu != activeMenu){
activeMenu.hideMenu();
}
activeMenu = menu;
if (!menu.isVisible()) {
menu.show();
menu.alignTo(el, 'tl-bl?');
menu.sync();
el.setStyle('text-decoration', 'underline');
doc.on('mouseover', handleOver, null, {buffer:150});
doc.on('mousedown', handleDown);
}
}
el.on('mouseover', function(e){
if(!tid){
tid = showMenu.defer(150);
}
});
el.on('mouseout', function(e){
if(tid && !e.within(el, true)){
clearTimeout(tid);
tid = 0;
}
});
}
createMenu('iwebos');
createMenu('home');
createMenu('document');
createMenu('calendar');
createMenu('mail');
createMenu('administrator');
createMenu('contact');
createMenu('paperwork');
// expanders
Ext.getBody().on('click', function(e, t){
t = Ext.get(t);
e.stopEvent();
var bd = t.next('div.expandable-body');
bd.enableDisplayMode();
var bdi = bd.first();
var expanded = bd.isVisible();
if(expanded){
bd.hide();
}else{
bdi.hide();
bd.show();
bdi.slideIn('l', {duration:0.2, stopFx: true, easing:'easeOut'});
}
t.update(!expanded ? 'Hide details' : 'Show details');
}, null, {delegate:'a.expander'});
});
| inetcloud/iMail | source/mail-admin/js/inet/ui/common/menu/Menu.js | JavaScript | gpl-2.0 | 2,082 |
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# d$
#
# 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/>.
#
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
class stock_incoterms(osv.Model):
"""
stock_incoterm
"""
_inherit = 'stock.incoterms'
_columns = {
'description': fields.text('Description',
help='Formal description for this incoterm.'),
}
| 3dfxsoftware/cbss-addons | incoterm_ext/incoterm.py | Python | gpl-2.0 | 1,298 |
/**
* Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved.
* This software is published under the GPL GNU General Public 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 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.
*
* This software was written for the
* Department of Family Medicine
* McMaster University
* Hamilton
* Ontario, Canada
*/
package oscar.oscarWaitingList.util;
import java.util.Date;
import java.util.List;
import org.oscarehr.common.dao.WaitingListDao;
import org.oscarehr.common.model.WaitingList;
import org.oscarehr.util.MiscUtils;
import org.oscarehr.util.SpringUtils;
import oscar.util.ConversionUtils;
public class WLWaitingListUtil {
// Modified this method in Feb 2007 to ensure that all records cannot be deleted except hidden.
static public synchronized void removeFromWaitingList(String waitingListID, String demographicNo) {
MiscUtils.getLogger().debug("WLWaitingListUtil.removeFromWaitingList(): removing waiting list: " + waitingListID + " for patient " + demographicNo);
WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class);
for (WaitingList wl : dao.findByWaitingListIdAndDemographicId(ConversionUtils.fromIntString(waitingListID), ConversionUtils.fromIntString(demographicNo))) {
wl.setHistory(true);
dao.merge(wl);
}
rePositionWaitingList(waitingListID);
}
static public synchronized void add2WaitingList(String waitingListID, String waitingListNote, String demographicNo, String onListSince) {
MiscUtils.getLogger().debug("WLWaitingListUtil.add2WaitingList(): adding to waitingList: " + waitingListID + " for patient " + demographicNo);
boolean emptyIds = waitingListID.equalsIgnoreCase("0") || demographicNo.equalsIgnoreCase("0");
if (emptyIds) {
MiscUtils.getLogger().debug("Ids are not proper - exiting");
return;
}
WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class);
int maxPosition = dao.getMaxPosition(ConversionUtils.fromIntString(waitingListID));
WaitingList list = new WaitingList();
list.setListId(maxPosition);
list.setDemographicNo(ConversionUtils.fromIntString(demographicNo));
list.setNote(waitingListNote);
if (onListSince == null || onListSince.length() <= 0) {
list.setOnListSince(new Date());
} else {
list.setOnListSince(ConversionUtils.fromDateString(onListSince));
}
list.setPosition(maxPosition + 1);
list.setHistory(false);
dao.persist(list);
// update the waiting list positions
rePositionWaitingList(waitingListID);
}
/*
* This method adds the Waiting List note to the same position in the waitingList table but do not delete previous ones - later on DisplayWaitingList.jsp will display only the most current Waiting List Note record.
*/
static public synchronized void updateWaitingListRecord(String waitingListID, String waitingListNote, String demographicNo, String onListSince) {
MiscUtils.getLogger().debug("WLWaitingListUtil.updateWaitingListRecord(): waitingListID: " + waitingListID + " for patient " + demographicNo);
boolean isWatingIdSet = !waitingListID.equalsIgnoreCase("0") && !demographicNo.equalsIgnoreCase("0");
if (!isWatingIdSet) return;
WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class);
List<WaitingList> waitingLists = dao.findByWaitingListIdAndDemographicId(ConversionUtils.fromIntString(waitingListID), ConversionUtils.fromIntString(demographicNo));
if (waitingLists.isEmpty()) return;
long pos = 1;
for (WaitingList wl : waitingLists) {
pos = wl.getPosition();
}
// set all previous records 'is_history' fielf to 'N' --> to keep as record but never display
for (WaitingList wl : waitingLists) {
wl.setHistory(true);
dao.merge(wl);
}
WaitingList wl = new WaitingList();
wl.setListId(ConversionUtils.fromIntString(waitingListID));
wl.setDemographicNo(ConversionUtils.fromIntString(demographicNo));
wl.setNote(waitingListNote);
wl.setPosition(pos);
wl.setOnListSince(ConversionUtils.fromDateString(onListSince));
wl.setHistory(false);
dao.saveEntity(wl);
// update the waiting list positions
rePositionWaitingList(waitingListID);
}
/*
* This method adds the Waiting List note to the same position in the waitingList table but do not delete previous ones - later on DisplayWaitingList.jsp will display only the most current Waiting List Note record.
*/
static public synchronized void updateWaitingList(String id, String waitingListID, String waitingListNote, String demographicNo, String onListSince) {
MiscUtils.getLogger().debug("WLWaitingListUtil.updateWaitingList(): waitingListID: " + waitingListID + " for patient " + demographicNo);
boolean idsSet = !waitingListID.equalsIgnoreCase("0") && !demographicNo.equalsIgnoreCase("0");
if (!idsSet) {
MiscUtils.getLogger().debug("Ids are not set - exiting");
return;
}
boolean wlIdsSet = (id != null && !id.equals(""));
if (!wlIdsSet) {
MiscUtils.getLogger().debug("Waiting list id is not set");
return;
}
WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class);
WaitingList waitingListEntry = dao.find(ConversionUtils.fromIntString(id));
if (waitingListEntry == null) {
MiscUtils.getLogger().debug("Unable to fetch waiting list with id " + id);
return;
}
waitingListEntry.setListId(ConversionUtils.fromIntString(waitingListID));
waitingListEntry.setNote(waitingListNote);
waitingListEntry.setOnListSince(ConversionUtils.fromDateString(onListSince));
dao.merge(waitingListEntry);
}
public static void rePositionWaitingList(String waitingListID) {
int i = 1;
WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class);
for (WaitingList waitingList : dao.findByWaitingListId(ConversionUtils.fromIntString(waitingListID))) {
waitingList.setPosition(i);
dao.merge(waitingList);
i++;
}
}
}
| hexbinary/landing | src/main/java/oscar/oscarWaitingList/util/WLWaitingListUtil.java | Java | gpl-2.0 | 6,477 |
<?php
$db = mysql_connect("localhost","root","");
mysql_select_db("asterisk");
// Астериск по каким то непонятным причинам сбрасывает в cdr одинаковые записи без forkcdr и т.д.
// задача найти их и убрать.
//проверка на трансфер
$transfer = array();
$q = "
select
c.id, c.calldate, c.src, c.channel, c.lastdata, c.duration, c.billsec, c.disposition, c.uniqueid
from
cdr as c left join stat as s on c.id=s.cdrid
where
c.lastapp='Transferred Call' and
c.calldate>='2010-04-01 00:00:00';";
//and
// s.id is NULL;
//";
$r = mysql_query($q);
$n = mysql_num_rows($r);
for($i=0;$i<$n;$i++) {
list($id,$cd,$src, $ch, $ldata,$dur,$bs,$disp,$uid) = mysql_fetch_array($r);
$transfer[$ch] = $id.';;'.$cd.';;'.$src.';;'.$ldata.';;'.$dur.';;'.$bs.';;'.$disp.';;'.$uid;
}
print_r($transfer);
$q = "
select
c.id as cdrid,
c.dcontext as dcontext,
c.calldate as calldate,
c.src as src,
c.dst as dst,
c.channel as channel,
c.dstchannel as dstchannel,
c.duration as duration,
c.billsec as billsec,
c.disposition as disposition,
c.uniqueid as uniqueid,
s.id as sid
from
cdr as c left join stat as s on c.id=s.cdrid
where
s.id is NULL";
//echo $q."<br>";
$r = mysql_query($q);
$n = mysql_num_rows($r);
echo date("Y-m-d H:i:s: ").$n."\n";
//$n = 30;
$io = '';
$cdrid = 0;
$cd = '';
for($i=0;$i<$n;$i++) {
$row = mysql_fetch_array($r);
//print_r($row);
$cdrid = $row['cdrid'];
if(substr($row['dcontext'],0,2) == "ip" || $row['dcontext']=='inbound') // ip - old, inbound - new
$io = "in";
if(substr($row['dcontext'],0,1) == "c" || substr($row['dcontext'],0,1) == "p")
$io = "out";
$cd = $row['calldate'];
$src = $row['src'];
$dst = $row['dst'];
$kod = '-1'; //самая главная штука :) -1 = не обсчитан
//$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
$aa = preg_split('/-/', $row['channel'], -1, PREG_SPLIT_NO_EMPTY);
$ch = $aa[0];
$aa = preg_split('/-/', $row['dstchannel'], -1, PREG_SPLIT_NO_EMPTY);
$dstch = $aa[0];
$duration = $row['duration'];
$billsec = $row['billsec'];
$cause = $row['disposition'];
$uid = $row['uniqueid'];
//$tr = isset($transfer[$row['dstchannel']]);
$tr = 0;
$qt='';
/*if(isset($transfer[$row['dstchannel']])){
$tch = $row['dstchannel'];
$a = str_getcsv($transfer[$tch],';;');
list($tid,$tcd,$tsrc,$tldata,$tdur,$tbs,$tdisp,$tuid) = $a;
if($tcd==$cd){
//у нас есть трансфер
$qt = "insert into stat values(0,$tid,'tr','$cd',NOW(),'$tsrc','$dst','$kod','$ch','$tldata','$tdur','$tbs','$tdisp','$tuid','0.00','0.00');";
echo $qt."\n";
$kod = -5;
}
}*/
$qu = "insert into stat values(0,$cdrid,'$io','$cd',NOW(),'$src','$dst','$kod','$ch','$dstch','$duration','$billsec','$cause','$uid','0.00','0.00');";
$ru = mysql_query($qu);
if($kod==-5) $rt = mysql_query($qt);
//if(isset($transfer[$row['dstchannel']])) echo $qu."\n";
//echo '<br><br>';
}
mysql_close($db);
function str_getcsv($p,$d) {
return preg_split("/$d/", $p);
}
?>
| Calc86/tel | cron/unique.php | PHP | gpl-2.0 | 3,241 |
<?php
/*
* Styles and scripts registration and enqueuing
*
* @package mantra
* @subpackage Functions
*/
// Adding the viewport meta if the mobile view has been enabled
if($mantra_mobile=="Enable") add_action('wp_head', 'mantra_mobile_meta');
function mantra_mobile_meta() {
global $mantra_options;
foreach ($mantra_options as $key => $value) {
${"$key"} = $value ;
}
echo '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">';
}
// Loading mantra css style
function mantra_style() {
global $mantra_options;
foreach ($mantra_options as $key => $value) {
${"$key"} = $value ;
}
// Loading the style.css
wp_register_style( 'mantras', get_stylesheet_uri() );
wp_enqueue_style( 'mantras');
}
// Loading google font styles
function mantra_google_styles() {
global $mantra_options;
foreach ($mantra_options as $key => $value) {
${"$key"} = $value ;
}
wp_register_style( 'mantra_googlefont', esc_attr($mantra_googlefont2 ));
wp_register_style( 'mantra_googlefonttitle', esc_attr($mantra_googlefonttitle2 ));
wp_register_style( 'mantra_googlefontside',esc_attr($mantra_googlefontside2) );
wp_register_style( 'mantra_googlefontsubheader', esc_attr($mantra_googlefontsubheader2) );
wp_enqueue_style( 'mantra_googlefont');
wp_enqueue_style( 'mantra_googlefonttitle');
wp_enqueue_style( 'mantra_googlefontside');
wp_enqueue_style( 'mantra_googlefontsubheader');
// Loading the style-mobile.css if the mobile view is enabled
if($mantra_mobile=="Enable") { wp_register_style( 'mantra-mobile', get_template_directory_uri() . '/style-mobile.css' );
wp_enqueue_style( 'mantra-mobile');}
}
// CSS loading and hook into wp_enque_scripts
add_action('wp_print_styles', 'mantra_style',1 );
add_action('wp_head', 'mantra_custom_styles' ,8);
if($mantra_customcss!="/* Mantra Custom CSS */") add_action('wp_head', 'mantra_customcss',9);
add_action('wp_head', 'mantra_google_styles');
// JS loading and hook into wp_enque_scripts
add_action('wp_head', 'mantra_customjs' );
// Scripts loading and hook into wp_enque_scripts
function mantra_scripts_method() {
global $mantra_options;
foreach ($mantra_options as $key => $value) {
${"$key"} = $value ;
}
// If frontend - load the js for the menu and the social icons animations
if ( !is_admin() ) {
wp_register_script('cryout-frontend',get_template_directory_uri() . '/js/frontend.js', array('jquery') );
wp_enqueue_script('cryout-frontend');
// If mantra from page is enabled and the current page is home page - load the nivo slider js
if($mantra_frontpage == "Enable" && is_front_page()) {
wp_register_script('cryout-nivoSlider',get_template_directory_uri() . '/js/nivo-slider.js', array('jquery'));
wp_enqueue_script('cryout-nivoSlider');
}
}
/* We add some JavaScript to pages with the comment form
* to support sites with threaded comments (when in use).
*/
if ( is_singular() && get_option( 'thread_comments' ) )
wp_enqueue_script( 'comment-reply' );
}
add_action('wp_enqueue_scripts', 'mantra_scripts_method');
/**
* Adding CSS3 PIE behavior to elements that need it
*/
function mantra_ie_pie() {
echo '
<!--[if lte IE 8]>
<style type="text/css" media="screen">
#access ul li,
.edit-link a ,
#footer-widget-area .widget-title, .entry-meta,.entry-meta .comments-link,
.short-button-light, .short-button-dark ,.short-button-color ,blockquote {
position:relative;
behavior: url('.get_template_directory_uri().'/js/PIE/PIE.php);
}
#access ul ul {
-pie-box-shadow:0px 5px 5px #999;
}
#access ul li.current_page_item, #access ul li.current-menu-item ,
#access ul li ,#access ul ul ,#access ul ul li, .commentlist li.comment ,.commentlist .avatar,
.contentsearch #searchsubmit , .widget_search #s, #search #s , .widget_search #searchsubmit ,
.nivo-caption, .theme-default .nivoSlider {
behavior: url('.get_template_directory_uri().'/js/PIE/PIE.php);
}
</style>
<![endif]-->
';
}
add_action('wp_head', 'mantra_ie_pie', 10);
?>
| DanielMSchmidt/stadtfest-theme | wp-content/themes/mantra/includes/theme-styles.php | PHP | gpl-2.0 | 4,286 |
// OGLTexture.cpp
// KlayGE OpenGLÎÆÀíÀà ʵÏÖÎļþ
// Ver 3.12.0
// °æÈ¨ËùÓÐ(C) ¹¨ÃôÃô, 2003-2007
// Homepage: http://www.klayge.org
//
// 3.9.0
// Ö§³ÖTexture Array (2009.8.5)
//
// 3.6.0
// ÓÃpbo¼ÓËÙ (2007.3.13)
//
// 2.7.0
// Ôö¼ÓÁËAddressingMode, FilteringºÍAnisotropy (2005.6.27)
// Ôö¼ÓÁËMaxMipLevelºÍMipMapLodBias (2005.6.28)
//
// 2.3.0
// Ôö¼ÓÁËCopyToMemory (2005.2.6)
//
// Ð޸ļǼ
/////////////////////////////////////////////////////////////////////////////////
#include <KlayGE/KlayGE.hpp>
#include <KFL/ErrorHandling.hpp>
#include <KFL/Math.hpp>
#include <KlayGE/RenderEngine.hpp>
#include <KlayGE/RenderFactory.hpp>
#include <KlayGE/Texture.hpp>
#include <cstring>
#include <glloader/glloader.h>
#include <KlayGE/OpenGL/OGLRenderEngine.hpp>
#include <KlayGE/OpenGL/OGLUtil.hpp>
#include <KlayGE/OpenGL/OGLTexture.hpp>
namespace KlayGE
{
OGLTexture::OGLTexture(TextureType type, uint32_t array_size, uint32_t sample_count, uint32_t sample_quality, uint32_t access_hint)
: Texture(type, sample_count, sample_quality, access_hint),
hw_res_ready_(false)
{
array_size_ = array_size;
switch (type_)
{
case TT_1D:
if (array_size > 1)
{
target_type_ = GL_TEXTURE_1D_ARRAY;
}
else
{
target_type_ = GL_TEXTURE_1D;
}
break;
case TT_2D:
if (array_size > 1)
{
target_type_ = GL_TEXTURE_2D_ARRAY;
}
else
{
target_type_ = GL_TEXTURE_2D;
}
break;
case TT_3D:
target_type_ = GL_TEXTURE_3D;
break;
case TT_Cube:
if (array_size > 1)
{
target_type_ = GL_TEXTURE_CUBE_MAP_ARRAY;
}
else
{
target_type_ = GL_TEXTURE_CUBE_MAP;
}
break;
default:
KFL_UNREACHABLE("Invalid texture type");
}
if (sample_count_ <= 1)
{
if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access())
{
glCreateTextures(target_type_, 1, &texture_);
}
else if (glloader_GL_EXT_direct_state_access())
{
glGenTextures(1, &texture_);
}
else
{
glGenTextures(1, &texture_);
glBindTexture(target_type_, texture_);
}
}
else
{
glGenRenderbuffers(1, &texture_);
}
}
OGLTexture::~OGLTexture()
{
this->DeleteHWResource();
if (Context::Instance().RenderFactoryValid())
{
auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance());
re.DeleteBuffers(1, &pbo_);
}
else
{
glDeleteBuffers(1, &pbo_);
}
if (sample_count_ <= 1)
{
if (Context::Instance().RenderFactoryValid())
{
auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance());
re.DeleteTextures(1, &texture_);
}
else
{
glDeleteTextures(1, &texture_);
}
}
else
{
glDeleteRenderbuffers(1, &texture_);
}
}
std::wstring const & OGLTexture::Name() const
{
static const std::wstring name(L"OpenGL Texture");
return name;
}
uint32_t OGLTexture::Width(uint32_t level) const
{
KFL_UNUSED(level);
BOOST_ASSERT(level < num_mip_maps_);
return 1;
}
uint32_t OGLTexture::Height(uint32_t level) const
{
KFL_UNUSED(level);
BOOST_ASSERT(level < num_mip_maps_);
return 1;
}
uint32_t OGLTexture::Depth(uint32_t level) const
{
KFL_UNUSED(level);
BOOST_ASSERT(level < num_mip_maps_);
return 1;
}
void OGLTexture::CopyToSubTexture1D(Texture& target, uint32_t dst_array_index, uint32_t dst_level, uint32_t dst_x_offset,
uint32_t dst_width, uint32_t src_array_index, uint32_t src_level, uint32_t src_x_offset, uint32_t src_width, TextureFilter filter)
{
KFL_UNUSED(target);
KFL_UNUSED(dst_array_index);
KFL_UNUSED(dst_level);
KFL_UNUSED(dst_x_offset);
KFL_UNUSED(dst_width);
KFL_UNUSED(src_array_index);
KFL_UNUSED(src_level);
KFL_UNUSED(src_x_offset);
KFL_UNUSED(src_width);
KFL_UNUSED(filter);
KFL_UNREACHABLE("Can't be called");
}
void OGLTexture::CopyToSubTexture2D(Texture& target, uint32_t dst_array_index, uint32_t dst_level, uint32_t dst_x_offset,
uint32_t dst_y_offset, uint32_t dst_width, uint32_t dst_height, uint32_t src_array_index, uint32_t src_level, uint32_t src_x_offset,
uint32_t src_y_offset, uint32_t src_width, uint32_t src_height, TextureFilter filter)
{
KFL_UNUSED(target);
KFL_UNUSED(dst_array_index);
KFL_UNUSED(dst_level);
KFL_UNUSED(dst_x_offset);
KFL_UNUSED(dst_y_offset);
KFL_UNUSED(dst_width);
KFL_UNUSED(dst_height);
KFL_UNUSED(src_array_index);
KFL_UNUSED(src_level);
KFL_UNUSED(src_x_offset);
KFL_UNUSED(src_y_offset);
KFL_UNUSED(src_width);
KFL_UNUSED(src_height);
KFL_UNUSED(filter);
KFL_UNREACHABLE("Can't be called");
}
void OGLTexture::CopyToSubTexture3D(Texture& target, uint32_t dst_array_index, uint32_t dst_level, uint32_t dst_x_offset,
uint32_t dst_y_offset, uint32_t dst_z_offset, uint32_t dst_width, uint32_t dst_height, uint32_t dst_depth, uint32_t src_array_index,
uint32_t src_level, uint32_t src_x_offset, uint32_t src_y_offset, uint32_t src_z_offset, uint32_t src_width, uint32_t src_height,
uint32_t src_depth, TextureFilter filter)
{
KFL_UNUSED(target);
KFL_UNUSED(dst_array_index);
KFL_UNUSED(dst_level);
KFL_UNUSED(dst_x_offset);
KFL_UNUSED(dst_y_offset);
KFL_UNUSED(dst_z_offset);
KFL_UNUSED(dst_width);
KFL_UNUSED(dst_height);
KFL_UNUSED(dst_depth);
KFL_UNUSED(src_array_index);
KFL_UNUSED(src_level);
KFL_UNUSED(src_x_offset);
KFL_UNUSED(src_y_offset);
KFL_UNUSED(src_z_offset);
KFL_UNUSED(src_width);
KFL_UNUSED(src_height);
KFL_UNUSED(src_depth);
KFL_UNUSED(filter);
KFL_UNREACHABLE("Can't be called");
}
void OGLTexture::CopyToSubTextureCube(Texture& target, uint32_t dst_array_index, CubeFaces dst_face, uint32_t dst_level,
uint32_t dst_x_offset, uint32_t dst_y_offset, uint32_t dst_width, uint32_t dst_height, uint32_t src_array_index, CubeFaces src_face,
uint32_t src_level, uint32_t src_x_offset, uint32_t src_y_offset, uint32_t src_width, uint32_t src_height, TextureFilter filter)
{
KFL_UNUSED(target);
KFL_UNUSED(dst_array_index);
KFL_UNUSED(dst_face);
KFL_UNUSED(dst_level);
KFL_UNUSED(dst_x_offset);
KFL_UNUSED(dst_y_offset);
KFL_UNUSED(dst_width);
KFL_UNUSED(dst_height);
KFL_UNUSED(src_array_index);
KFL_UNUSED(src_face);
KFL_UNUSED(src_level);
KFL_UNUSED(src_x_offset);
KFL_UNUSED(src_y_offset);
KFL_UNUSED(src_width);
KFL_UNUSED(src_height);
KFL_UNUSED(filter);
KFL_UNREACHABLE("Can't be called");
}
void OGLTexture::Map1D(uint32_t array_index, uint32_t level, TextureMapAccess tma,
uint32_t x_offset, uint32_t width, void*& data)
{
KFL_UNUSED(array_index);
KFL_UNUSED(level);
KFL_UNUSED(tma);
KFL_UNUSED(x_offset);
KFL_UNUSED(width);
KFL_UNUSED(data);
KFL_UNREACHABLE("Can't be called");
}
void OGLTexture::Map2D(uint32_t array_index, uint32_t level, TextureMapAccess tma,
uint32_t x_offset, uint32_t y_offset,
uint32_t width, uint32_t height,
void*& data, uint32_t& row_pitch)
{
KFL_UNUSED(array_index);
KFL_UNUSED(level);
KFL_UNUSED(tma);
KFL_UNUSED(x_offset);
KFL_UNUSED(y_offset);
KFL_UNUSED(width);
KFL_UNUSED(height);
KFL_UNUSED(data);
KFL_UNUSED(row_pitch);
KFL_UNREACHABLE("Can't be called");
}
void OGLTexture::Map3D(uint32_t array_index, uint32_t level, TextureMapAccess tma,
uint32_t x_offset, uint32_t y_offset, uint32_t z_offset,
uint32_t width, uint32_t height, uint32_t depth,
void*& data, uint32_t& row_pitch, uint32_t& slice_pitch)
{
KFL_UNUSED(array_index);
KFL_UNUSED(level);
KFL_UNUSED(tma);
KFL_UNUSED(x_offset);
KFL_UNUSED(y_offset);
KFL_UNUSED(z_offset);
KFL_UNUSED(width);
KFL_UNUSED(height);
KFL_UNUSED(depth);
KFL_UNUSED(data);
KFL_UNUSED(row_pitch);
KFL_UNUSED(slice_pitch);
KFL_UNREACHABLE("Can't be called");
}
void OGLTexture::MapCube(uint32_t array_index, CubeFaces face, uint32_t level, TextureMapAccess tma,
uint32_t x_offset, uint32_t y_offset, uint32_t width, uint32_t height,
void*& data, uint32_t& row_pitch)
{
KFL_UNUSED(array_index);
KFL_UNUSED(face);
KFL_UNUSED(level);
KFL_UNUSED(tma);
KFL_UNUSED(x_offset);
KFL_UNUSED(y_offset);
KFL_UNUSED(width);
KFL_UNUSED(height);
KFL_UNUSED(data);
KFL_UNUSED(row_pitch);
KFL_UNREACHABLE("Can't be called");
}
void OGLTexture::Unmap1D(uint32_t array_index, uint32_t level)
{
KFL_UNUSED(array_index);
KFL_UNUSED(level);
KFL_UNREACHABLE("Can't be called");
}
void OGLTexture::Unmap2D(uint32_t array_index, uint32_t level)
{
KFL_UNUSED(array_index);
KFL_UNUSED(level);
KFL_UNREACHABLE("Can't be called");
}
void OGLTexture::Unmap3D(uint32_t array_index, uint32_t level)
{
KFL_UNUSED(array_index);
KFL_UNUSED(level);
KFL_UNREACHABLE("Can't be called");
}
void OGLTexture::UnmapCube(uint32_t array_index, CubeFaces face, uint32_t level)
{
KFL_UNUSED(array_index);
KFL_UNUSED(face);
KFL_UNUSED(level);
KFL_UNREACHABLE("Can't be called");
}
bool OGLTexture::HwBuildMipSubLevels(TextureFilter filter)
{
if (IsDepthFormat(format_) || (ChannelType<0>(format_) == ECT_UInt) || (ChannelType<0>(format_) == ECT_SInt))
{
if (filter != TextureFilter::Point)
{
return false;
}
}
else
{
if (filter != TextureFilter::Linear)
{
return false;
}
}
if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access())
{
glGenerateTextureMipmap(texture_);
}
else if (glloader_GL_EXT_direct_state_access())
{
glGenerateTextureMipmapEXT(texture_, target_type_);
}
else
{
auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance());
re.BindTexture(0, target_type_, texture_);
glGenerateMipmap(target_type_);
}
return true;
}
void OGLTexture::TexParameteri(GLenum pname, GLint param)
{
auto iter = tex_param_i_.find(pname);
if ((iter == tex_param_i_.end()) || (iter->second != param))
{
if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access())
{
glTextureParameteri(texture_, pname, param);
}
else if (glloader_GL_EXT_direct_state_access())
{
glTextureParameteriEXT(texture_, target_type_, pname, param);
}
else
{
auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance());
re.BindTexture(0, target_type_, texture_);
glTexParameteri(target_type_, pname, param);
}
tex_param_i_[pname] = param;
}
}
void OGLTexture::TexParameterf(GLenum pname, GLfloat param)
{
auto iter = tex_param_f_.find(pname);
if ((iter == tex_param_f_.end()) || (iter->second != param))
{
if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access())
{
glTextureParameterf(texture_, pname, param);
}
else if (glloader_GL_EXT_direct_state_access())
{
glTextureParameterfEXT(texture_, target_type_, pname, param);
}
else
{
auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance());
re.BindTexture(0, target_type_, texture_);
glTexParameterf(target_type_, pname, param);
}
tex_param_f_[pname] = param;
}
}
void OGLTexture::TexParameterfv(GLenum pname, GLfloat const * param)
{
float4 const f4_param(param);
auto iter = tex_param_fv_.find(pname);
if ((iter == tex_param_fv_.end()) || (iter->second != f4_param))
{
if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access())
{
glTextureParameterfv(texture_, pname, param);
}
else if (glloader_GL_EXT_direct_state_access())
{
glTextureParameterfvEXT(texture_, target_type_, pname, param);
}
else
{
auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance());
re.BindTexture(0, target_type_, texture_);
glTexParameterfv(target_type_, pname, param);
}
tex_param_fv_[pname] = f4_param;
}
}
ElementFormat OGLTexture::SRGBToRGB(ElementFormat pf)
{
switch (pf)
{
case EF_ARGB8_SRGB:
return EF_ARGB8;
case EF_BC1_SRGB:
return EF_BC1;
case EF_BC2_SRGB:
return EF_BC2;
case EF_BC3_SRGB:
return EF_BC3;
default:
return pf;
}
}
void OGLTexture::DeleteHWResource()
{
hw_res_ready_ = false;
}
bool OGLTexture::HWResourceReady() const
{
return hw_res_ready_;
}
void OGLTexture::UpdateSubresource1D(uint32_t array_index, uint32_t level,
uint32_t x_offset, uint32_t width,
void const * data)
{
KFL_UNUSED(array_index);
KFL_UNUSED(level);
KFL_UNUSED(x_offset);
KFL_UNUSED(width);
KFL_UNUSED(data);
KFL_UNREACHABLE("Can't be called");
}
void OGLTexture::UpdateSubresource2D(uint32_t array_index, uint32_t level,
uint32_t x_offset, uint32_t y_offset, uint32_t width, uint32_t height,
void const * data, uint32_t row_pitch)
{
KFL_UNUSED(array_index);
KFL_UNUSED(level);
KFL_UNUSED(x_offset);
KFL_UNUSED(y_offset);
KFL_UNUSED(width);
KFL_UNUSED(height);
KFL_UNUSED(data);
KFL_UNUSED(row_pitch);
KFL_UNREACHABLE("Can't be called");
}
void OGLTexture::UpdateSubresource3D(uint32_t array_index, uint32_t level,
uint32_t x_offset, uint32_t y_offset, uint32_t z_offset,
uint32_t width, uint32_t height, uint32_t depth,
void const * data, uint32_t row_pitch, uint32_t slice_pitch)
{
KFL_UNUSED(array_index);
KFL_UNUSED(level);
KFL_UNUSED(x_offset);
KFL_UNUSED(y_offset);
KFL_UNUSED(z_offset);
KFL_UNUSED(width);
KFL_UNUSED(height);
KFL_UNUSED(depth);
KFL_UNUSED(data);
KFL_UNUSED(row_pitch);
KFL_UNUSED(slice_pitch);
KFL_UNREACHABLE("Can't be called");
}
void OGLTexture::UpdateSubresourceCube(uint32_t array_index, Texture::CubeFaces face, uint32_t level,
uint32_t x_offset, uint32_t y_offset, uint32_t width, uint32_t height,
void const * data, uint32_t row_pitch)
{
KFL_UNUSED(array_index);
KFL_UNUSED(face);
KFL_UNUSED(level);
KFL_UNUSED(x_offset);
KFL_UNUSED(y_offset);
KFL_UNUSED(width);
KFL_UNUSED(height);
KFL_UNUSED(data);
KFL_UNUSED(row_pitch);
KFL_UNREACHABLE("Can't be called");
}
}
| gongminmin/KlayGE | KlayGE/Plugins/Src/Render/OpenGL/OGLTexture.cpp | C++ | gpl-2.0 | 14,017 |
<?php
function tzs_front_end_user_products_handler($atts) {
// Определяем атрибуты
// [tzs-view-user-products user_id="1"] - указываем на странице раздела
// [tzs-view-products] - указываем на страницах подразделов
extract( shortcode_atts( array(
'user_id' => '0',
), $atts, 'tzs-view-user-products' ) );
ob_start();
$sql1 = ' AND user_id='.$user_id;
global $wpdb;
$page = current_page_number();
$url = current_page_url();
$pp = TZS_RECORDS_PER_PAGE;
$sql = "SELECT COUNT(*) as cnt FROM ".TZS_PRODUCTS_TABLE." WHERE active=1 $sql1 ";
$res = $wpdb->get_row($sql);
if (count($res) == 0 && $wpdb->last_error != null) {
print_error('Не удалось отобразить список товаров. Свяжитесь, пожалуйста, с администрацией сайта -count');
} else {
$records = $res->cnt;
$pages = ceil($records / $pp);
if ($pages == 0)
$pages = 1;
if ($page > $pages)
$page = $pages;
$from = ($page-1) * $pp;
$sql = "SELECT * FROM ".TZS_PRODUCTS_TABLE." WHERE active=1 $sql1 ORDER BY created DESC LIMIT $from,$pp; ";
$res = $wpdb->get_results($sql);
if (count($res) == 0 && $wpdb->last_error != null) {
print_error('Не удалось отобразить список товаров. Свяжитесь, пожалуйста, с администрацией сайта - record');
} else {
if (count($res) == 0) {
?>
<div style="clear: both;"></div>
<div class="errors">
<div id="info error">По Вашему запросу ничего не найдено.</div>
</div>
<?php
} else {
?>
<div>
<table id="tbl_products">
<tr>
<th id="tbl_products_id">Номер</th>
<th id="tbl_products_img">Фото</th>
<th id="tbl_products_dtc">Дата размещения</th>
<th id="title">Описание товара</th>
<th id="price">Стоимость товара</th>
<th id="descr">Форма оплаты</th>
<th id="cities">Город</th>
<th id="comm">Комментарии</th>
</tr>
<?php
foreach ( $res as $row ) {
?>
<tr rid="<?php echo $row->id;?>">
<td><?php echo $row->id;?></td>
<td>
<?php
if (strlen($row->image_id_lists) > 0) {
//$img_names = explode(';', $row->pictures);
$main_image_id = $row->main_image_id;
// Вначале выведем главное изображение
$attachment_info = wp_get_attachment_image_src($main_image_id, 'thumbnail');
if ($attachment_info !== false) {
//if (file_exists(ABSPATH . $img_names[0])) {
//echo '<img src="'.get_site_url().'/'.$img_names[0].'" alt="">';
echo '<img src="'.$attachment_info[0].'" alt="">';
// width="50px" height="50px"
} else {
echo ' ';
}
} else {
echo ' ';
}
?>
</td>
<td><?php echo convert_date($row->created); ?></td>
<td><?php echo htmlspecialchars($row->title);?></td>
<td><?php echo $row->price." ".$GLOBALS['tzs_pr_curr'][$row->currency];?></td>
<td><?php echo $GLOBALS['tzs_pr_payment'][$row->payment];?></td>
<td><?php echo tzs_city_to_str($row->from_cid, $row->from_rid, $row->from_sid, $row->city_from);?></td>
<td><?php echo htmlspecialchars($row->comment);?></td>
</tr>
<?php
}
?>
</table>
</div>
<?php
}
build_pages_footer($page, $pages);
}
}
////
?>
<script src="/wp-content/plugins/tzs/assets/js/search.js"></script>
<script>
var post = [];
<?php
echo "// POST dump here\n";
foreach ($_POST as $key => $value) {
echo "post[".tzs_encode2($key)."] = ".tzs_encode2($value).";\n";
}
if (!isset($_POST['type_id'])) {
echo "post[".tzs_encode2("type_id")."] = ".tzs_encode2($p_id).";\n";
}
if (!isset($_POST['cur_type_id'])) {
echo "post[".tzs_encode2("cur_type_id")."] = ".tzs_encode2($p_id).";\n";
}
?>
function showSearchDialog() {
doSearchDialog('products', post, null);
//doSearchDialog('auctions', post, null);
}
jQuery(document).ready(function(){
jQuery('#tbl_products').on('click', 'td', function(e) {
var nonclickable = 'true' == e.delegateTarget.rows[0].cells[this.cellIndex].getAttribute('nonclickable');
var id = this.parentNode.getAttribute("rid");
if (!nonclickable)
document.location = "/account/view-product/?id="+id;
});
hijackLinks(post);
});
</script>
<?php
////
$output = ob_get_contents();
ob_end_clean();
return $output;
}
?> | serker72/T3S_Old | wp-content/plugins/tzs/front-end/tzs.user.products.php | PHP | gpl-2.0 | 6,919 |
<?php
/*
@author : Giriraj Namachivayam
@date : Apr 25, 2013
@demourl : http://ngiriraj.com/socialMedia/oauthlogin/
@license : Free to use,
*/
include "socialmedia_oauth_connect.php";
$oauth = new socialmedia_oauth_connect();
$oauth->provider="DeviantArt";
$oauth->client_id = "396";
$oauth->client_secret = "xxxxxxxxxxxxxxxxxxxxxxxxx";
$oauth->redirect_uri ="http://ngiriraj.com/socialMedia/oauthlogin/deviantart.php";
$oauth->Initialize();
$code = ($_REQUEST["code"]) ? ($_REQUEST["code"]) : "";
if(empty($code)) {
$oauth->Authorize();
}else{
$oauth->code = $code;
# $oauth->getAccessToken();
$getData = json_decode($oauth->getUserProfile());
$oauth->debugJson($getData);
}
?> | phoenixz/base | data/plugins/socialmedia-oauth-login/deviantart.php | PHP | gpl-2.0 | 703 |
<?php
/**
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
namespace eZ\Bundle\EzPublishIOBundle\DependencyInjection\Factory;
use League\Flysystem\Adapter\Local;
/**
* Builds a Local Flysystem Adapter instance with the given permissions configuration.
*/
class LocalAdapterFactory
{
/**
* @param string $rootDir
* @param int $filesPermissions Permissions used when creating files. Example: 0640.
* @param int $directoriesPermissions Permissions when creating directories. Example: 0750.
*
* @return Local
*/
public function build($rootDir, $filesPermissions, $directoriesPermissions)
{
return new Local(
$rootDir,
LOCK_EX,
Local::DISALLOW_LINKS,
['file' => ['public' => $filesPermissions], 'dir' => ['public' => $directoriesPermissions]]
);
}
}
| ezsystems/ezpublish-kernel | eZ/Bundle/EzPublishIOBundle/DependencyInjection/Factory/LocalAdapterFactory.php | PHP | gpl-2.0 | 987 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Reflection
{
public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public Dictionary<string, int> Grades { get; set; }
public Student(string first, string last)
{
this.FirstName = first;
this.LastName = last;
this.Grades = new Dictionary<string, int>();
}
public void AddGrade(string course, int grade)
{
this.Grades.Add(course,grade);
}
}
}
| Omri27/AfekaTorrent | Reflection/Student.cs | C# | gpl-2.0 | 689 |
import os
from unipath import Path
try:
# expect at ~/source/tshilo-dikotla/etc/default.cnf
# etc folder is not in the git repo
PATH = Path(os.path.dirname(os.path.realpath(__file__))).ancestor(
1).child('etc')
if not os.path.exists(PATH):
raise TypeError(
'Path to database credentials at \'{}\' does not exist'.format(PATH))
with open(os.path.join(PATH, 'secret_key.txt')) as f:
PRODUCTION_SECRET_KEY = f.read().strip()
PRODUCTION_POSTGRES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(PATH, 'default.cnf'),
},
'HOST': '',
'PORT': '',
'ATOMIC_REQUESTS': True,
},
# 'lab_api': {
# 'ENGINE': 'django.db.backends.mysql',
# 'OPTIONS': {
# 'read_default_file': os.path.join(PATH, 'lab_api.cnf'),
# },
# 'HOST': '',
# 'PORT': '',
# 'ATOMIC_REQUESTS': True,
# },
}
except TypeError:
PRODUCTION_POSTGRES = None
PRODUCTION_SECRET_KEY = None
print('Path to production database credentials does not exist')
TRAVIS_POSTGRES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'td',
'USER': 'travis',
'HOST': '',
'PORT': '',
'ATOMIC_REQUESTS': True,
},
'lab_api': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'td_lab',
'USER': 'travis',
'HOST': '',
'PORT': '',
'ATOMIC_REQUESTS': True,
},
'test_server': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'td_test',
'USER': 'travis',
'HOST': '',
'PORT': '',
'ATOMIC_REQUESTS': True,
},
}
TEST_HOSTS_POSTGRES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'td',
'USER': 'django',
'PASSWORD': 'django',
'HOST': '',
'PORT': '',
'ATOMIC_REQUESTS': True,
},
'lab_api': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'td_lab',
'USER': 'django',
'PASSWORD': 'django',
'HOST': '',
'PORT': '',
'ATOMIC_REQUESTS': True,
},
}
| botswana-harvard/tshilo-dikotla | tshilo_dikotla/databases.py | Python | gpl-2.0 | 2,422 |
/**
* @file
* File with JS to initialize jQuery plugins on fields.
*/
(function($){
Drupal.behaviors.field_timer = {
attach: function() {
var settings = drupalSettings.field_timer;
if ($.countdown != undefined) {
$.countdown.setDefaults($.countdown.regionalOptions['']);
}
for (var key in settings) {
var options = settings[key].settings;
var $item = $('#' + key);
var timestamp = $item.data('timestamp');
switch (settings[key].plugin) {
case 'county':
$item.once('field-timer').each(function() {
$(this).county($.extend({endDateTime: new Date(timestamp * 1000)}, options));
});
break;
case 'jquery.countdown':
$item.once('field-timer').each(function() {
$(this).countdown($.extend(
options,
{
until: (options.until ? new Date(timestamp * 1000) : null),
since: (options.since ? new Date(timestamp * 1000) : null)
},
$.countdown.regionalOptions[options.regional]
));
});
break;
case 'jquery.countdown.led':
$item.once('field-timer').each(function() {
$(this).countdown({
until: (options.until ? new Date(timestamp * 1000) : null),
since: (options.since ? new Date(timestamp * 1000) : null),
layout: $item.html()
});
});
break;
}
}
}
}
})(jQuery);
| blakefrederick/sas-backend | modules/field_timer/js/field_timer.js | JavaScript | gpl-2.0 | 1,598 |
/*
* (C) 2007-2010 Alibaba Group Holding Limited.
*
* 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.
*
*
* Version: $Id: test_batch_read.cpp 44 2010-11-12 07:43:00Z chuyu@taobao.com $
*
* Authors:
* qushan <qushan@taobao.com>
* - initial release
*
*/
#include "util.h"
#include "thread.h"
#include "common/func.h"
#include "client/tfs_client_api.h"
#include <vector>
#include <algorithm>
#include <functional>
using namespace KFS;
using namespace tfs::client;
using namespace tfs::common;
static int32_t m_stop = 0;
void sign_handler(int32_t sig)
{
switch (sig)
{
case SIGINT:
m_stop = 1;
break;
}
}
#define FILE_NAME_LEN 18
void* read_worker(void* arg)
{
ThreadParam param = *(ThreadParam*) (arg);
char file_list_name[100];
sprintf(file_list_name, "wf_%d", param.index_);
FILE* input_fd = fopen(file_list_name, "rb");
if (NULL == input_fd)
{
printf("index(%d) open read file failed, exit\n", param.index_);
return NULL;
}
/*
param.locker_->lock();
TfsSession session;
session.init((char*) param.conf_.c_str());
param.locker_->unlock();
TfsFile tfs_file;
tfs_file.set_session(&session);
*/
printf("init connection to nameserver:%s\n", param.ns_ip_port_.c_str());
TfsClient tfsclient;
int iret = tfsclient.initialize(param.ns_ip_port_);
if (iret == TFS_ERROR)
{
return NULL;
}
Timer timer;
Stater stater("read");
const int32_t BUFLEN = 32;
char name_buf[BUFLEN];
int32_t failed_count = 0;
int32_t zoomed_count = 0;
int32_t total_count = 0;
int64_t time_start = Func::curr_time();
int64_t time_consumed = 0, min_time_consumed = 0, max_time_consumed = 0, accumlate_time_consumed = 0;
// 1M file number, each 18 bit, total 18M
vector < std::string > write_file_list;
while (fgets(name_buf, BUFLEN, input_fd))
{
ssize_t endpos = strlen(name_buf) - 1;
while (name_buf[endpos] == '\n')
{
name_buf[endpos] = 0;
--endpos;
}
write_file_list.push_back(name_buf);
}
fclose(input_fd);
//random read
if (param.random_)
{
vector<std::string>::iterator start = write_file_list.begin();
vector<std::string>::iterator end = write_file_list.end();
random_shuffle(start, end);
}
bool read_image = false;
bool image_scale_random = false;
if ((param.max_size_ != 0) && (param.min_size_ != 0))
{
read_image = true;
}
if (param.max_size_ != param.min_size_)
{
image_scale_random = true;
}
vector<std::string>::iterator vit = write_file_list.begin();
for (; vit != write_file_list.end(); vit++)
{
if (m_stop)
{
break;
}
if ((param.file_count_ > 0) && (total_count >= param.file_count_))
{
break;
}
timer.start();
int32_t ret = 0;
bool zoomed = true;
if (read_image)
{
if (image_scale_random)
{
srand(time(NULL) + rand() + pthread_self());
int32_t min_width = (param.max_size_ / 6);
int32_t min_height = (param.min_size_ / 6);
int32_t scale_width = rand() % (param.max_size_ - min_width) + min_width;
int32_t scale_height = rand() % (param.min_size_ - min_height) + min_height;
ret = copy_file_v3(tfsclient, (char *) (*vit).c_str(), scale_width, scale_height, -1, zoomed);
if (zoomed)
{
++zoomed_count;
}
}
}
else
{
ret = copy_file_v2(tfsclient, (char *) (*vit).c_str(), -1);
}
if (ret != TFS_SUCCESS)
{
printf("read file fail %s ret : %d\n", (*vit).c_str(), ret);
++failed_count;
}
else
{
time_consumed = timer.consume();
stater.stat_time_count(time_consumed);
if (total_count == 0)
{
min_time_consumed = time_consumed;
}
if (time_consumed < min_time_consumed)
{
min_time_consumed = time_consumed;
}
if (time_consumed > max_time_consumed)
{
max_time_consumed = time_consumed;
}
accumlate_time_consumed += time_consumed;
}
if (param.profile_)
{
printf("read file (%s), (%s)\n", (*vit).c_str(), ret == TFS_SUCCESS ? "success" : "failed");
print_rate(ret, time_consumed);
}
++total_count;
}
uint32_t total_succ_count = total_count - failed_count;
((ThreadParam*) arg)->file_count_ = total_succ_count;
int64_t time_stop = Func::curr_time();
time_consumed = time_stop - time_start;
double iops = static_cast<double> (total_succ_count) / (static_cast<double> (time_consumed) / 1000000);
double rate = static_cast<double> (time_consumed) / total_succ_count;
double aiops = static_cast<double> (total_succ_count) / (static_cast<double> (accumlate_time_consumed) / 1000000);
double arate = static_cast<double> (accumlate_time_consumed) / total_succ_count;
printf("thread index:%5d count:%5d failed:%5d, zoomed:%5d, filesize:%6d iops:%10.3f rate:%10.3f ,"
" min:%" PRI64_PREFIX "d, max:%" PRI64_PREFIX "d,avg:%" PRI64_PREFIX "d aiops:%10.3f, arate:%10.3f \n", param.index_, total_count, failed_count, zoomed_count,
param.file_size_, iops, rate, min_time_consumed, max_time_consumed, accumlate_time_consumed / total_succ_count,
aiops, arate);
stater.dump_time_stat();
return NULL;
}
int main(int argc, char* argv[])
{
int32_t thread_count = 1;
ThreadParam input_param;
int32_t ret = fetch_input_opt(argc, argv, input_param, thread_count);
if (ret != TFS_SUCCESS || input_param.ns_ip_port_.empty() || thread_count > THREAD_SIZE)
{
printf("usage: -d -t \n");
exit(-1);
}
//if (thread_count > 0) ClientPoolCollect::setClientPoolCollectParam(thread_count,0,0);
signal(SIGINT, sign_handler);
MetaThread threads[THREAD_SIZE];
ThreadParam param[THREAD_SIZE];
tbsys::CThreadMutex glocker;
int64_t time_start = Func::curr_time();
for (int32_t i = 0; i < thread_count; ++i)
{
param[i].index_ = i;
param[i].conf_ = input_param.conf_;
param[i].file_count_ = input_param.file_count_;
param[i].file_size_ = input_param.file_size_;
param[i].min_size_ = input_param.min_size_;
param[i].max_size_ = input_param.max_size_;
param[i].profile_ = input_param.profile_;
param[i].random_ = input_param.random_;
param[i].locker_ = &glocker;
param[i].ns_ip_port_ = input_param.ns_ip_port_;
threads[i].start(read_worker, (void*) ¶m[i]);
}
for (int32_t i = 0; i < thread_count; ++i)
{
threads[i].join();
}
int32_t total_count = 0;
for (int32_t i = 0; i < thread_count; ++i)
{
total_count += param[i].file_count_;
}
int64_t time_stop = Func::curr_time();
int64_t time_consumed = time_stop - time_start;
double iops = static_cast<double>(total_count) / (static_cast<double>(time_consumed) / 1000000);
double rate = static_cast<double>(time_consumed) / total_count;
printf("read_thread count filesize iops rate\n");
printf("%10d %5d %9d %8.3f %12.3f \n", thread_count, total_count, input_param.file_size_, iops, rate);
}
| qqiangwu/annotated-tfs | tests/batch/test_batch_read.cpp | C++ | gpl-2.0 | 7,158 |
namespace PowerPointLabs.ELearningLab.AudioGenerator
{
public class AzureAccount
{
private static AzureAccount instance;
private string key;
private string endpoint;
public static AzureAccount GetInstance()
{
if (instance == null)
{
instance = new AzureAccount();
}
return instance;
}
private AzureAccount()
{
key = null;
endpoint = null;
}
public void SetUserKeyAndRegion(string key, string endpoint)
{
this.key = key;
this.endpoint = endpoint;
}
public string GetKey()
{
return key;
}
public string GetRegion()
{
return endpoint;
}
public string GetUri()
{
if (!string.IsNullOrEmpty(endpoint))
{
return EndpointToUriConverter.azureEndpointToUriMapping[endpoint];
}
return null;
}
public bool IsEmpty()
{
return key == null || endpoint == null;
}
public void Clear()
{
key = null;
endpoint = null;
}
}
}
| PowerPointLabs/PowerPointLabs | PowerPointLabs/PowerPointLabs/ELearningLab/AudioGenerator/AzureVoiceGenerator/Model/AzureAccount.cs | C# | gpl-2.0 | 1,280 |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Hash;
use App\Models\Link;
use App\Models\User;
use App\Helpers\UserHelper;
class AdminController extends Controller {
/**
* Show the admin panel, and process admin AJAX requests.
*
* @return Response
*/
public function displayAdminPage(Request $request) {
if (!$this->isLoggedIn()) {
return abort(404);
}
$username = session('username');
$role = session('role');
$admin_users = null;
$admin_links = null;
if ($this->currIsAdmin()) {
$admin_users = User::paginate(15);
$admin_links = Link::paginate(15);
}
$user = UserHelper::getUserByUsername($username);
if (!$user) {
return redirect(route('index'))->with('error', 'Invalid or disabled account.');
}
$user_links = Link::where('creator', $username)
->paginate(15);
return view('admin', [
'role' => $role,
'admin_users' => $admin_users,
'admin_links' => $admin_links,
'user_links' => $user_links,
'api_key' => $user->api_key,
'api_active' => $user->api_active,
'api_quota' => $user->api_quota,
'user_id' => $user->id
]);
}
public function changePassword(Request $request) {
if (!$this->isLoggedIn()) {
return abort(404);
}
$username = session('username');
$old_password = $request->input('current_password');
$new_password = $request->input('new_password');
if (UserHelper::checkCredentials($username, $old_password) == false) {
// Invalid credentials
return redirect('admin')->with('error', 'Current password invalid. Try again.');
}
else {
// Credentials are correct
$user = UserHelper::getUserByUsername($username);
$user->password = Hash::make($new_password);
$user->save();
$request->session()->flash('success', "Password changed successfully.");
return redirect(route('admin'));
}
}
}
| goeroe/polr | app/Http/Controllers/AdminController.php | PHP | gpl-2.0 | 2,212 |
package teammates.client.scripts;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import teammates.common.datatransfer.DataBundle;
import teammates.common.datatransfer.attributes.CourseAttributes;
import teammates.common.datatransfer.attributes.InstructorAttributes;
import teammates.common.datatransfer.attributes.StudentAttributes;
import teammates.common.util.JsonUtils;
import teammates.test.driver.BackDoor;
import teammates.test.driver.FileHelper;
import teammates.test.driver.TestProperties;
import teammates.test.pageobjects.Browser;
import teammates.test.pageobjects.BrowserPool;
/**
* Annotations for Performance tests with
* <ul>
* <li>Name: name of the test</li>
* <li>CustomTimer: (default is false) if true, the function will return the duration need to recorded itself.
* If false, the function return the status of the test and expected the function
* which called it to record the duration.</li>
* </ul>
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface PerformanceTest {
String name() default "";
boolean customTimer() default false;
}
/**
* Usage: This script is to profile performance of the app with id in test.properties. To run multiple instance
* of this script in parallel, use ParallelProfiler.Java.
*
* <p>Notes:
* <ul>
* <li>Edit name of the report file, the result will be written to a file in src/test/resources/data folder</li>
* <li>Make sure that the data in PerformanceProfilerImportData.json is imported (by using ImportData.java)</li>
* </ul>
*/
public class PerformanceProfiler extends Thread {
private static final String defaultReportPath = TestProperties.TEST_DATA_FOLDER + "/" + "nameOfTheReportFile.txt";
private static final int NUM_OF_RUNS = 2;
private static final int WAIT_TIME_TEST = 1000; //waiting time between tests, in ms
private static final int WAIT_TIME_RUN = 5000; //waiting time between runs, in ms
private static final String runningDataSourceFile = "PerformanceProfilerRunningData.json";
private String reportFilePath;
private DataBundle data;
private Map<String, ArrayList<Float>> results = new HashMap<>();
protected PerformanceProfiler(String path) {
reportFilePath = path;
}
@Override
public void run() {
//Data used for profiling
String jsonString = "";
try {
jsonString = FileHelper.readFile(TestProperties.TEST_DATA_FOLDER + "/" + runningDataSourceFile);
} catch (IOException e) {
e.printStackTrace();
}
data = JsonUtils.fromJson(jsonString, DataBundle.class);
//Import previous results
try {
results = importReportFile(reportFilePath);
} catch (IOException e) {
e.printStackTrace();
}
Browser browser;
for (int i = 0; i < NUM_OF_RUNS; i++) {
browser = BrowserPool.getBrowser();
//overcome initial loading time with the below line
//getInstructorAsJson();
//get all methods with annotation and record time
Method[] methods = PerformanceProfiler.class.getMethods();
for (Method method : methods) {
performMethod(method);
}
// Wait between runs
BrowserPool.release(browser);
try {
Thread.sleep(WAIT_TIME_RUN);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Write the results back to file
try {
printResult(reportFilePath);
} catch (IOException e) {
e.printStackTrace();
}
System.out.print("\n Finished!");
}
/**
* This function perform the method and print the return value for debugging.
*/
private void performMethod(Method method) {
if (method.isAnnotationPresent(PerformanceTest.class)) {
PerformanceTest test = method.getAnnotation(PerformanceTest.class);
String name = test.name();
boolean customTimer = test.customTimer();
Type type = method.getReturnType();
if (!results.containsKey(name)) {
results.put(name, new ArrayList<Float>());
}
try {
float duration = 0;
if (type.equals(String.class) && !customTimer) {
long startTime = System.nanoTime();
Object retVal = method.invoke(this);
long endTime = System.nanoTime();
duration = (float) ((endTime - startTime) / 1000000.0); //in miliSecond
System.out.print("Name: " + name + "\tTime: " + duration + "\tVal: " + retVal.toString() + "\n");
} else if (type.equals(Long.class) && customTimer) {
duration = (float) ((Long) method.invoke(this) / 1000000.0);
System.out.print("Name: " + name + "\tTime: " + duration + "\n");
}
// Add new duration to the arrayList of the test.
ArrayList<Float> countList = results.get(name);
countList.add(duration);
} catch (Exception e) {
System.out.print(e.toString());
}
// reduce chance of data not being persisted
try {
Thread.sleep(WAIT_TIME_TEST);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Run this script as an single-thread Java application (for simple, non-parallel profiling).
* For parallel profiling, please use ParallelProfiler.java.
*/
public static void main(String[] args) {
// Run this script as an single-thread Java application (for simple, non-parallel profiling)
// For parallel profiling, please use ParallelProfiler.java
new PerformanceProfiler(defaultReportPath).start();
}
/**
* The results from file stored in filePath.
* @return {@code HashMap<nameOfTest, durations>} of the report stored in filePath
*/
private static HashMap<String, ArrayList<Float>> importReportFile(String filePath) throws IOException {
HashMap<String, ArrayList<Float>> results = new HashMap<>();
File reportFile = new File(filePath);
// Create the report file if not existed
if (!reportFile.exists()) {
try {
reportFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return results;
}
//Import old data to the HashMap
BufferedReader br = new BufferedReader(new FileReader(filePath));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
String[] strs = strLine.split("\\|");
String testName = strs[0];
String[] durations = strs[2].split("\\,");
ArrayList<Float> arr = new ArrayList<>();
for (String str : durations) {
Float f = Float.parseFloat(str);
arr.add(f);
}
results.put(testName, arr);
}
br.close();
return results;
}
/**
* Writes the results to the file with path filePath.
*/
private void printResult(String filePath) throws IOException {
List<String> list = new ArrayList<>();
for (String str : results.keySet()) {
list.add(str);
}
Collections.sort(list);
FileWriter fstream = new FileWriter(filePath);
BufferedWriter out = new BufferedWriter(fstream);
for (String str : list) {
StringBuilder lineStrBuilder = new StringBuilder();
ArrayList<Float> arr = results.get(str);
Float total = 0.0f;
for (Float f : arr) {
total += f;
lineStrBuilder.append(f).append(" , ");
}
String lineStr = lineStrBuilder.substring(0, lineStrBuilder.length() - 3); //remove last comma
Float average = total / arr.size();
out.write(str + "| " + average + " | " + lineStr + "\n");
}
out.close();
}
// TODO: this class needs to be tweaked to work with the new Browser class
// Performance Tests , the order of these tests is also the order they will run
/*
@PerformanceTest(name = "Instructor login",customTimer = true)
public Long instructorLogin() {
browser.goToUrl(TestProperties.TEAMMATES_URL);
browser.click(browser.instructorLoginButton);
long startTime = System.nanoTime();
browser.login("testingforteammates@gmail.com", "testingforteammates", false);
return System.nanoTime()-startTime;
}
@PerformanceTest(name = "Instructor home page")
String instructorHomePage() {
browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorHome");
return "";
}
@PerformanceTest(name = "Instructor eval page")
public String instructorEval() {
browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorEval");
return "";
}
@PerformanceTest(name = "Instructor add eval",customTimer = true)
public Long instructorAddEval() {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.add(Calendar.DATE, +1);
Date date1 = cal.getTime();
cal.add(Calendar.DATE, +2);
Date date2 = cal.getTime();
long startTime = System.nanoTime();
browser.addEvaluation("idOf_Z2_Cou0_of_Coo0", "test", date1, date2, true,
"This is the instructions, please follow", 5);
browser.waitForStatusMessage(Common.STATUS_EVALUATION_ADDED);
return System.nanoTime() - startTime;
}
@PerformanceTest(name = "Instructor eval page")
public String instructorEval2() {
browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorEval");
return "";
}
@PerformanceTest(name = "Instructor delete eval*",customTimer = true)
public Long instructorDeleteEval() {
int evalRowID = browser.getEvaluationRowID("idOf_Z2_Cou0_of_Coo0", "test");
By deleteLinkLocator = browser.getInstructorEvaluationDeleteLinkLocator(evalRowID);
long startTime =System.nanoTime();
browser.clickAndConfirm(deleteLinkLocator);
return System.nanoTime() - startTime;
}
@PerformanceTest(name = "Instructor course page")
public String instructorCourse() {
browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorCourse");
return "";
}
@PerformanceTest(name = "Instructor add course",customTimer = true)
public Long instructorAddCourse() {
long startTime = System.nanoTime();
browser.addCourse("testcourse", "testcourse");
browser.waitForStatusMessage(Common.STATUS_COURSE_ADDED);
return System.nanoTime() - startTime;
}
@PerformanceTest(name = "Instructor course page")
public String instructorCourse2() {
browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorCourse");
return "";
}
@PerformanceTest(name = "Instructor delete course*",customTimer = true)
public Long instructorDeleteCourse() throws Exception {
String courseId = "testcourse";
int courseRowId = browser.getCourseRowID(courseId);
By deleteLinkLocator = browser.getInstructorCourseDeleteLinkLocator(courseRowId);
long startTime = System.nanoTime();
browser.clickAndConfirm(deleteLinkLocator);
return System.nanoTime() - startTime;
}
@PerformanceTest(name = "Instructor course student detail page")
public String instructorCourseStudentDetails() {
browser.goToUrl(TestProperties.TEAMMATES_URL
+ "/page/instructorCourseStudentDetails?courseid=idOf_Z2_Cou0_of_Coo0"
+ "&studentemail=testingforteammates%40gmail.com");
return "";
}
@PerformanceTest(name = "Instructor course enroll page")
public String instructorCourseEnroll() {
browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorCourseEnroll?courseid=idOf_Z2_Cou0_of_Coo0");
return "";
}
@PerformanceTest(name = "Instructor course enroll student*",customTimer = true)
public Long instructorCourseEnrollStudent() {
String enrollString = "Team 1 | teststudent | alice.b.tmms@gmail.com | This comment has been changed\n";
browser.fillString(By.id("enrollstudents"), enrollString);
long startTime = System.nanoTime();
browser.click(By.id("button_enroll"));
return System.nanoTime() - startTime;
}
@PerformanceTest(name = "Instructor course enroll page")
public String instructorCourseDetails() {
browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorCourseDetails?courseid=idOf_Z2_Cou0_of_Coo0");
return "";
}
@PerformanceTest(name = "Instructor course delete student *",customTimer = true)
public Long instructorCourseDeleteStudent() {
int studentRowId = browser.getStudentRowId("teststudent");
long startTime = System.nanoTime();
browser.clickInstructorCourseDetailStudentDeleteAndConfirm(studentRowId);
return System.nanoTime() - startTime;
}
@PerformanceTest(name = "Instructor eval results")
public String instructorEvalResults() {
browser.goToUrl(TestProperties.TEAMMATES_URL
+ "/page/instructorEvalResults?courseid=idOf_Z2_Cou0_of_Coo0"
+ "&evaluationname=Z2_Eval0_in_Cou0_of_Coo0");
return "";
}
@PerformanceTest(name = "Instructor view student eval ")
public String instructorViewStuEval() {
browser.goToUrl(TestProperties.TEAMMATES_URL
+ "/page/instructorEvalSubmissionView?courseid=idOf_Z2_Cou0_of_Coo0"
+ "&evaluationname=Z2_Eval0_in_Cou0_of_Coo0&studentemail=Z2_Stu59Email%40gmail.com");
return "";
}
@PerformanceTest(name = "Instructor help page ")
public String instructorHelp() {
browser.goToUrl(TestProperties.TEAMMATES_URL + "/instructorHelp.jsp");
return "";
}
@PerformanceTest(name = "Instructor log out")
public String instructorLogout() {
browser.logout();
return "";
}
@PerformanceTest(name = "Student login")
public String stuLogin() {
browser.loginStudent("testingforteammates@gmail.com","testingforteammates");
return "";
}
@PerformanceTest(name = "Student homepage")
public String stuHomepage() {
browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/studentHome");
return "";
}
@PerformanceTest(name = "Student course detail page")
public String stuCoursepage() {
browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/studentCourseDetails?courseid=idOf_Z2_Cou0_of_Coo0");
return "";
}
@PerformanceTest(name = "Student edit submission page")
public String stuEditSubmissionPage() {
browser.goToUrl(TestProperties.TEAMMATES_URL
+ "/page/studentEvalEdit?courseid=idOf_Z2_Cou0_of_Coo0"
+ "&evaluationname=Z2_Eval0_in_Cou0_of_Coo0");
return "";
}
@PerformanceTest(name = "Student edit submission ")
public String stuEditSubmission() {
browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/studentCourseDetails?courseid=idOf_Z2_Cou0_of_Coo0");
return "";
}
@PerformanceTest(name = "Student eval result ")
public String stuEvalResultPage() {
browser.goToUrl(TestProperties.TEAMMATES_URL
+ "/page/studentEvalResults?courseid=idOf_Z2_Cou0_of_Coo0"
+ "&evaluationname=Z2_Eval0_in_Cou0_of_Coo0");
return "";
}
@PerformanceTest(name = "Student log out")
public String stuLogout() {
browser.logout();
return "";
}
@PerformanceTest(name = "BD create instructor")
public String createInstructor() {
String status = "";
Set<String> set = data.instructors.keySet();
for (String instructorKey : set) {
InstructorAttributes instructor = data.instructors.get(instructorKey);
status += BackDoor.createInstructor(instructor);
}
return status;
}
@PerformanceTest(name = "BD get instructor")
public String getInstructorAsJson() {
String status = "";
Set<String> set = data.instructors.keySet();
for (String instructorKey : set) {
InstructorAttributes instructor = data.instructors.get(instructorKey);
status += BackDoor.getInstructorAsJson(instructor.googleId, instructor.courseId);
}
return status;
}
@PerformanceTest(name = "BD get courses by instructor")
public String getCoursesByInstructor() {
String status = "";
Set<String> set = data.instructors.keySet();
for (String instructorKey : set) {
InstructorAttributes instructor = data.instructors.get(instructorKey);
String[] courses = BackDoor.getCoursesByInstructorId(instructor.googleId);
for (String courseName : courses) {
status += " " + courseName;
}
}
return status;
}
@PerformanceTest(name = "BD create course")
public String createCourse() {
String status = "";
Set<String> set = data.courses.keySet();
for (String courseKey : set) {
CourseAttributes course = data.courses.get(courseKey);
status += " " + BackDoor.createCourse(course);
}
return status;
}
@PerformanceTest(name = "BD get course")
public String getCourseAsJson() {
String status = "";
Set<String> set = data.courses.keySet();
for (String courseKey : set) {
CourseAttributes course = data.courses.get(courseKey);
status += " " + BackDoor.getCourseAsJson(course.id);
}
return status;
}
@PerformanceTest(name = "BD create student")
public String createStudent() {
String status = "";
Set<String> set = data.students.keySet();
for (String studentKey : set) {
StudentAttributes student = data.students.get(studentKey);
status += " " + BackDoor.createStudent(student);
}
return status;
}
// The method createSubmission is not implemented in BackDoor yet.
@PerformanceTest(name = "BD create submission")
static public String createSubmissions()
{
String status = "";
Set<String> set = data.submissions.keySet();
for (String submissionKey : set)
{
SubmissionData submission = data.submissions.get(submissionKey);
status += " " + BackDoor.createSubmission(submission);
}
return status;
}
*/
@PerformanceTest(name = "BD get student")
public String getStudent() {
StringBuilder status = new StringBuilder();
Set<String> set = data.getStudents().keySet();
for (String studentKey : set) {
StudentAttributes student = data.getStudents().get(studentKey);
status.append(' ').append(JsonUtils.toJson(BackDoor.getStudent(student.course, student.email)));
}
return status.toString();
}
@PerformanceTest(name = "BD get key for student")
public String getKeyForStudent() {
StringBuilder status = new StringBuilder();
Set<String> set = data.getStudents().keySet();
for (String studentKey : set) {
StudentAttributes student = data.getStudents().get(studentKey);
status.append(' ').append(BackDoor.getEncryptedKeyForStudent(student.course, student.email));
}
return status.toString();
}
@PerformanceTest(name = "BD edit student")
public String editStudent() {
StringBuilder status = new StringBuilder();
Set<String> set = data.getStudents().keySet();
for (String studentKey : set) {
StudentAttributes student = data.getStudents().get(studentKey);
status.append(' ').append(BackDoor.editStudent(student.email, student));
}
return status.toString();
}
@PerformanceTest(name = "BD delete student")
public String deleteStudent() {
StringBuilder status = new StringBuilder();
Set<String> set = data.getStudents().keySet();
for (String studentKey : set) {
StudentAttributes student = data.getStudents().get(studentKey);
status.append(' ').append(BackDoor.deleteStudent(student.course, student.email));
}
return status.toString();
}
@PerformanceTest(name = "BD Delete Course")
public String deleteCourse() {
StringBuilder status = new StringBuilder();
Set<String> set = data.getCourses().keySet();
for (String courseKey : set) {
CourseAttributes course = data.getCourses().get(courseKey);
status.append(' ').append(BackDoor.deleteCourse(course.getId()));
}
return status.toString();
}
@PerformanceTest(name = "BD Delete Instructor")
public String deleteInstructor() {
StringBuilder status = new StringBuilder();
Set<String> set = data.getInstructors().keySet();
for (String instructorKey : set) {
InstructorAttributes instructor = data.getInstructors().get(instructorKey);
status.append(BackDoor.deleteInstructor(instructor.email, instructor.courseId));
}
return status.toString();
}
}
| Gorgony/teammates | src/client/java/teammates/client/scripts/PerformanceProfiler.java | Java | gpl-2.0 | 22,398 |
/*
* Copyright (C) 2013-2014 Stefan Ascher <sa14@stievie.mooo.com>
*
* This file is part of Giddo.
*
* Giddo 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.
* Giddo 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 Giddo. If not, see <http://www.gnu.org/licenses/>.
*/
function dayDiff(first, second)
{
return Math.round((second - first) / (1000 * 60 * 60 * 24));
}
$(document).ready(function() {
var now = new Date();
var nowUtc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),
now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
$.each($(".date-time"), function() {
var val = $(this).text();
var dt = val.split(" ");
var date = dt[0].split("-");
var then = new Date(Date.UTC(parseInt(date[0]), parseInt(date[1]) - 1, parseInt(date[2])));
var daysSince = dayDiff(then, nowUtc);
var time = dt[1].split(":");
var years = now.getFullYear() - parseInt(date[0]);
if (years !== 0)
return;
$(this).attr("title", val);
var months = (now.getMonth() + 1) - parseInt(date[1]);
if (daysSince > 29)
{
if (months > 1)
{
$(this).text(months + " months ago");
return;
}
if (months === 1)
{
$(this).text(months + " month ago");
return;
}
}
if (daysSince > 1)
{
$(this).text(daysSince + " days ago");
return;
}
if (daysSince === 1)
{
$(this).text(daysSince + " day ago");
return;
}
var hours = now.getHours() - parseInt(time[0]);
if (hours > 1)
{
$(this).text(hours + " hours ago");
return;
}
if (hours === 1)
{
$(this).text(hours + " hour ago");
return;
}
var mins = now.getMinutes() - parseInt(time[1]);
if (mins > 1)
{
$(this).text(mins + " minutes ago");
return;
}
if (mins === 1)
{
$(this).text(mins + " minute ago");
return;
}
var secs = now.getSeconds() - parseInt(time[2]);
if (secs > 1)
{
$(this).text(secs + " seconds ago");
return;
}
if (secs === 1)
{
$(this).text(secs + " second ago");
return;
}
$(this).text("right now");
});
$.each($(".time"), function() {
var val = $(this).text();
var dt = val.split(" ");
$(this).attr("title", val);
$(this).text(dt[1]);
});
});
| stievie/Giddo | js/datetime.js | JavaScript | gpl-2.0 | 2,848 |
/*
* Copyright (c) 1998-2015 Caucho Technology -- all rights reserved
*
* This file is part of Baratine(TM)(TM)
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Baratine 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.
*
* Baratine 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Baratine; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package io.baratine.pipe;
import java.util.Map;
/**
* General message type for pipes.
*
* This Message API is designed to improve interoperability by providing a
* useful default API. While pipes can use any message type, general messages
* drivers like an AMQP broker or a mail sender need to choose one of
* their own.
*
* Applications may be better served by using application-specific messages.
*
* @param <T> type of the encapsulated value
*/
public interface Message<T>
{
/**
* Method value returns encapsulated message value.
*
* @return encapsulated value
*/
T value();
/**
* Method headers returns optional header passed with the message
*
* @return map of headers
*/
Map<String,Object> headers();
/**
* Method header returns value of a header matching a key
*
* @param key header key
* @return header value
*/
Object header(String key);
/**
* Create an instance of a MessageBuilder using passed value as an encapsulated
* Message value.
*
* @param value value to encapsulate in a message
* @param <X> type of the value
* @return an instance of MessageBuilder
*/
static <X> MessageBuilder<X> newMessage(X value)
{
return new MessageImpl<>(value);
}
/**
* MessageBuilder interface allows setting properties for a Message, such as
* headers.
*
* @param <T> type of a value encapsulated in a Message
*/
interface MessageBuilder<T> extends Message<T>
{
MessageBuilder<T> header(String key, Object value);
}
}
| baratine/baratine | api/src/main/java/io/baratine/pipe/Message.java | Java | gpl-2.0 | 2,551 |
package org.caliog.myRPG.Mobs;
import org.bukkit.entity.Entity;
import org.caliog.myRPG.Manager;
import org.caliog.myRPG.Entities.PlayerManager;
import org.caliog.myRPG.Entities.myClass;
import org.caliog.myRPG.Utils.EntityUtils;
public class PetController {
public static void controll() {
for (final myClass player : PlayerManager.getPlayers()) {
if (player.getPets().isEmpty())
continue;
for (final Pet pet : player.getPets()) {
Entity entity = EntityUtils.getEntity(pet.getId(), player.getPlayer().getWorld());
if (entity == null)
continue;
if (entity.getLocation().distanceSquared(player.getPlayer().getLocation()) > 512) {
Manager.scheduleTask(new Runnable() {
@Override
public void run() {
pet.die(player);
}
});
}
}
}
}
}
| caliog/myRPG | src/org/caliog/myRPG/Mobs/PetController.java | Java | gpl-2.0 | 811 |
/*
Elysian Fields is a 2D game programmed in C# with the framework MonoGame
Copyright (C) 2015 Erik Iwarson
If you have any questions, don't hesitate to send me an e-mail at erikiwarson@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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Elysian_Fields
{
class DamageObject
{
public Creature creature;
public int ID;
public int damageDealt;
public int EndTime;
public int StartTime;
public const int Steps = 30;
public const int DamageDuration = 1000;
public const int Text_Damage = 1;
public const int Text_Healing = 2;
public const int Text_Experience = 3;
public int StepDuration { get { return DamageDuration / Steps; } set { } }
public int CurrentStep = 0;
public int Text_Type = 0;
//public bool Healing;
//public int OffsetX
public Coordinates Position = new Coordinates();
//public int StartOffsetX;
public double StartOffsetY = 15;
//public int EndOffsetX;
//public int EndOffsetY = 0;
public DamageObject()
{
ID = -1;
}
public DamageObject(Creature monster, int Damage, int _text_type, int _StartTime, int _EndTime, int id = 0, Coordinates pos = null)
{
creature = monster;
damageDealt = Damage;
ID = id;
EndTime = _EndTime;
StartTime = _StartTime;
Position = pos;
Text_Type = _text_type;
}
public double OffsetY(int CurrentTime)
{
double CurrentStepEndTime = StartTime + DamageDuration - ((Steps - CurrentStep) * StepDuration);
if (CurrentTime >= CurrentStepEndTime)
{
if(CurrentStep < Steps)
CurrentStep++;
}
return StartOffsetY - (CurrentStep * (StartOffsetY / Steps));
}
}
}
| Szune/Elysian-Fields | Elysian Fields/Elysian Fields/DamageObject.cs | C# | gpl-2.0 | 2,733 |
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xerces.impl.xs;
import java.util.Vector;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.dv.SchemaDVFactory;
import org.apache.xerces.impl.dv.ValidatedInfo;
import org.apache.xerces.impl.dv.XSSimpleType;
import org.apache.xerces.impl.xs.identity.IdentityConstraint;
import org.apache.xerces.impl.xs.util.SimpleLocator;
import org.apache.xerces.impl.xs.util.StringListImpl;
import org.apache.xerces.impl.xs.util.XSNamedMap4Types;
import org.apache.xerces.impl.xs.util.XSNamedMapImpl;
import org.apache.xerces.impl.xs.util.XSObjectListImpl;
import org.apache.xerces.parsers.DOMParser;
import org.apache.xerces.parsers.IntegratedParserConfiguration;
import org.apache.xerces.parsers.SAXParser;
import org.apache.xerces.util.SymbolHash;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.grammars.XMLGrammarDescription;
import org.apache.xerces.xni.grammars.XSGrammar;
import org.apache.xerces.xs.StringList;
import org.apache.xerces.xs.XSAnnotation;
import org.apache.xerces.xs.XSAttributeDeclaration;
import org.apache.xerces.xs.XSAttributeGroupDefinition;
import org.apache.xerces.xs.XSConstants;
import org.apache.xerces.xs.XSElementDeclaration;
import org.apache.xerces.xs.XSModel;
import org.apache.xerces.xs.XSModelGroupDefinition;
import org.apache.xerces.xs.XSNamedMap;
import org.apache.xerces.xs.XSNamespaceItem;
import org.apache.xerces.xs.XSNotationDeclaration;
import org.apache.xerces.xs.XSObjectList;
import org.apache.xerces.xs.XSParticle;
import org.apache.xerces.xs.XSTypeDefinition;
import org.apache.xerces.xs.XSWildcard;
/**
* This class is to hold all schema component declaration that are declared
* within one namespace.
*
* The Grammar class this class extends contains what little
* commonality there is between XML Schema and DTD grammars. It's
* useful to distinguish grammar objects from other kinds of object
* when they exist in pools or caches.
*
* @xerces.internal
*
* @author Sandy Gao, IBM
* @author Elena Litani, IBM
*
* @version $Id: SchemaGrammar.java,v 1.42 2004/12/15 23:48:48 mrglavas Exp $
*/
public class SchemaGrammar implements XSGrammar, XSNamespaceItem {
// the target namespace of grammar
String fTargetNamespace;
// global decls: map from decl name to decl object
SymbolHash fGlobalAttrDecls;
SymbolHash fGlobalAttrGrpDecls;
SymbolHash fGlobalElemDecls;
SymbolHash fGlobalGroupDecls;
SymbolHash fGlobalNotationDecls;
SymbolHash fGlobalIDConstraintDecls;
SymbolHash fGlobalTypeDecls;
// the XMLGrammarDescription member
XSDDescription fGrammarDescription = null;
// annotations associated with the "root" schema of this targetNamespace
XSAnnotationImpl [] fAnnotations = null;
// number of annotations declared
int fNumAnnotations;
// symbol table for constructing parsers (annotation support)
private SymbolTable fSymbolTable = null;
// parsers for annotation support
private SAXParser fSAXParser = null;
private DOMParser fDOMParser = null;
//
// Constructors
//
// needed to make BuiltinSchemaGrammar work.
protected SchemaGrammar() {}
/**
* Default constructor.
*
* @param targetNamespace
* @param grammarDesc the XMLGrammarDescription corresponding to this objec
* at the least a systemId should always be known.
* @param symbolTable needed for annotation support
*/
public SchemaGrammar(String targetNamespace, XSDDescription grammarDesc,
SymbolTable symbolTable) {
fTargetNamespace = targetNamespace;
fGrammarDescription = grammarDesc;
fSymbolTable = symbolTable;
// REVISIT: do we know the numbers of the following global decls
// when creating this grammar? If so, we can pass the numbers in,
// and use that number to initialize the following hashtables.
fGlobalAttrDecls = new SymbolHash();
fGlobalAttrGrpDecls = new SymbolHash();
fGlobalElemDecls = new SymbolHash();
fGlobalGroupDecls = new SymbolHash();
fGlobalNotationDecls = new SymbolHash();
fGlobalIDConstraintDecls = new SymbolHash();
// if we are parsing S4S, put built-in types in first
// they might get overwritten by the types from S4S, but that's
// considered what the application wants to do.
if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA)
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone();
else
fGlobalTypeDecls = new SymbolHash();
} // <init>(String, XSDDescription)
// number of built-in XSTypes we need to create for base and full
// datatype set
private static final int BASICSET_COUNT = 29;
private static final int FULLSET_COUNT = 46;
private static final int GRAMMAR_XS = 1;
private static final int GRAMMAR_XSI = 2;
// this class makes sure the static, built-in schema grammars
// are immutable.
public static class BuiltinSchemaGrammar extends SchemaGrammar {
/**
* Special constructor to create the grammars for the schema namespaces
*
* @param grammar
*/
public BuiltinSchemaGrammar(int grammar) {
SchemaDVFactory schemaFactory = SchemaDVFactory.getInstance();
if (grammar == GRAMMAR_XS) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// get all built-in types
fGlobalTypeDecls = schemaFactory.getBuiltInTypes();
// add anyType
fGlobalTypeDecls.put(fAnyType.getName(), fAnyType);
}
else if (grammar == GRAMMAR_XSI) {
// target namespace
fTargetNamespace = SchemaSymbols.URI_XSI;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_XSI);
// no global decls other than attributes
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(1);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
fGlobalTypeDecls = new SymbolHash(1);
// 4 attributes, so initialize the size as 4*2 = 8
fGlobalAttrDecls = new SymbolHash(8);
String name = null;
String tns = null;
XSSimpleType type = null;
short scope = XSConstants.SCOPE_GLOBAL;
// xsi:type
name = SchemaSymbols.XSI_TYPE;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_QNAME);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:nil
name = SchemaSymbols.XSI_NIL;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_BOOLEAN);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
XSSimpleType anyURI = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_ANYURI);
// xsi:schemaLocation
name = SchemaSymbols.XSI_SCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = schemaFactory.createTypeList(null, SchemaSymbols.URI_XSI, (short)0, anyURI, null);
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
// xsi:noNamespaceSchemaLocation
name = SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION;
tns = SchemaSymbols.URI_XSI;
type = anyURI;
fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope));
}
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(Vector importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
}
/**
* <p>A partial schema for schemas for validating annotations.</p>
*
* @xerces.internal
*
* @author Michael Glavassevich, IBM
*/
public static final class Schema4Annotations extends SchemaGrammar {
/**
* Special constructor to create a schema
* capable of validating annotations.
*/
public Schema4Annotations() {
// target namespace
fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
// grammar description
fGrammarDescription = new XSDDescription();
fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE;
fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA);
// no global decls other than types and
// element declarations for <annotation>, <documentation> and <appinfo>.
fGlobalAttrDecls = new SymbolHash(1);
fGlobalAttrGrpDecls = new SymbolHash(1);
fGlobalElemDecls = new SymbolHash(6);
fGlobalGroupDecls = new SymbolHash(1);
fGlobalNotationDecls = new SymbolHash(1);
fGlobalIDConstraintDecls = new SymbolHash(1);
// get all built-in types
fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls;
// create element declarations for <annotation>, <documentation> and <appinfo>
XSElementDecl annotationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_ANNOTATION);
XSElementDecl documentationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_DOCUMENTATION);
XSElementDecl appinfoDecl = createAnnotationElementDecl(SchemaSymbols.ELT_APPINFO);
// add global element declarations
fGlobalElemDecls.put(annotationDecl.fName, annotationDecl);
fGlobalElemDecls.put(documentationDecl.fName, documentationDecl);
fGlobalElemDecls.put(appinfoDecl.fName, appinfoDecl);
// create complex type declarations for <annotation>, <documentation> and <appinfo>
XSComplexTypeDecl annotationType = new XSComplexTypeDecl();
XSComplexTypeDecl documentationType = new XSComplexTypeDecl();
XSComplexTypeDecl appinfoType = new XSComplexTypeDecl();
// set the types on their element declarations
annotationDecl.fType = annotationType;
documentationDecl.fType = documentationType;
appinfoDecl.fType = appinfoType;
// create attribute groups for <annotation>, <documentation> and <appinfo>
XSAttributeGroupDecl annotationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl documentationAttrs = new XSAttributeGroupDecl();
XSAttributeGroupDecl appinfoAttrs = new XSAttributeGroupDecl();
// fill in attribute groups
{
// create and fill attribute uses for <annotation>, <documentation> and <appinfo>
XSAttributeUseImpl annotationIDAttr = new XSAttributeUseImpl();
annotationIDAttr.fAttrDecl = new XSAttributeDecl();
annotationIDAttr.fAttrDecl.setValues(SchemaSymbols.ATT_ID, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ID),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, annotationType, null);
annotationIDAttr.fUse = SchemaSymbols.USE_OPTIONAL;
annotationIDAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationSourceAttr = new XSAttributeUseImpl();
documentationSourceAttr.fAttrDecl = new XSAttributeDecl();
documentationSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationSourceAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl documentationLangAttr = new XSAttributeUseImpl();
documentationLangAttr.fAttrDecl = new XSAttributeDecl();
documentationLangAttr.fAttrDecl.setValues("lang".intern(), NamespaceContext.XML_URI, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_LANGUAGE),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null);
documentationLangAttr.fUse = SchemaSymbols.USE_OPTIONAL;
documentationLangAttr.fConstraintType = XSConstants.VC_NONE;
XSAttributeUseImpl appinfoSourceAttr = new XSAttributeUseImpl();
appinfoSourceAttr.fAttrDecl = new XSAttributeDecl();
appinfoSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI),
XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, appinfoType, null);
appinfoSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL;
appinfoSourceAttr.fConstraintType = XSConstants.VC_NONE;
// create lax attribute wildcard for <annotation>, <documentation> and <appinfo>
XSWildcardDecl otherAttrs = new XSWildcardDecl();
otherAttrs.fNamespaceList = new String [] {fTargetNamespace, null};
otherAttrs.fType = XSWildcard.NSCONSTRAINT_NOT;
otherAttrs.fProcessContents = XSWildcard.PC_LAX;
// add attribute uses and wildcards to attribute groups for <annotation>, <documentation> and <appinfo>
annotationAttrs.addAttributeUse(annotationIDAttr);
annotationAttrs.fAttributeWC = otherAttrs;
documentationAttrs.addAttributeUse(documentationSourceAttr);
documentationAttrs.addAttributeUse(documentationLangAttr);
documentationAttrs.fAttributeWC = otherAttrs;
appinfoAttrs.addAttributeUse(appinfoSourceAttr);
appinfoAttrs.fAttributeWC = otherAttrs;
}
// create particles for <annotation>
XSParticleDecl annotationParticle = createUnboundedModelGroupParticle();
{
XSModelGroupImpl annotationChoice = new XSModelGroupImpl();
annotationChoice.fCompositor = XSModelGroupImpl.MODELGROUP_CHOICE;
annotationChoice.fParticleCount = 2;
annotationChoice.fParticles = new XSParticleDecl[2];
annotationChoice.fParticles[0] = createChoiceElementParticle(appinfoDecl);
annotationChoice.fParticles[1] = createChoiceElementParticle(documentationDecl);
annotationParticle.fValue = annotationChoice;
}
// create wildcard particle for <documentation> and <appinfo>
XSParticleDecl anyWCSequenceParticle = createUnboundedAnyWildcardSequenceParticle();
// fill complex types
annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, new XSObjectListImpl(null, 0));
annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION);
annotationType.setIsAnonymous();
documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, new XSObjectListImpl(null, 0));
documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION);
documentationType.setIsAnonymous();
appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType,
XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION),
XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, new XSObjectListImpl(null, 0));
appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO);
appinfoType.setIsAnonymous();
} // <init>(int)
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription.makeClone();
} // getGrammarDescription(): XMLGrammarDescription
// override these methods solely so that these
// objects cannot be modified once they're created.
public void setImportedGrammars(Vector importedGrammars) {
// ignore
}
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
// ignore
}
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
// ignore
}
public void addGlobalElementDecl(XSElementDecl decl) {
// ignore
}
public void addGlobalGroupDecl(XSGroupDecl decl) {
// ignore
}
public void addGlobalNotationDecl(XSNotationDecl decl) {
// ignore
}
public void addGlobalTypeDecl(XSTypeDefinition decl) {
// ignore
}
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
// ignore
}
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
// ignore
}
public synchronized void addDocument(Object document, String location) {
// ignore
}
// annotation support
synchronized DOMParser getDOMParser() {
return null;
}
synchronized SAXParser getSAXParser() {
return null;
}
//
// private helper methods
//
private XSElementDecl createAnnotationElementDecl(String localName) {
XSElementDecl eDecl = new XSElementDecl();
eDecl.fName = localName;
eDecl.fTargetNamespace = fTargetNamespace;
eDecl.setIsGlobal();
eDecl.fBlock = (XSConstants.DERIVATION_EXTENSION |
XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION);
eDecl.setConstraintType(XSConstants.VC_NONE);
return eDecl;
}
private XSParticleDecl createUnboundedModelGroupParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 0;
particle.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particle.fType = XSParticleDecl.PARTICLE_MODELGROUP;
return particle;
}
private XSParticleDecl createChoiceElementParticle(XSElementDecl ref) {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
particle.fValue = ref;
return particle;
}
private XSParticleDecl createUnboundedAnyWildcardSequenceParticle() {
XSParticleDecl particle = createUnboundedModelGroupParticle();
XSModelGroupImpl sequence = new XSModelGroupImpl();
sequence.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
sequence.fParticleCount = 1;
sequence.fParticles = new XSParticleDecl[1];
sequence.fParticles[0] = createAnyLaxWildcardParticle();
particle.fValue = sequence;
return particle;
}
private XSParticleDecl createAnyLaxWildcardParticle() {
XSParticleDecl particle = new XSParticleDecl();
particle.fMinOccurs = 1;
particle.fMaxOccurs = 1;
particle.fType = XSParticleDecl.PARTICLE_WILDCARD;
XSWildcardDecl anyWC = new XSWildcardDecl();
anyWC.fNamespaceList = null;
anyWC.fType = XSWildcard.NSCONSTRAINT_ANY;
anyWC.fProcessContents = XSWildcard.PC_LAX;
particle.fValue = anyWC;
return particle;
}
}
// Grammar methods
// return the XMLGrammarDescription corresponding to this
// object
public XMLGrammarDescription getGrammarDescription() {
return fGrammarDescription;
} // getGrammarDescription(): XMLGrammarDescription
// DTDGrammar methods
public boolean isNamespaceAware () {
return true;
} // isNamespaceAware():boolean
Vector fImported = null;
public void setImportedGrammars(Vector importedGrammars) {
fImported = importedGrammars;
}
public Vector getImportedGrammars() {
return fImported;
}
/**
* Returns this grammar's target namespace.
*/
public final String getTargetNamespace() {
return fTargetNamespace;
} // getTargetNamespace():String
/**
* register one global attribute
*/
public void addGlobalAttributeDecl(XSAttributeDecl decl) {
fGlobalAttrDecls.put(decl.fName, decl);
}
/**
* register one global attribute group
*/
public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) {
fGlobalAttrGrpDecls.put(decl.fName, decl);
}
/**
* register one global element
*/
public void addGlobalElementDecl(XSElementDecl decl) {
fGlobalElemDecls.put(decl.fName, decl);
// if there is a substitution group affiliation, store in an array,
// for further constraint checking: UPA, PD, EDC
if (decl.fSubGroup != null) {
if (fSubGroupCount == fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount+INC_SIZE);
fSubGroups[fSubGroupCount++] = decl;
}
}
/**
* register one global group
*/
public void addGlobalGroupDecl(XSGroupDecl decl) {
fGlobalGroupDecls.put(decl.fName, decl);
}
/**
* register one global notation
*/
public void addGlobalNotationDecl(XSNotationDecl decl) {
fGlobalNotationDecls.put(decl.fName, decl);
}
/**
* register one global type
*/
public void addGlobalTypeDecl(XSTypeDefinition decl) {
fGlobalTypeDecls.put(decl.getName(), decl);
}
/**
* register one identity constraint
*/
public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl) {
elmDecl.addIDConstraint(decl);
fGlobalIDConstraintDecls.put(decl.getIdentityConstraintName(), decl);
}
/**
* get one global attribute
*/
public final XSAttributeDecl getGlobalAttributeDecl(String declName) {
return(XSAttributeDecl)fGlobalAttrDecls.get(declName);
}
/**
* get one global attribute group
*/
public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName) {
return(XSAttributeGroupDecl)fGlobalAttrGrpDecls.get(declName);
}
/**
* get one global element
*/
public final XSElementDecl getGlobalElementDecl(String declName) {
return(XSElementDecl)fGlobalElemDecls.get(declName);
}
/**
* get one global group
*/
public final XSGroupDecl getGlobalGroupDecl(String declName) {
return(XSGroupDecl)fGlobalGroupDecls.get(declName);
}
/**
* get one global notation
*/
public final XSNotationDecl getGlobalNotationDecl(String declName) {
return(XSNotationDecl)fGlobalNotationDecls.get(declName);
}
/**
* get one global type
*/
public final XSTypeDefinition getGlobalTypeDecl(String declName) {
return(XSTypeDefinition)fGlobalTypeDecls.get(declName);
}
/**
* get one identity constraint
*/
public final IdentityConstraint getIDConstraintDecl(String declName) {
return(IdentityConstraint)fGlobalIDConstraintDecls.get(declName);
}
/**
* get one identity constraint
*/
public final boolean hasIDConstraints() {
return fGlobalIDConstraintDecls.getLength() > 0;
}
// array to store complex type decls
private static final int INITIAL_SIZE = 16;
private static final int INC_SIZE = 16;
private int fCTCount = 0;
private XSComplexTypeDecl[] fComplexTypeDecls = new XSComplexTypeDecl[INITIAL_SIZE];
private SimpleLocator[] fCTLocators = new SimpleLocator[INITIAL_SIZE];
// an array to store groups being redefined by restriction
// even-numbered elements are the derived groups, odd-numbered ones their bases
private static final int REDEFINED_GROUP_INIT_SIZE = 2;
private int fRGCount = 0;
private XSGroupDecl[] fRedefinedGroupDecls = new XSGroupDecl[REDEFINED_GROUP_INIT_SIZE];
private SimpleLocator[] fRGLocators = new SimpleLocator[REDEFINED_GROUP_INIT_SIZE/2];
// a flag to indicate whether we have checked the 3 constraints on this
// grammar.
boolean fFullChecked = false;
/**
* add one complex type decl: for later constraint checking
*/
public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) {
if (fCTCount == fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount+INC_SIZE);
fCTLocators = resize(fCTLocators, fCTCount+INC_SIZE);
}
fCTLocators[fCTCount] = locator;
fComplexTypeDecls[fCTCount++] = decl;
}
/**
* add a group redefined by restriction: for later constraint checking
*/
public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) {
if (fRGCount == fRedefinedGroupDecls.length) {
// double array size each time.
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount << 1);
fRGLocators = resize(fRGLocators, fRGCount);
}
fRGLocators[fRGCount/2] = locator;
fRedefinedGroupDecls[fRGCount++] = derived;
fRedefinedGroupDecls[fRGCount++] = base;
}
/**
* get all complex type decls: for later constraint checking
*/
final XSComplexTypeDecl[] getUncheckedComplexTypeDecls() {
if (fCTCount < fComplexTypeDecls.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fComplexTypeDecls;
}
/**
* get the error locator of all complex type decls
*/
final SimpleLocator[] getUncheckedCTLocators() {
if (fCTCount < fCTLocators.length) {
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
return fCTLocators;
}
/**
* get all redefined groups: for later constraint checking
*/
final XSGroupDecl[] getRedefinedGroupDecls() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRedefinedGroupDecls;
}
/**
* get the error locator of all redefined groups
*/
final SimpleLocator[] getRGLocators() {
if (fRGCount < fRedefinedGroupDecls.length) {
fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount);
fRGLocators = resize(fRGLocators, fRGCount/2);
}
return fRGLocators;
}
/**
* after the first-round checking, some types don't need to be checked
* against UPA again. here we trim the array to the proper size.
*/
final void setUncheckedTypeNum(int newSize) {
fCTCount = newSize;
fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount);
fCTLocators = resize(fCTLocators, fCTCount);
}
// used to store all substitution group information declared in
// this namespace
private int fSubGroupCount = 0;
private XSElementDecl[] fSubGroups = new XSElementDecl[INITIAL_SIZE];
/**
* get all substitution group information: for the 3 constraint checking
*/
final XSElementDecl[] getSubstitutionGroups() {
if (fSubGroupCount < fSubGroups.length)
fSubGroups = resize(fSubGroups, fSubGroupCount);
return fSubGroups;
}
// anyType and anySimpleType: because there are so many places where
// we need direct access to these two types
public final static XSComplexTypeDecl fAnyType = new XSAnyType();
private static class XSAnyType extends XSComplexTypeDecl {
public XSAnyType () {
fName = SchemaSymbols.ATTVAL_ANYTYPE;
super.fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA;
fBaseType = this;
fDerivedBy = XSConstants.DERIVATION_RESTRICTION;
fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED;
fParticle = null;
fAttrGrp = null;
}
// overridden methods
public void setValues(String name, String targetNamespace,
XSTypeDefinition baseType, short derivedBy, short schemaFinal,
short block, short contentType,
boolean isAbstract, XSAttributeGroupDecl attrGrp,
XSSimpleType simpleType, XSParticleDecl particle) {
// don't allow this.
}
public void setName(String name){
// don't allow this.
}
public void setIsAbstractType() {
// null implementation
}
public void setContainsTypeID() {
// null implementation
}
public void setIsAnonymous() {
// null implementation
}
public void reset() {
// null implementation
}
public XSObjectList getAttributeUses() {
return new XSObjectListImpl(null, 0);
}
public XSAttributeGroupDecl getAttrGrp() {
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl();
attrGrp.fAttributeWC = wildcard;
return attrGrp;
}
public XSWildcard getAttributeWildcard() {
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
return wildcard;
}
public XSParticle getParticle() {
// the wildcard used in anyType (content and attribute)
// the spec will change strict to skip for anyType
XSWildcardDecl wildcard = new XSWildcardDecl();
wildcard.fProcessContents = XSWildcardDecl.PC_LAX;
// the particle for the content wildcard
XSParticleDecl particleW = new XSParticleDecl();
particleW.fMinOccurs = 0;
particleW.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED;
particleW.fType = XSParticleDecl.PARTICLE_WILDCARD;
particleW.fValue = wildcard;
// the model group of a sequence of the above particle
XSModelGroupImpl group = new XSModelGroupImpl();
group.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE;
group.fParticleCount = 1;
group.fParticles = new XSParticleDecl[1];
group.fParticles[0] = particleW;
// the content of anyType: particle of the above model group
XSParticleDecl particleG = new XSParticleDecl();
particleG.fType = XSParticleDecl.PARTICLE_MODELGROUP;
particleG.fValue = group;
return particleG;
}
public XSObjectList getAnnotations() {
return null;
}
}
private static class BuiltinAttrDecl extends XSAttributeDecl {
public BuiltinAttrDecl(String name, String tns,
XSSimpleType type, short scope) {
fName = name;
super.fTargetNamespace = tns;
fType = type;
fScope = scope;
}
public void setValues(String name, String targetNamespace,
XSSimpleType simpleType, short constraintType, short scope,
ValidatedInfo valInfo, XSComplexTypeDecl enclosingCT) {
// ignore this call.
}
public void reset () {
// also ignore this call.
}
public XSAnnotation getAnnotation() {
return null;
}
} // class BuiltinAttrDecl
// the grammars to hold components of the schema namespace
public final static BuiltinSchemaGrammar SG_SchemaNS = new BuiltinSchemaGrammar(GRAMMAR_XS);
public final static Schema4Annotations SG_Schema4Annotations = new Schema4Annotations();
public final static XSSimpleType fAnySimpleType = (XSSimpleType)SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_ANYSIMPLETYPE);
// the grammars to hold components of the schema-instance namespace
public final static BuiltinSchemaGrammar SG_XSI = new BuiltinSchemaGrammar(GRAMMAR_XSI);
static final XSComplexTypeDecl[] resize(XSComplexTypeDecl[] oldArray, int newSize) {
XSComplexTypeDecl[] newArray = new XSComplexTypeDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSGroupDecl[] resize(XSGroupDecl[] oldArray, int newSize) {
XSGroupDecl[] newArray = new XSGroupDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final XSElementDecl[] resize(XSElementDecl[] oldArray, int newSize) {
XSElementDecl[] newArray = new XSElementDecl[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
static final SimpleLocator[] resize(SimpleLocator[] oldArray, int newSize) {
SimpleLocator[] newArray = new SimpleLocator[newSize];
System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize));
return newArray;
}
// XSNamespaceItem methods
// the max index / the max value of XSObject type
private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE;
private static final boolean[] GLOBAL_COMP = {false, // null
true, // attribute
true, // element
true, // type
false, // attribute use
true, // attribute group
true, // group
false, // model group
false, // particle
false, // wildcard
false, // idc
true, // notation
false, // annotation
false, // facet
false, // multi value facet
true, // complex type
true // simple type
};
// store a certain kind of components from all namespaces
private XSNamedMap[] fComponents = null;
// store the documents and their locations contributing to this namespace
// REVISIT: use StringList and XSObjectList for there fields.
private Vector fDocuments = null;
private Vector fLocations = null;
public synchronized void addDocument(Object document, String location) {
if (fDocuments == null) {
fDocuments = new Vector();
fLocations = new Vector();
}
fDocuments.addElement(document);
fLocations.addElement(location);
}
/**
* [schema namespace]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#nsi-schema_namespace">[schema namespace]</a>
* @return The target namespace of this item.
*/
public String getSchemaNamespace() {
return fTargetNamespace;
}
// annotation support
synchronized DOMParser getDOMParser() {
if (fDOMParser != null) return fDOMParser;
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
IntegratedParserConfiguration config = new IntegratedParserConfiguration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
fDOMParser = new DOMParser(config);
return fDOMParser;
}
synchronized SAXParser getSAXParser() {
if (fSAXParser != null) return fSAXParser;
// REVISIT: when schema handles XML 1.1, will need to
// revisit this (and the practice of not prepending an XML decl to the annotation string
IntegratedParserConfiguration config = new IntegratedParserConfiguration(fSymbolTable);
// note that this should never produce errors or require
// entity resolution, so just a barebones configuration with
// a couple of feature set will do fine
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true);
config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false);
fSAXParser = new SAXParser(config);
return fSAXParser;
}
/**
* [schema components]: a list of top-level components, i.e. element
* declarations, attribute declarations, etc.
* @param objectType The type of the declaration, i.e.
* <code>ELEMENT_DECLARATION</code>. Note that
* <code>XSTypeDefinition.SIMPLE_TYPE</code> and
* <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the
* <code>objectType</code> to retrieve only complex types or simple
* types, instead of all types.
* @return A list of top-level definition of the specified type in
* <code>objectType</code> or an empty <code>XSNamedMap</code> if no
* such definitions exist.
*/
public synchronized XSNamedMap getComponents(short objectType) {
if (objectType <= 0 || objectType > MAX_COMP_IDX ||
!GLOBAL_COMP[objectType]) {
return XSNamedMapImpl.EMPTY_MAP;
}
if (fComponents == null)
fComponents = new XSNamedMap[MAX_COMP_IDX+1];
// get the hashtable for this type of components
if (fComponents[objectType] == null) {
SymbolHash table = null;
switch (objectType) {
case XSConstants.TYPE_DEFINITION:
case XSTypeDefinition.COMPLEX_TYPE:
case XSTypeDefinition.SIMPLE_TYPE:
table = fGlobalTypeDecls;
break;
case XSConstants.ATTRIBUTE_DECLARATION:
table = fGlobalAttrDecls;
break;
case XSConstants.ELEMENT_DECLARATION:
table = fGlobalElemDecls;
break;
case XSConstants.ATTRIBUTE_GROUP:
table = fGlobalAttrGrpDecls;
break;
case XSConstants.MODEL_GROUP_DEFINITION:
table = fGlobalGroupDecls;
break;
case XSConstants.NOTATION_DECLARATION:
table = fGlobalNotationDecls;
break;
}
// for complex/simple types, create a special implementation,
// which take specific types out of the hash table
if (objectType == XSTypeDefinition.COMPLEX_TYPE ||
objectType == XSTypeDefinition.SIMPLE_TYPE) {
fComponents[objectType] = new XSNamedMap4Types(fTargetNamespace, table, objectType);
}
else {
fComponents[objectType] = new XSNamedMapImpl(fTargetNamespace, table);
}
}
return fComponents[objectType];
}
/**
* Convenience method. Returns a top-level simple or complex type
* definition.
* @param name The name of the definition.
* @return An <code>XSTypeDefinition</code> or null if such definition
* does not exist.
*/
public XSTypeDefinition getTypeDefinition(String name) {
return getGlobalTypeDecl(name);
}
/**
* Convenience method. Returns a top-level attribute declaration.
* @param name The name of the declaration.
* @return A top-level attribute declaration or null if such declaration
* does not exist.
*/
public XSAttributeDeclaration getAttributeDeclaration(String name) {
return getGlobalAttributeDecl(name);
}
/**
* Convenience method. Returns a top-level element declaration.
* @param name The name of the declaration.
* @return A top-level element declaration or null if such declaration
* does not exist.
*/
public XSElementDeclaration getElementDeclaration(String name) {
return getGlobalElementDecl(name);
}
/**
* Convenience method. Returns a top-level attribute group definition.
* @param name The name of the definition.
* @return A top-level attribute group definition or null if such
* definition does not exist.
*/
public XSAttributeGroupDefinition getAttributeGroup(String name) {
return getGlobalAttributeGroupDecl(name);
}
/**
* Convenience method. Returns a top-level model group definition.
*
* @param name The name of the definition.
* @return A top-level model group definition definition or null if such
* definition does not exist.
*/
public XSModelGroupDefinition getModelGroupDefinition(String name) {
return getGlobalGroupDecl(name);
}
/**
* Convenience method. Returns a top-level notation declaration.
*
* @param name The name of the declaration.
* @return A top-level notation declaration or null if such declaration
* does not exist.
*/
public XSNotationDeclaration getNotationDeclaration(String name) {
return getGlobalNotationDecl(name);
}
/**
* [document location]
* @see <a href="http://www.w3.org/TR/xmlschema-1/#sd-document_location">[document location]</a>
* @return a list of document information item
*/
public StringList getDocumentLocations() {
return new StringListImpl(fLocations);
}
/**
* Return an <code>XSModel</code> that represents components in this schema
* grammar.
*
* @return an <code>XSModel</code> representing this schema grammar
*/
public XSModel toXSModel() {
return new XSModelImpl(new SchemaGrammar[]{this});
}
public XSModel toXSModel(XSGrammar[] grammars) {
if (grammars == null || grammars.length == 0)
return toXSModel();
int len = grammars.length;
boolean hasSelf = false;
for (int i = 0; i < len; i++) {
if (grammars[i] == this) {
hasSelf = true;
break;
}
}
SchemaGrammar[] gs = new SchemaGrammar[hasSelf ? len : len+1];
for (int i = 0; i < len; i++)
gs[i] = (SchemaGrammar)grammars[i];
if (!hasSelf)
gs[len] = this;
return new XSModelImpl(gs);
}
/**
* @see org.apache.xerces.xs.XSNamespaceItem#getAnnotations()
*/
public XSObjectList getAnnotations() {
return new XSObjectListImpl(fAnnotations, fNumAnnotations);
}
public void addAnnotation(XSAnnotationImpl annotation) {
if(annotation == null)
return;
if(fAnnotations == null) {
fAnnotations = new XSAnnotationImpl[2];
} else if(fNumAnnotations == fAnnotations.length) {
XSAnnotationImpl[] newArray = new XSAnnotationImpl[fNumAnnotations << 1];
System.arraycopy(fAnnotations, 0, newArray, 0, fNumAnnotations);
fAnnotations = newArray;
}
fAnnotations[fNumAnnotations++] = annotation;
}
} // class SchemaGrammar
| BIORIMP/biorimp | BIO-RIMP/test_data/code/xerces/src/org/apache/xerces/impl/xs/SchemaGrammar.java | Java | gpl-2.0 | 49,139 |
// **********************************************************************
//
// Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
using Test;
using System;
using System.Diagnostics;
using System.Reflection;
[assembly: CLSCompliant(true)]
[assembly: AssemblyTitle("IceTest")]
[assembly: AssemblyDescription("Ice test")]
[assembly: AssemblyCompany("ZeroC, Inc.")]
public class Collocated
{
internal class App : Ice.Application
{
public override int run(string[] args)
{
communicator().getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010");
communicator().getProperties().setProperty("Ice.Warn.Dispatch", "0");
Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter");
adapter.addServantLocator(new ServantLocatorI("category"), "category");
adapter.addServantLocator(new ServantLocatorI(""), "");
adapter.add(new TestI(), communicator().stringToIdentity("asm"));
adapter.add(new TestActivationI(), communicator().stringToIdentity("test/activation"));
AllTests.allTests(communicator(), true);
return 0;
}
}
public static int Main(string[] args)
{
App app = new App();
return app.main(args);
}
}
| sbesson/zeroc-ice | cs/test/Ice/servantLocator/Collocated.cs | C# | gpl-2.0 | 1,521 |
// 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.
// Based upon
// CDialogMinTrayBtn template class
// MFC CDialog with minimize to systemtray button (0.04a)
// Supports WinXP styles (thanks to David Yuheng Zhao for CVisualStylesXP - yuheng_zhao@yahoo.com)
//
// ------------------------------------------------------------
// DialogMinTrayBtn.hpp
// zegzav - 2002,2003 - eMule project (http://www.emule-project.net)
// ------------------------------------------------------------
//
// Modified by Tim Kosse (mailto:tim.kosse@gmx.de) for use within FileZilla
#include "StdAfx.h";
#include "MinTrayBtn.h"
#include "VisualStylesXP.h"
IMPLEMENT_DYNCREATE(CMinTrayBtn, CHookWnd);
// ------------------------------
// constants
// ------------------------------
#define CAPTION_BUTTONSPACE (2)
#define CAPTION_MINHEIGHT (8)
#define TIMERMINTRAYBTN_ID 0x76617a67
#define TIMERMINTRAYBTN_PERIOD 200 // ms
#define WP_TRAYBUTTON WP_MINBUTTON
BEGIN_TM_PART_STATES(TRAYBUTTON)
TM_STATE(1, TRAYBS, NORMAL)
TM_STATE(2, TRAYBS, HOT)
TM_STATE(3, TRAYBS, PUSHED)
TM_STATE(4, TRAYBS, DISABLED)
// Inactive
TM_STATE(5, TRAYBS, INORMAL)
TM_STATE(6, TRAYBS, IHOT)
TM_STATE(7, TRAYBS, IPUSHED)
TM_STATE(8, TRAYBS, IDISABLED)
END_TM_PART_STATES()
#define BMP_TRAYBTN_WIDTH (21)
#define BMP_TRAYBTN_HEIGHT (21)
#define BMP_TRAYBTN_BLUE _T("IDB_LUNA_BLUE")
#define BMP_TRAYBTN_METALLIC _T("IDB_LUNA_METALLIC")
#define BMP_TRAYBTN_HOMESTEAD _T("IDB_LUNA_HOMESTEAD")
#define BMP_TRAYBTN_TRANSCOLOR (RGB(255,0,255))
LPCTSTR CMinTrayBtn::m_pszMinTrayBtnBmpName[] = { BMP_TRAYBTN_BLUE, BMP_TRAYBTN_METALLIC, BMP_TRAYBTN_HOMESTEAD };
#define VISUALSTYLESXP_DEFAULTFILE L"LUNA.MSSTYLES"
#define VISUALSTYLESXP_BLUE 0
#define VISUALSTYLESXP_METALLIC 1
#define VISUALSTYLESXP_HOMESTEAD 2
#define VISUALSTYLESXP_NAMEBLUE L"NORMALCOLOR"
#define VISUALSTYLESXP_NAMEMETALLIC L"METALLIC"
#define VISUALSTYLESXP_NAMEHOMESTEAD L"HOMESTEAD"
// _WIN32_WINNT >= 0x0501 (XP only)
#define _WM_THEMECHANGED 0x031A
#define _ON_WM_THEMECHANGED() \
{ _WM_THEMECHANGED, 0, 0, 0, AfxSig_l, \
(AFX_PMSG)(AFX_PMSGW) \
(static_cast< LRESULT (AFX_MSG_CALL CWnd::*)(void) > (_OnThemeChanged)) \
},
// _WIN32_WINDOWS >= 0x0410 (95 not supported)
BOOL (WINAPI *CMinTrayBtn::_TransparentBlt)(HDC, int, int, int, int, HDC, int, int, int, int, UINT)= NULL;
// ------------------------------
// contructor/init
// ------------------------------
CMinTrayBtn::CMinTrayBtn(CWnd* pParentWnd) : CHookWnd(FALSE),
m_MinTrayBtnPos(0,0), m_MinTrayBtnSize(0,0), m_bMinTrayBtnEnabled(TRUE), m_bMinTrayBtnVisible(TRUE),
m_bMinTrayBtnUp(TRUE), m_bMinTrayBtnCapture(FALSE), m_bMinTrayBtnActive(FALSE), m_bMinTrayBtnHitTest(FALSE)
{
ASSERT(pParentWnd);
m_pOwner = pParentWnd;
m_hDLL = NULL;
MinTrayBtnInit();
}
CMinTrayBtn::~CMinTrayBtn()
{
if (m_hDLL)
FreeLibrary(m_hDLL);
}
void CMinTrayBtn::MinTrayBtnInit()
{
m_nMinTrayBtnTimerId = 0;
MinTrayBtnInitBitmap();
if (!_TransparentBlt)
{
m_hDLL = LoadLibrary(_T("MSIMG32.DLL"));
if (m_hDLL)
{
(FARPROC &)_TransparentBlt = GetProcAddress(m_hDLL, "TransparentBlt");
if (!_TransparentBlt)
{
FreeLibrary(m_hDLL);
m_hDLL = NULL;
}
}
}
}
// ------------------------------
// messages
// ------------------------------
void CMinTrayBtn::OnNcPaint()
{
MinTrayBtnUpdatePosAndSize();
MinTrayBtnDraw();
}
BOOL CMinTrayBtn::OnNcActivate(BOOL bActive)
{
MinTrayBtnUpdatePosAndSize();
m_bMinTrayBtnActive = bActive;
MinTrayBtnDraw();
return TRUE;
}
UINT CMinTrayBtn::OnNcHitTest(CPoint point)
{
BOOL bPreviousHitTest= m_bMinTrayBtnHitTest;
m_bMinTrayBtnHitTest= MinTrayBtnHitTest(point);
if ((!IsWindowsClassicStyle()) && (m_bMinTrayBtnHitTest != bPreviousHitTest))
MinTrayBtnDraw(); // Windows XP Style (hot button)
if (m_bMinTrayBtnHitTest)
return HTMINTRAYBUTTON;
return HTERROR;
}
BOOL CMinTrayBtn::OnNcLButtonDown(UINT nHitTest, CPoint point)
{
if ((m_pOwner->GetStyle() & WS_DISABLED) || (!MinTrayBtnIsEnabled()) || (!MinTrayBtnIsVisible()) || (!MinTrayBtnHitTest(point)))
{
return FALSE;
}
m_pOwner->SetCapture();
m_bMinTrayBtnCapture = TRUE;
MinTrayBtnSetDown();
return TRUE;
}
BOOL CMinTrayBtn::OnMouseMove(UINT nFlags, CPoint point)
{
if ((m_pOwner->GetStyle() & WS_DISABLED) || (!m_bMinTrayBtnCapture))
return FALSE;
m_pOwner->ClientToScreen(&point);
m_bMinTrayBtnHitTest= MinTrayBtnHitTest(point);
if (m_bMinTrayBtnHitTest)
{
if (m_bMinTrayBtnUp)
MinTrayBtnSetDown();
}
else
{
if (!m_bMinTrayBtnUp)
MinTrayBtnSetUp();
}
return TRUE;
}
BOOL CMinTrayBtn::OnLButtonUp(UINT nFlags, CPoint point)
{
if ((m_pOwner->GetStyle() & WS_DISABLED) || (!m_bMinTrayBtnCapture))
return FALSE;
ReleaseCapture();
m_bMinTrayBtnCapture = FALSE;
MinTrayBtnSetUp();
m_pOwner->ClientToScreen(&point);
if (MinTrayBtnHitTest(point))
m_pOwner->SendMessage(WM_SYSCOMMAND, SC_MINIMIZETRAY, MAKELONG(point.x, point.y));
return TRUE;
}
void CMinTrayBtn::OnThemeChanged()
{
MinTrayBtnInitBitmap();
}
// ------------------------------
// methods
// ------------------------------
void CMinTrayBtn::MinTrayBtnUpdatePosAndSize()
{
DWORD dwStyle = m_pOwner->GetStyle();
DWORD dwExStyle = m_pOwner->GetExStyle();
INT caption= ((dwExStyle & WS_EX_TOOLWINDOW) == 0) ? GetSystemMetrics(SM_CYCAPTION) - 1 : GetSystemMetrics(SM_CYSMCAPTION) - 1;
if (caption < CAPTION_MINHEIGHT)
caption= CAPTION_MINHEIGHT;
CSize borderfixed(-GetSystemMetrics(SM_CXFIXEDFRAME), GetSystemMetrics(SM_CYFIXEDFRAME));
CSize bordersize(-GetSystemMetrics(SM_CXSIZEFRAME), GetSystemMetrics(SM_CYSIZEFRAME));
CRect window;
m_pOwner->GetWindowRect(&window);
CSize button;
button.cy= caption - (CAPTION_BUTTONSPACE * 2);
button.cx= button.cy;
if (IsWindowsClassicStyle())
button.cx+= 2;
m_MinTrayBtnSize = button;
m_MinTrayBtnPos.x = window.Width() - ((CAPTION_BUTTONSPACE + button.cx) * 2);
m_MinTrayBtnPos.y = CAPTION_BUTTONSPACE;
if ((dwStyle & WS_THICKFRAME) != 0)
{
// resizable window
m_MinTrayBtnPos+= bordersize;
}
else
{
// fixed window
m_MinTrayBtnPos+= borderfixed;
}
if ( ((dwExStyle & WS_EX_TOOLWINDOW) == 0) && (((dwStyle & WS_MINIMIZEBOX) != 0) || ((dwStyle & WS_MAXIMIZEBOX) != 0)) )
{
if (IsWindowsClassicStyle())
m_MinTrayBtnPos.x-= (button.cx * 2) + CAPTION_BUTTONSPACE;
else
m_MinTrayBtnPos.x-= (button.cx + CAPTION_BUTTONSPACE) * 2;
}
}
void CMinTrayBtn::MinTrayBtnShow()
{
if (MinTrayBtnIsVisible())
return;
m_bMinTrayBtnVisible = TRUE;
if (m_pOwner->IsWindowVisible())
{
m_pOwner->RedrawWindow(NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW);
}
}
void CMinTrayBtn::MinTrayBtnHide()
{
if (!MinTrayBtnIsVisible())
return;
m_bMinTrayBtnVisible= FALSE;
if (m_pOwner->IsWindowVisible())
{
m_pOwner->RedrawWindow(NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW);
}
}
void CMinTrayBtn::MinTrayBtnEnable()
{
if (MinTrayBtnIsEnabled())
return;
m_bMinTrayBtnEnabled= TRUE;
MinTrayBtnSetUp();
}
void CMinTrayBtn::MinTrayBtnDisable()
{
if (!MinTrayBtnIsEnabled())
return;
m_bMinTrayBtnEnabled= FALSE;
if (m_bMinTrayBtnCapture)
{
ReleaseCapture();
m_bMinTrayBtnCapture= FALSE;
}
MinTrayBtnSetUp();
}
void CMinTrayBtn::MinTrayBtnDraw()
{
if (!MinTrayBtnIsVisible())
return;
CDC *pDC = m_pOwner->GetWindowDC();
if (!pDC)
return; // panic!
if (IsWindowsClassicStyle())
{
CBrush black(GetSysColor(COLOR_BTNTEXT));
CBrush gray(GetSysColor(COLOR_GRAYTEXT));
CBrush gray2(GetSysColor(COLOR_BTNHILIGHT));
// button
if (m_bMinTrayBtnUp)
pDC->DrawFrameControl(MinTrayBtnGetRect(), DFC_BUTTON, DFCS_BUTTONPUSH);
else
pDC->DrawFrameControl(MinTrayBtnGetRect(), DFC_BUTTON, DFCS_BUTTONPUSH | DFCS_PUSHED);
// dot
CRect btn= MinTrayBtnGetRect();
btn.DeflateRect(2,2);
UINT caption= MinTrayBtnGetSize().cy + (CAPTION_BUTTONSPACE * 2);
UINT pixratio= (caption >= 14) ? ((caption >= 20) ? 2 + ((caption - 20) / 8) : 2) : 1;
UINT pixratio2= (caption >= 12) ? 1 + (caption - 12) / 8: 0;
UINT dotwidth= (1 + pixratio * 3) >> 1;
UINT dotheight= pixratio;
CRect dot(CPoint(0,0), CPoint(dotwidth, dotheight));
CSize spc((1 + pixratio2 * 3) >> 1, pixratio2);
dot-= dot.Size();
dot+= btn.BottomRight();
dot-= spc;
if (!m_bMinTrayBtnUp)
dot+= CPoint(1,1);
if (m_bMinTrayBtnEnabled)
{
pDC->FillRect(dot, &black);
}
else
{
pDC->FillRect(dot + CPoint(1,1), &gray2);
pDC->FillRect(dot, &gray);
}
}
else
{
// VisualStylesXP
CRect btn = MinTrayBtnGetRect();
int iState;
if (!m_bMinTrayBtnEnabled)
iState= TRAYBS_DISABLED;
else if (m_pOwner->GetStyle() & WS_DISABLED)
iState= MINBS_NORMAL;
else if (m_bMinTrayBtnHitTest)
iState= (m_bMinTrayBtnCapture) ? MINBS_PUSHED : MINBS_HOT;
else
iState= MINBS_NORMAL;
// inactive
if (!m_bMinTrayBtnActive)
iState+= 4; // inactive state TRAYBS_Ixxx
if ((m_bmMinTrayBtnBitmap.m_hObject) && (_TransparentBlt))
{
// known theme (bitmap)
CBitmap *pBmpOld;
CDC dcMem;
if ((dcMem.CreateCompatibleDC(pDC)) && ((pBmpOld= dcMem.SelectObject(&m_bmMinTrayBtnBitmap)) != NULL))
{
_TransparentBlt(pDC->m_hDC, btn.left, btn.top, btn.Width(), btn.Height(), dcMem.m_hDC, 0, BMP_TRAYBTN_HEIGHT * (iState - 1), BMP_TRAYBTN_WIDTH, BMP_TRAYBTN_HEIGHT, BMP_TRAYBTN_TRANSCOLOR);
dcMem.SelectObject(pBmpOld);
}
}
else
{
// unknown theme (ThemeData)
HTHEME hTheme= g_xpStyle.OpenThemeData(m_pOwner->GetSafeHwnd(), L"Window");
if (hTheme)
{
btn.top+= btn.Height() / 8;
g_xpStyle.DrawThemeBackground(hTheme, pDC->m_hDC, WP_TRAYBUTTON, iState, &btn, NULL);
g_xpStyle.CloseThemeData(hTheme);
}
}
}
m_pOwner->ReleaseDC(pDC);
}
BOOL CMinTrayBtn::MinTrayBtnHitTest(CPoint point) const
{
CRect rWnd;
m_pOwner->GetWindowRect(&rWnd);
point.Offset(-rWnd.TopLeft());
CRect rBtn= MinTrayBtnGetRect();
rBtn.InflateRect(0, CAPTION_BUTTONSPACE);
return (rBtn.PtInRect(point));
}
void CMinTrayBtn::MinTrayBtnSetUp()
{
m_bMinTrayBtnUp= TRUE;
MinTrayBtnDraw();
}
void CMinTrayBtn::MinTrayBtnSetDown()
{
m_bMinTrayBtnUp = FALSE;
MinTrayBtnDraw();
}
BOOL CMinTrayBtn::IsWindowsClassicStyle() const
{
return (!((g_xpStyle.IsThemeActive()) && (g_xpStyle.IsAppThemed())));
}
INT CMinTrayBtn::GetVisualStylesXPColor() const
{
if (IsWindowsClassicStyle())
return -1;
WCHAR szwThemeFile[MAX_PATH];
WCHAR szwThemeColor[256];
if (g_xpStyle.GetCurrentThemeName(szwThemeFile, MAX_PATH, szwThemeColor, 256, NULL, 0) != S_OK)
return -1;
WCHAR *p;
if ((p= wcsrchr(szwThemeFile, '\\')) == NULL)
return -1;
p++;
if (_wcsicmp(p, VISUALSTYLESXP_DEFAULTFILE) != 0)
return -1;
if (_wcsicmp(szwThemeColor, VISUALSTYLESXP_NAMEBLUE) == 0)
return VISUALSTYLESXP_BLUE;
if (_wcsicmp(szwThemeColor, VISUALSTYLESXP_NAMEMETALLIC) == 0)
return VISUALSTYLESXP_METALLIC;
if (_wcsicmp(szwThemeColor, VISUALSTYLESXP_NAMEHOMESTEAD) == 0)
return VISUALSTYLESXP_HOMESTEAD;
return -1;
}
BOOL CMinTrayBtn::MinTrayBtnInitBitmap()
{
INT nColor;
m_bmMinTrayBtnBitmap.DeleteObject();
if ((nColor= GetVisualStylesXPColor()) == -1)
return FALSE;
const TCHAR *pszBmpName= m_pszMinTrayBtnBmpName[nColor];
BOOL res = m_bmMinTrayBtnBitmap.Attach(::LoadBitmap(AfxGetInstanceHandle(), pszBmpName));
return res;
}
#define WM_THEMECHANGED 0x031A
BOOL CMinTrayBtn::ProcessWindowMessage(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam, LRESULT& lResult)
{
switch (nMsg)
{
case WM_NCPAINT:
lResult = DefWindowProc(nMsg, wParam, lParam);
OnNcPaint();
return TRUE;
case WM_SETTEXT:
lResult = DefWindowProc(nMsg, wParam, lParam);
MinTrayBtnDraw();
return TRUE;
case WM_NCACTIVATE:
lResult = DefWindowProc(nMsg, wParam, lParam);
OnNcActivate(wParam);
return TRUE;
case WM_NCHITTEST:
{
lResult = (INT)OnNcHitTest(CPoint(lParam));
if (lResult == HTERROR)
lResult = DefWindowProc(nMsg, wParam, lParam);
}
return TRUE;
case WM_NCLBUTTONDOWN:
if (!OnNcLButtonDown(wParam, CPoint(lParam)))
lResult = DefWindowProc(nMsg, wParam, lParam);
else
lResult = 0;
return TRUE;
case WM_THEMECHANGED:
OnThemeChanged();
break;
case WM_MOUSEMOVE:
OnMouseMove(wParam, CPoint(lParam));
break;
case WM_LBUTTONUP:
if (OnLButtonUp(wParam, CPoint(lParam)))
lResult = 0;
else
lResult = DefWindowProc(nMsg, wParam, lParam);
return TRUE;
}
return FALSE;
}
| ChadSki/FeatherweightVirtualMachine | FVM_UI/fvmshell/misc/MinTrayBtn.cpp | C++ | gpl-2.0 | 13,862 |
package com.pcab.marvel.model;
/**
* Summary type used for creators.
*/
public class RoleSummary extends Summary {
/**
* The role in the parent entity.
*/
private String role;
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
| pablocabrera85/marvel-api-client | src/main/java/com/pcab/marvel/model/RoleSummary.java | Java | gpl-2.0 | 330 |
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: test_velocity_caps.cpp,v 1.2 2005/03/14 19:36:42 bobclark Exp $
*
* Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL") in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your version of
* this file only under the terms of the GPL, and not to allow others
* to use your version of this file under the terms of either the RPSL
* or RCSL, indicate your decision by deleting the provisions above
* and replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient may
* use your version of this file under the terms of any one of the
* RPSL, the RCSL or the GPL.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
#include "hxtypes.h"
#include "hxcom.h"
#include "hxplayvelocity.h"
#include "test_velocity_caps.h"
CHXPlaybackVelocityCapsTest::CHXPlaybackVelocityCapsTest()
{
m_ppCaps[0] = new CHXPlaybackVelocityCaps();
m_ppCaps[1] = new CHXPlaybackVelocityCaps();
}
CHXPlaybackVelocityCapsTest::~CHXPlaybackVelocityCapsTest()
{
HX_DELETE(m_ppCaps[0]);
HX_DELETE(m_ppCaps[1]);
}
void CHXPlaybackVelocityCapsTest::GetCommandInfo(UTVector<HLXUnitTestCmdInfo*>& cmds)
{
cmds.Resize(6);
cmds[0] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this,
"CHXPlaybackVelocityCaps()",
&CHXPlaybackVelocityCapsTest::HandleConstructorCmd,
2);
cmds[1] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this,
"GetNumRanges",
&CHXPlaybackVelocityCapsTest::HandleGetNumRangesCmd,
3);
cmds[2] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this,
"GetRange",
&CHXPlaybackVelocityCapsTest::HandleGetRangeCmd,
5);
cmds[3] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this,
"AddRange",
&CHXPlaybackVelocityCapsTest::HandleAddRangeCmd,
5);
cmds[4] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this,
"CombineCapsLogicalAnd",
&CHXPlaybackVelocityCapsTest::HandleCombineCapsLogicalAndCmd,
2);
cmds[5] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this,
"IsCapable",
&CHXPlaybackVelocityCapsTest::HandleIsCapableCmd,
4);
}
const char* CHXPlaybackVelocityCapsTest::DefaultCommandLine() const
{
return "test_velocity_caps test_velocity_caps.in -a";
}
HLXCmdBasedTest* CHXPlaybackVelocityCapsTest::Clone() const
{
return new CHXPlaybackVelocityCapsTest();
}
bool CHXPlaybackVelocityCapsTest::HandleConstructorCmd(const UTVector<UTString>& params)
{
bool bRet = false;
UINT32 ulIndex = strtoul(params[1], NULL, 10);
if (ulIndex < 2)
{
HX_DELETE(m_ppCaps[ulIndex]);
m_ppCaps[ulIndex] = new CHXPlaybackVelocityCaps();
if (m_ppCaps[ulIndex])
{
bRet = true;
}
}
return bRet;
}
bool CHXPlaybackVelocityCapsTest::HandleGetNumRangesCmd(const UTVector<UTString>& params)
{
bool bRet = false;
UINT32 ulIndex = strtoul(params[1], NULL, 10);
if (ulIndex < 2 && m_ppCaps[ulIndex])
{
UINT32 ulExpectedNum = strtoul(params[2], NULL, 10);
UINT32 ulActualNum = m_ppCaps[ulIndex]->GetNumRanges();
if (ulExpectedNum == ulActualNum)
{
bRet = true;
}
}
return bRet;
}
bool CHXPlaybackVelocityCapsTest::HandleGetRangeCmd(const UTVector<UTString>& params)
{
bool bRet = false;
UINT32 ulIndex = strtoul(params[1], NULL, 10);
if (ulIndex < 2 && m_ppCaps[ulIndex])
{
UINT32 ulRangeIndex = strtoul(params[2], NULL, 10);
INT32 lExpectedMin = (INT32) strtol(params[3], NULL, 10);
INT32 lExpectedMax = (INT32) strtol(params[4], NULL, 10);
INT32 lActualMin = 0;
INT32 lActualMax = 0;
HX_RESULT retVal = m_ppCaps[ulIndex]->GetRange(ulRangeIndex, lActualMin, lActualMax);
if (SUCCEEDED(retVal) &&
lExpectedMin == lActualMin &&
lExpectedMax == lActualMax)
{
bRet = true;
}
}
return bRet;
}
bool CHXPlaybackVelocityCapsTest::HandleAddRangeCmd(const UTVector<UTString>& params)
{
bool bRet = false;
UINT32 ulIndex = strtoul(params[1], NULL, 10);
if (ulIndex < 2 && m_ppCaps[ulIndex])
{
INT32 lMinToAdd = strtol(params[2], NULL, 10);
INT32 lMaxToAdd = strtol(params[3], NULL, 10);
UINT32 ulExpRet = strtoul(params[4], NULL, 10);
HX_RESULT retVal = m_ppCaps[ulIndex]->AddRange(lMinToAdd, lMaxToAdd);
if ((ulExpRet && SUCCEEDED(retVal)) ||
(!ulExpRet && FAILED(retVal)))
{
bRet = true;
}
}
return bRet;
}
bool CHXPlaybackVelocityCapsTest::HandleCombineCapsLogicalAndCmd(const UTVector<UTString>& params)
{
bool bRet = false;
UINT32 ulIndex = strtoul(params[1], NULL, 10);
if (ulIndex < 2 && m_ppCaps[0] && m_ppCaps[1])
{
UINT32 ulOtherIndex = (ulIndex == 0 ? 1 : 0);
HX_RESULT retVal = m_ppCaps[ulIndex]->CombineCapsLogicalAnd(m_ppCaps[ulOtherIndex]);
if (SUCCEEDED(retVal))
{
bRet = true;
}
}
return bRet;
}
bool CHXPlaybackVelocityCapsTest::HandleIsCapableCmd(const UTVector<UTString>& params)
{
bool bRet = false;
UINT32 ulIndex = strtoul(params[1], NULL, 10);
if (ulIndex < 2 && m_ppCaps[ulIndex])
{
INT32 lVelToCheck = strtol(params[2], NULL, 10);
UINT32 ulExpRet = strtoul(params[3], NULL, 10);
HXBOOL bExpRet = (ulExpRet ? TRUE : FALSE);
HXBOOL bActRet = m_ppCaps[ulIndex]->IsCapable(lVelToCheck);
if (bActRet == bExpRet)
{
bRet = true;
}
}
return bRet;
}
| muromec/qtopia-ezx | src/3rdparty/libraries/helix/src/common/util/test/test_velocity_caps.cpp | C++ | gpl-2.0 | 8,664 |
/***************************************************************************
kgpanel.cpp - description
-------------------
copyright : (C) 2003 by Csaba Karai
copyright : (C) 2010 by Jan Lepper
e-mail : krusader@users.sourceforge.net
web site : http://krusader.sourceforge.net
---------------------------------------------------------------------------
Description
***************************************************************************
A
db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b.
88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D
88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY'
88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b
88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88.
YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD
S o u r c e F i l e
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "kgpanel.h"
#include "../defaults.h"
#include "../Dialogs/krdialogs.h"
#include <QtGui/QTabWidget>
#include <QFrame>
#include <QGridLayout>
#include <QLabel>
#include <QVBoxLayout>
#include <klocale.h>
#include <QtGui/QValidator>
#include <kmessagebox.h>
#include <kfiledialog.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include "viewtype.h"
#include "viewfactory.h"
#include "module.h"
#include "viewconfigui.h"
#include "../krusaderapp.h"
#include "../Panel/krlayoutfactory.h"
enum {
PAGE_MISC = 0,
PAGE_VIEW,
PAGE_PANELTOOLBAR,
PAGE_MOUSE,
PAGE_MEDIA_MENU,
PAGE_LAYOUT
};
KgPanel::KgPanel(bool first, QWidget* parent) :
KonfiguratorPage(first, parent)
{
tabWidget = new QTabWidget(this);
setWidget(tabWidget);
setWidgetResizable(true);
setupMiscTab();
setupPanelTab();
setupButtonsTab();
setupMouseModeTab();
setupMediaMenuTab();
setupLayoutTab();
}
ViewConfigUI *KgPanel::viewConfigUI()
{
ViewConfigUI *viewCfg = qobject_cast<ViewConfigUI*>(KrusaderApp::self()->module("View"));
Q_ASSERT(viewCfg);
return viewCfg;
}
// ---------------------------------------------------------------------------------------
// ---------------------------- Misc TAB ------------------------------------------------
// ---------------------------------------------------------------------------------------
void KgPanel::setupMiscTab()
{
QScrollArea *scrollArea = new QScrollArea(tabWidget);
QWidget *tab = new QWidget(scrollArea);
scrollArea->setFrameStyle(QFrame::NoFrame);
scrollArea->setWidget(tab);
scrollArea->setWidgetResizable(true);
tabWidget->addTab(scrollArea, i18n("General"));
QVBoxLayout *miscLayout = new QVBoxLayout(tab);
miscLayout->setSpacing(6);
miscLayout->setContentsMargins(11, 11, 11, 11);
// ---------------------------------------------------------------------------------------
// ------------------------------- Address Bar -------------------------------------------
// ---------------------------------------------------------------------------------------
QGroupBox *miscGrp = createFrame(i18n("Address bar"), tab);
QGridLayout *miscGrid = createGridLayout(miscGrp);
KONFIGURATOR_CHECKBOX_PARAM general_settings[] = { // cfg_class, cfg_name, default, text, restart, tooltip
{"Look&Feel", "FlatOriginBar", _FlatOriginBar, i18n("Flat address bar"), true, 0 },
{"Look&Feel", "ShortenHomePath", _ShortenHomePath, i18n("Shorten home path"), true, i18n("Display home path as \"~\"") },
};
KonfiguratorCheckBoxGroup *cbs = createCheckBoxGroup(2, 0, general_settings, 2 /*count*/, miscGrp, PAGE_MISC);
cbs->find("FlatOriginBar")->addDep(cbs->find("ShortenHomePath"));
miscGrid->addWidget(cbs, 0, 0);
miscLayout->addWidget(miscGrp);
// ---------------------------------------------------------------------------------------
// ------------------------------- Operation ---------------------------------------------
// ---------------------------------------------------------------------------------------
miscGrp = createFrame(i18n("Operation"), tab);
miscGrid = createGridLayout(miscGrp);
KONFIGURATOR_CHECKBOX_PARAM operation_settings[] = { // cfg_class, cfg_name, default, text, restart, tooltip
{"Look&Feel", "Mark Dirs", _MarkDirs, i18n("Autoselect directories"), false, i18n("When matching the select criteria, not only files will be selected, but also directories.") },
{"Look&Feel", "Rename Selects Extension", true, i18n("Rename selects extension"), false, i18n("When renaming a file, the whole text is selected. If you want Total-Commander like renaming of just the name, without extension, uncheck this option.") },
{"Look&Feel", "UnselectBeforeOperation", _UnselectBeforeOperation, i18n("Unselect files before copy/move"), false, i18n("Unselect files, which are to be copied/moved, before the operation starts.") },
{"Look&Feel", "FilterDialogRemembersSettings", _FilterDialogRemembersSettings, i18n("Filter dialog remembers settings"), false, i18n("The filter dialog is opened with the last filter settings that where applied to the panel.") },
};
cbs = createCheckBoxGroup(2, 0, operation_settings, 4 /*count*/, miscGrp, PAGE_MISC);
miscGrid->addWidget(cbs, 0, 0);
miscLayout->addWidget(miscGrp);
// ---------------------------------------------------------------------------------------
// ------------------------------ Tabs ---------------------------------------------------
// ---------------------------------------------------------------------------------------
miscGrp = createFrame(i18n("Tabs"), tab);
miscGrid = createGridLayout(miscGrp);
KONFIGURATOR_CHECKBOX_PARAM tabbar_settings[] = { // cfg_class cfg_name default text restart tooltip
{"Look&Feel", "Fullpath Tab Names", _FullPathTabNames, i18n("Use full path tab names"), true , i18n("Display the full path in the folder tabs. By default only the last part of the path is displayed.") },
{"Look&Feel", "Show Tab Buttons", true, i18n("Show new/close tab buttons"), true , i18n("Show the new/close tab buttons") },
};
cbs = createCheckBoxGroup(2, 0, tabbar_settings, 2 /*count*/, miscGrp, PAGE_MISC);
miscGrid->addWidget(cbs, 0, 0);
// ----------------- Tab Bar position ----------------------------------
QHBoxLayout *hbox = new QHBoxLayout();
hbox->addWidget(new QLabel(i18n("Tab Bar position:"), miscGrp));
KONFIGURATOR_NAME_VALUE_PAIR positions[] = {{ i18n("Top"), "top" },
{ i18n("Bottom"), "bottom" }
};
KonfiguratorComboBox *cmb = createComboBox("Look&Feel", "Tab Bar Position",
"bottom", positions, 2, miscGrp, true, false, PAGE_MISC);
hbox->addWidget(cmb);
hbox->addWidget(createSpacer(miscGrp));
miscGrid->addLayout(hbox, 1, 0);
miscLayout->addWidget(miscGrp);
// ---------------------------------------------------------------------------------------
// ----------------------------- Quicksearch -------------------------------------------
// ---------------------------------------------------------------------------------------
miscGrp = createFrame(i18n("Quicksearch/Quickfilter"), tab);
miscGrid = createGridLayout(miscGrp);
KONFIGURATOR_CHECKBOX_PARAM quicksearch[] = { // cfg_class cfg_name default text restart tooltip
{"Look&Feel", "New Style Quicksearch", _NewStyleQuicksearch, i18n("New style Quicksearch"), false, i18n("Opens a quick search dialog box.") },
{"Look&Feel", "Case Sensitive Quicksearch", _CaseSensitiveQuicksearch, i18n("Case sensitive Quicksearch/QuickFilter"), false, i18n("All files beginning with capital letters appear before files beginning with non-capital letters (UNIX default).") },
{"Look&Feel", "Up/Down Cancels Quicksearch", false, i18n("Up/Down cancels Quicksearch"), false, i18n("Pressing the Up/Down buttons cancels Quicksearch.") },
};
quicksearchCheckboxes = createCheckBoxGroup(2, 0, quicksearch, 3 /*count*/, miscGrp, PAGE_MISC);
miscGrid->addWidget(quicksearchCheckboxes, 0, 0);
connect(quicksearchCheckboxes->find("New Style Quicksearch"), SIGNAL(stateChanged(int)), this, SLOT(slotDisable()));
slotDisable();
// -------------- Quicksearch position -----------------------
hbox = new QHBoxLayout();
hbox->addWidget(new QLabel(i18n("Position:"), miscGrp));
cmb = createComboBox("Look&Feel", "Quicksearch Position",
"bottom", positions, 2, miscGrp, true, false, PAGE_MISC);
hbox->addWidget(cmb);
hbox->addWidget(createSpacer(miscGrp));
miscGrid->addLayout(hbox, 1, 0);
miscLayout->addWidget(miscGrp);
// --------------------------------------------------------------------------------------------
// ------------------------------- Status/Totalsbar settings ----------------------------------
// --------------------------------------------------------------------------------------------
miscGrp = createFrame(i18n("Status/Totalsbar"), tab);
miscGrid = createGridLayout(miscGrp);
KONFIGURATOR_CHECKBOX_PARAM barSettings[] =
{
{"Look&Feel", "Show Size In Bytes", true, i18n("Show size in bytes too"), true, i18n("Show size in bytes too") },
{"Look&Feel", "ShowSpaceInformation", true, i18n("Show space information"), true, i18n("Show free/total space on the device") },
};
KonfiguratorCheckBoxGroup *barSett = createCheckBoxGroup(2, 0, barSettings,
2 /*count*/, miscGrp, PAGE_MISC);
miscGrid->addWidget(barSett, 1, 0, 1, 2);
miscLayout->addWidget(miscGrp);
}
// --------------------------------------------------------------------------------------------
// ------------------------------------ Layout Tab --------------------------------------------
// --------------------------------------------------------------------------------------------
void KgPanel::setupLayoutTab()
{
QScrollArea *scrollArea = new QScrollArea(tabWidget);
QWidget *tab = new QWidget(scrollArea);
scrollArea->setFrameStyle(QFrame::NoFrame);
scrollArea->setWidget(tab);
scrollArea->setWidgetResizable(true);
tabWidget->addTab(scrollArea, i18n("Layout"));
QGridLayout *grid = createGridLayout(tab);
QStringList layoutNames = KrLayoutFactory::layoutNames();
int numLayouts = layoutNames.count();
grid->addWidget(createSpacer(tab), 0, 2);
QLabel *l = new QLabel(i18n("Layout:"), tab);
l->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
grid->addWidget(l, 0, 0);
KONFIGURATOR_NAME_VALUE_PAIR *layouts = new KONFIGURATOR_NAME_VALUE_PAIR[numLayouts];
for (int i = 0; i != numLayouts; i++) {
layouts[ i ].text = KrLayoutFactory::layoutDescription(layoutNames[i]);
layouts[ i ].value = layoutNames[i];
}
KonfiguratorComboBox *cmb = createComboBox("PanelLayout", "Layout", "default",
layouts, numLayouts, tab, true, false, PAGE_LAYOUT);
grid->addWidget(cmb, 0, 1);
delete [] layouts;
l = new QLabel(i18n("Frame Color:"), tab);
l->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
grid->addWidget(l, 1, 0);
KONFIGURATOR_NAME_VALUE_PAIR frameColor[] = {
{ i18nc("Frame color", "Defined by Layout"), "default" },
{ i18nc("Frame color", "None"), "none" },
{ i18nc("Frame color", "Statusbar"), "Statusbar" }
};
cmb = createComboBox("PanelLayout", "FrameColor",
"default", frameColor, 3, tab, true, false, PAGE_LAYOUT);
grid->addWidget(cmb, 1, 1);
l = new QLabel(i18n("Frame Shape:"), tab);
l->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
grid->addWidget(l, 2, 0);
KONFIGURATOR_NAME_VALUE_PAIR frameShape[] = {
{ i18nc("Frame shape", "Defined by Layout"), "default" },
{ i18nc("Frame shape", "None"), "NoFrame" },
{ i18nc("Frame shape", "Box"), "Box" },
{ i18nc("Frame shape", "Panel"), "Panel" },
};
cmb = createComboBox("PanelLayout", "FrameShape",
"default", frameShape, 4, tab, true, false, PAGE_LAYOUT);
grid->addWidget(cmb, 2, 1);
l = new QLabel(i18n("Frame Shadow:"), tab);
l->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
grid->addWidget(l, 3, 0);
KONFIGURATOR_NAME_VALUE_PAIR frameShadow[] = {
{ i18nc("Frame shadow", "Defined by Layout"), "default" },
{ i18nc("Frame shadow", "None"), "Plain" },
{ i18nc("Frame shadow", "Raised"), "Raised" },
{ i18nc("Frame shadow", "Sunken"), "Sunken" },
};
cmb = createComboBox("PanelLayout", "FrameShadow",
"default", frameShadow, 4, tab, true, false, PAGE_LAYOUT);
grid->addWidget(cmb, 3, 1);
}
// ----------------------------------------------------------------------------------
// ---------------------------- VIEW TAB -------------------------------------------
// ----------------------------------------------------------------------------------
void KgPanel::setupPanelTab()
{
QScrollArea *scrollArea = new QScrollArea(tabWidget);
scrollArea->setFrameStyle(QFrame::NoFrame);
scrollArea->setWidgetResizable(true);
QWidget *tab_panel = viewConfigUI()->createViewCfgTab(scrollArea, this, PAGE_VIEW);
scrollArea->setWidget(tab_panel);
tabWidget->addTab(scrollArea, i18n("View"));
}
// -----------------------------------------------------------------------------------
// -------------------------- Panel Toolbar TAB ----------------------------------
// -----------------------------------------------------------------------------------
void KgPanel::setupButtonsTab()
{
QScrollArea *scrollArea = new QScrollArea(tabWidget);
QWidget *tab = new QWidget(scrollArea);
scrollArea->setFrameStyle(QFrame::NoFrame);
scrollArea->setWidget(tab);
scrollArea->setWidgetResizable(true);
tabWidget->addTab(scrollArea, i18n("Buttons"));
QBoxLayout * tabLayout = new QVBoxLayout(tab);
tabLayout->setSpacing(6);
tabLayout->setContentsMargins(11, 11, 11, 11);
KONFIGURATOR_CHECKBOX_PARAM buttonsParams[] =
// cfg_class cfg_name default text restart tooltip
{
{"ListPanelButtons", "Icons", false, i18n("Toolbar buttons have icons"), true, "" },
{"Look&Feel", "Media Button Visible", true, i18n("Show Media Button"), true , i18n("The media button will be visible.") },
{"Look&Feel", "Back Button Visible", false, i18n("Show Back Button"), true , "Goes back in history." },
{"Look&Feel", "Forward Button Visible", false, i18n("Show Forward Button"), true , "Goes forward in history." },
{"Look&Feel", "History Button Visible", true, i18n("Show History Button"), true , i18n("The history button will be visible.") },
{"Look&Feel", "Bookmarks Button Visible", true, i18n("Show Bookmarks Button"), true , i18n("The bookmarks button will be visible.") },
{"Look&Feel", "Panel Toolbar visible", _PanelToolBar, i18n("Show Panel Toolbar"), true, i18n("The panel toolbar will be visible.") },
};
buttonsCheckboxes = createCheckBoxGroup(1, 0, buttonsParams, 7/*count*/, tab, PAGE_PANELTOOLBAR);
connect(buttonsCheckboxes->find("Panel Toolbar visible"), SIGNAL(stateChanged(int)), this, SLOT(slotEnablePanelToolbar()));
tabLayout->addWidget(buttonsCheckboxes, 0, 0);
QGroupBox * panelToolbarGrp = createFrame(i18n("Visible Panel Toolbar buttons"), tab);
QGridLayout * panelToolbarGrid = createGridLayout(panelToolbarGrp);
KONFIGURATOR_CHECKBOX_PARAM panelToolbarButtonsParams[] = {
// cfg_class cfg_name default text restart tooltip
{"Look&Feel", "Open Button Visible", _Open, i18n("Open button"), true , i18n("Opens the directory browser.") },
{"Look&Feel", "Equal Button Visible", _cdOther, i18n("Equal button (=)"), true , i18n("Changes the panel directory to the other panel directory.") },
{"Look&Feel", "Up Button Visible", _cdUp, i18n("Up button (..)"), true , i18n("Changes the panel directory to the parent directory.") },
{"Look&Feel", "Home Button Visible", _cdHome, i18n("Home button (~)"), true , i18n("Changes the panel directory to the home directory.") },
{"Look&Feel", "Root Button Visible", _cdRoot, i18n("Root button (/)"), true , i18n("Changes the panel directory to the root directory.") },
{"Look&Feel", "SyncBrowse Button Visible", _syncBrowseButton, i18n("Toggle-button for sync-browsing"), true , i18n("Each directory change in the panel is also performed in the other panel.") },
};
panelToolbarButtonsCheckboxes = createCheckBoxGroup(1, 0, panelToolbarButtonsParams,
sizeof(panelToolbarButtonsParams) / sizeof(*panelToolbarButtonsParams),
panelToolbarGrp, PAGE_PANELTOOLBAR);
panelToolbarGrid->addWidget(panelToolbarButtonsCheckboxes, 0, 0);
tabLayout->addWidget(panelToolbarGrp, 1, 0);
// Enable panel toolbar checkboxes
slotEnablePanelToolbar();
}
// ---------------------------------------------------------------------------
// -------------------------- Mouse TAB ----------------------------------
// ---------------------------------------------------------------------------
void KgPanel::setupMouseModeTab()
{
QScrollArea *scrollArea = new QScrollArea(tabWidget);
scrollArea->setFrameStyle(QFrame::NoFrame);
scrollArea->setWidgetResizable(true);
QWidget *tab_mouse = viewConfigUI()->createSelectionModeCfgTab(scrollArea, this, PAGE_MOUSE);
scrollArea->setWidget(tab_mouse);
tabWidget->addTab(scrollArea, i18n("Selection Mode"));
}
// ---------------------------------------------------------------------------
// -------------------------- Media Menu TAB ----------------------------------
// ---------------------------------------------------------------------------
void KgPanel::setupMediaMenuTab()
{
QScrollArea *scrollArea = new QScrollArea(tabWidget);
QWidget *tab = new QWidget(scrollArea);
scrollArea->setFrameStyle(QFrame::NoFrame);
scrollArea->setWidget(tab);
scrollArea->setWidgetResizable(true);
tabWidget->addTab(scrollArea, i18n("Media Menu"));
QBoxLayout * tabLayout = new QVBoxLayout(tab);
tabLayout->setSpacing(6);
tabLayout->setContentsMargins(11, 11, 11, 11);
KONFIGURATOR_CHECKBOX_PARAM mediaMenuParams[] = {
// cfg_class cfg_name default text restart tooltip
{"MediaMenu", "ShowPath", true, i18n("Show Mount Path"), false, 0 },
{"MediaMenu", "ShowFSType", true, i18n("Show File System Type"), false, 0 },
};
KonfiguratorCheckBoxGroup *mediaMenuCheckBoxes =
createCheckBoxGroup(1, 0, mediaMenuParams,
sizeof(mediaMenuParams) / sizeof(*mediaMenuParams),
tab, PAGE_MEDIA_MENU);
tabLayout->addWidget(mediaMenuCheckBoxes, 0, 0);
QHBoxLayout *showSizeHBox = new QHBoxLayout();
showSizeHBox->addWidget(new QLabel(i18n("Show Size:"), tab));
KONFIGURATOR_NAME_VALUE_PAIR showSizeValues[] = {
{ i18nc("setting 'show size'", "Always"), "Always" },
{ i18nc("setting 'show size'", "When Device has no Label"), "WhenNoLabel" },
{ i18nc("setting 'show size'", "Never"), "Never" },
};
KonfiguratorComboBox *showSizeCmb =
createComboBox("MediaMenu", "ShowSize",
"Always", showSizeValues,
sizeof(showSizeValues) / sizeof(*showSizeValues),
tab, false, false, PAGE_MEDIA_MENU);
showSizeHBox->addWidget(showSizeCmb);
showSizeHBox->addStretch();
tabLayout->addLayout(showSizeHBox);
tabLayout->addStretch();
}
void KgPanel::slotDisable()
{
bool isNewStyleQuickSearch = quicksearchCheckboxes->find("New Style Quicksearch")->isChecked();
quicksearchCheckboxes->find("Case Sensitive Quicksearch")->setEnabled(isNewStyleQuickSearch);
}
void KgPanel::slotEnablePanelToolbar()
{
bool enableTB = buttonsCheckboxes->find("Panel Toolbar visible")->isChecked();
panelToolbarButtonsCheckboxes->find("Root Button Visible")->setEnabled(enableTB);
panelToolbarButtonsCheckboxes->find("Home Button Visible")->setEnabled(enableTB);
panelToolbarButtonsCheckboxes->find("Up Button Visible")->setEnabled(enableTB);
panelToolbarButtonsCheckboxes->find("Equal Button Visible")->setEnabled(enableTB);
panelToolbarButtonsCheckboxes->find("Open Button Visible")->setEnabled(enableTB);
panelToolbarButtonsCheckboxes->find("SyncBrowse Button Visible")->setEnabled(enableTB);
}
int KgPanel::activeSubPage()
{
return tabWidget->currentIndex();
}
| amatveyakin/skuire | krusader/Konfigurator/kgpanel.cpp | C++ | gpl-2.0 | 21,856 |
var v = "题库题数:1546(2015.05.09更新)";
alert("脚本加载完成。\n如果您为使用此脚本支付了任何费用,那么恭喜您,您被坑了。\n\n按确定开始执行。");
var allQ = [];
$(".examLi").each(function(){
allQ.push($(this).text());
});
var counter = 0;
for(var i = 1; i <= 20; i++){
var thisQ = allQ[i].split(" ");
var q = thisQ[64].substring(0, thisQ[64].length - 1); //问题
//答案
var a = [];
for(var ii = 112; ii <= 172; ii += 20){
a.push(thisQ[ii].substring(1, thisQ[ii].length - 1));
}
var rightA = getAns(q); //获取正确答案
if(a.indexOf(rightA) > -1){
$(".examLi").eq(i) //找到正确的题
.find("li").eq(a.indexOf(rightA)) //找到正确的选项
.addClass("currSolution"); //选择选项
}else{
counter += 1;
if(rightA !== undefined){ //题库错误处理
alert("题库错误!\n问题:\"" + q + "\"\n返回的答案:\"" + rightA + "\"\n捕获的答案列表:" + a);
}
}
}
alert("答题完成,有" + counter +"道题没填写(题库中没有或返回的答案无效)。")
//题库函数
function getAns (q){
// 79 = 79
switch(q){
case "以下哪一位数学家不是法国人?": return ".黎曼";
case "当PCl5 = PCl3 +Cl2的化学平衡常数Kc=1.8M时,在0.5L的容器中加入0.15molPCl5,求平衡后Cl2的浓度": return ".0.26M";
case "以下哪种颜色不属于色光三原色?": return ".黄";
case "iphone 4之后苹果推出的手机是": return ".iphone 4S";
case "c++的int类型通常占用几个字节?": return "4(byte)";
case "冥王星的公转周期?": return ".248地球年";
case "世界上用图像显示的第一个电子游戏是什么?": return ".Core War";
case "AIDS的全称是什么?": return ".获得性免疫缺陷综合征";
case "计算机编程中常见的if语句是?": return ".判断语句";
case "风靡一时的游戏主机“红白机”全名为?": return ".Family Computer";
case "当天空出现了鱼鳞云(透光高积云),下列哪种天气现象会发生?": return ".降雨";
case "一直被拿去做实验从未被超越的动物是": return ".小白鼠";
case "以下作品中哪一个完全没有使用3D技术": return ".LOVELIVE TV版";
case "以下哪款耳机采用了特斯拉技术": return ".拜亚T1";
case "美国历史上第一位黑人总统是": return ".Barack Hussein Obama II";
case "以下哪种功率放大器效率最低?": return ".甲类";
case "RGBA中的A是指?": return ".Alpha";
case "“不学礼,无以立”。出于何处?": return ".《论语》";
case "静电场的高斯定理和环路定理说明静电场是个什么场?": return ".有源有旋场";
case "新生物性状产生的根本原因在于?": return ".基因重组";
case "一个农田的全部生物属于?": return ".群落";
case "北回归线没有从下列哪个省中穿过?": return ".福建";
case "什么是“DTS”": return ".数字家庭影院系统";
case "被誉为生命科学“登月”计划的是": return ".人类基因组计划";
case "下列有关电子显微镜的说法正确的是": return ".常用的有透射电镜和扫描电子镜";
case "天文学上,红移是指": return ".天体离我们远去";
case "传说中从天而降砸到牛顿的是": return ".苹果";
case "拿破仑在从厄尔巴岛逃回法国,到兵败滑铁卢再次流放,一共重返帝位多少天?": return ".101";
case "剧毒NaCN(氰化钠)的水解产物HCN是什么味道": return ".苦杏仁味";
case "金鱼的卵什么颜色的才能孵化": return ".淡青色";
default: return undefined;
}} //结束switch和题库函数
} //结束运行确认
| mobaobaoss/mobaobaoss.github.io | timu1.js | JavaScript | gpl-2.0 | 3,742 |
package net.kolls.railworld.play;
/*
* Copyright (C) 2010 Steve Kollmansberger
*
* 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.
*/
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Vector;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.WindowConstants;
import net.kolls.railworld.Car;
import net.kolls.railworld.Factories;
import net.kolls.railworld.Images;
import net.kolls.railworld.RailSegment;
import net.kolls.railworld.Train;
import net.kolls.railworld.car.Caboose;
import net.kolls.railworld.car.Engine;
import net.kolls.railworld.play.script.ScriptManager;
import net.kolls.railworld.segment.EESegment;
import net.kolls.railworld.segment.LUSegment;
import net.kolls.railworld.tuic.TrainPainter;
/**
* Provides a window allowing the user to create a train to enter the map.
*
* @author Steve Kollmansberger
*
*/
public class TrainCreator extends JFrame {
private JPanel loaded, unloaded, nonload;
private MultiLineTrainPanel ctrain;
private Vector<EESegment> ees;
private PlayFrame pf;
private JComboBox enters, speeds;
private final int incr = Train.MAX_SPEED_MPH / Train.MAX_THROTTLE;
private Map<String,Car> sc;
/**
* Generate a series of engines, cargo cars, and possibly a caboose
* based on possible cargo cars.
*
* @param r Random number source
* @param engine The template car for the engine, e.g. to allow derived engine types
* @param sources Array of allowable cargo cars
* @return Train cars
*/
public static Car[] generate(Random r, Car engine, Car[] sources) {
int leng = r.nextInt(20)+2;
int occurs;
int i, j;
ArrayList<Car> results = new ArrayList<Car>();
int l2 = leng;
while (l2 > 1 && results.size() < 3) {
results.add( (Car)engine.newInstance());
l2 /= r.nextInt(5)+1;
}
if (sources.length == 0) return results.toArray(new Car[0]);
while (results.size() < leng) {
occurs = r.nextInt(4)+1;
i = r.nextInt(sources.length);
for (j = 0; j < occurs; j++) {
try {
Car c2 = (Car)sources[i].newInstance();
if (sources[i].loaded()) c2.load(); else c2.unload();
results.add(c2);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
if ((double)leng / 20 > r.nextDouble())
results.add(new Caboose());
return results.toArray(new Car[0]);
}
private void generate() {
Random r = new Random();
Car[] cars = sc.values().toArray(new Car[0]);
Car[] resultCars = generate(r, new Engine(), cars);
for (Car c : resultCars)
ctrain.myVC.add(c);
}
private JButton carButton(final Car c) {
String d = c.show();
Icon i = new ImageIcon(TrainPainter.image(c, this));
JButton j = new JButton(d,i);
j.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// because of the way the cars are added to the train
// we have to have separate instances for each car
// because a referencer is just copied
// so it's actually many of the same car otherwise
// this does create a problem for selected cars
try {
Car c2 = (Car)c.newInstance();
if (c.loaded()) c2.load(); else c2.unload();
ctrain.myVC.add(c2);
} catch (Exception ex) {
ex.printStackTrace();
}
ctrain.revalidate();
ctrain.repaint();
}
});
return j;
}
private void addLUButton(Car c) {
c.load();
loaded.add(carButton(c));
// in order to have a loaded and unloaded car
// separately, we need to have two instances
try {
Car c2 = (Car)c.newInstance();
c2.unload();
unloaded.add(carButton(c2));
} catch (Exception e) {
e.printStackTrace();
}
}
private void addWidgets() {
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
JTabbedPane tabbedPane = new JTabbedPane();
nonload = new JPanel();
loaded = new JPanel();
unloaded = new JPanel();
nonload.setLayout(new GridLayout(0,2));
loaded.setLayout(new GridLayout(0,2));
unloaded.setLayout(new GridLayout(0,2));
ArrayList<Car> at = Factories.cars.allTypes();
for (int i = 0; i < at.size(); i++) {
Car c = at.get(i);
if (c.canUserCreate() == false) continue;
if (c.isLoadable()) {
addLUButton(c);
} else {
nonload.add(carButton(c));
}
}
tabbedPane.add("Special", nonload);
tabbedPane.add("Loaded", loaded);
tabbedPane.add("Unloaded", unloaded);
getContentPane().add(tabbedPane);
ctrain = new MultiLineTrainPanel();
getContentPane().add(ctrain);
// create the combo boxes
// for selecting entrance and speed
JPanel hp = new JPanel();
hp.setLayout(new BoxLayout(hp, BoxLayout.X_AXIS));
hp.add(new JLabel("Entering At"));
hp.add(Box.createHorizontalGlue());
enters = new JComboBox();
Iterator<EESegment> ei = ees.iterator();
while (ei.hasNext()) {
EESegment ee = ei.next();
enters.addItem(ee.label);
}
hp.add(enters);
getContentPane().add(hp);
hp = new JPanel();
hp.setLayout(new BoxLayout(hp, BoxLayout.X_AXIS));
hp.add(new JLabel("Speed"));
hp.add(Box.createHorizontalGlue());
speeds = new JComboBox();
int i;
for (i = 1; i <= Train.MAX_THROTTLE; i++) {
speeds.addItem(Integer.toString(i*incr) + " MPH");
}
speeds.setSelectedIndex(i-2); // due to starting at 1
hp.add(speeds);
getContentPane().add(hp);
hp = new JPanel();
hp.setLayout(new BoxLayout(hp, BoxLayout.X_AXIS));
JButton b;
b = new JButton("OK");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (ctrain.myVC.isEmpty()) {
// cancel, no cars
dispose();
return;
}
Car[] cr = (ctrain.myVC.toArray(new Car[0]));
Train t = new Train(cr);
if (t.hasEngine())
t.setThrottle(speeds.getSelectedIndex()+1);
t.setVel(incr*(speeds.getSelectedIndex()+1)); // avoid acceleration wait
// also if there are no engines, the train
// would ever be stuck on the border
EESegment ee = ees.get(enters.getSelectedIndex());
t.pos.r = ee;
t.pos.orig = ee.HES;
t.followMeOnce = true;
t.getController().setTrainActionScriptNotify(sm);
pf.addTrain(t, true);
dispose(); // close window when done
}
});
hp.add(Box.createHorizontalGlue());
hp.add(b);
hp.add(Box.createHorizontalGlue());
b = new JButton("Clear");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ctrain.myVC.clear();
ctrain.revalidate();
getContentPane().repaint();
}
});
hp.add(b);
hp.add(Box.createHorizontalGlue());
b = new JButton("Generate");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ctrain.myVC.clear();
generate();
ctrain.revalidate();
getContentPane().repaint();
}
});
hp.add(b);
hp.add(Box.createHorizontalGlue());
b = new JButton("Cancel");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
hp.add(b);
hp.add(Box.createHorizontalGlue());
getContentPane().add(hp);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
pack();
}
private ScriptManager sm;
/**
* Shows the train creator window.
* The rail segments are needed for the generator to know what load/unload cars are supported.
* When created, the train will be added to the given trains collection automatically.
*
* @param lines An array of {@link RailSegment}s used for the train generator.
* @param pf PlayFrame by which the {@link PlayFrame#addTrain(Train, boolean)} method will be called.
* @param trainNotify The script manager to attach to the traincontroller for notification.
*/
public TrainCreator(RailSegment[] lines, PlayFrame pf, ScriptManager trainNotify) {
super("New Train");
setIconImage(Images.frameIcon);
// need to find all EE segments
// and lu segments for generator
ees = new Vector<EESegment>();
sc = new HashMap<String,Car>();
for (int i = 0; i < lines.length; i++) {
if (lines[i] instanceof EESegment)
ees.add((EESegment)lines[i]);
if (lines[i] instanceof LUSegment) {
Car[] cl = ((LUSegment)lines[i]).lu();
for (int j = 0; j < cl.length; j++)
sc.put(cl[j].show() + (cl[j].loaded() ? "/L" : "/U"), cl[j]);
}
}
this.pf = pf;
sm = trainNotify;
addWidgets();
}
}
| Neschur/railworld | src/net/kolls/railworld/play/TrainCreator.java | Java | gpl-2.0 | 9,483 |
<?php
/**
* @version CVS: 1.0.0
* @package Com_Propertycontact
* @author azharuddin <azharuddin.shaikh53@gmail.com>
* @copyright 2017 azharuddin
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
// Include dependancies
jimport('joomla.application.component.controller');
JLoader::registerPrefix('Propertycontact', JPATH_COMPONENT);
JLoader::register('PropertycontactController', JPATH_COMPONENT . '/controller.php');
// Execute the task.
$controller = JControllerLegacy::getInstance('Propertycontact');
$controller->execute(JFactory::getApplication()->input->get('task'));
$controller->redirect();
| azharu53/kuwithome | components/com_propertycontact/propertycontact.php | PHP | gpl-2.0 | 676 |
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public License
* Version 1.0 (the "NPL"); you may not use this file except in
* compliance with the NPL. You may obtain a copy of the NPL at
* http://www.mozilla.org/NPL/
*
* Software distributed under the NPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
* for the specific language governing rights and limitations under the
* NPL.
*
* The Initial Developer of this code under the NPL is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All Rights
* Reserved.
*
* This file was originally distributed with Rhino. I have copied it
* into SmallJava to avoid enforcing a dependency on Rhino being
* installed (and to avoid conflicting with installed versions of
* Rhino) -- all hail Java's extraordinarily bad package system!
*/
package com.svincent.smalljava.rhino;
public class Label {
private static final int FIXUPTABLE_SIZE = 8;
private static final boolean DEBUG = true;
public Label()
{
itsPC = -1;
}
public short getPC()
{
return itsPC;
}
public void fixGotos(byte theCodeBuffer[])
{
if (DEBUG) {
if ((itsPC == -1) && (itsFixupTable != null))
throw new RuntimeException("Unlocated label");
}
if (itsFixupTable != null) {
for (int i = 0; i < itsFixupTableTop; i++) {
int fixupSite = itsFixupTable[i];
// -1 to get delta from instruction start
short offset = (short)(itsPC - (fixupSite - 1));
theCodeBuffer[fixupSite++] = (byte)(offset >> 8);
theCodeBuffer[fixupSite] = (byte)offset;
}
}
itsFixupTable = null;
}
public void setPC(short thePC)
{
if (DEBUG) {
if ((itsPC != -1) && (itsPC != thePC))
throw new RuntimeException("Duplicate label");
}
itsPC = thePC;
}
public void addFixup(int fixupSite)
{
if (itsFixupTable == null) {
itsFixupTableTop = 1;
itsFixupTable = new int[FIXUPTABLE_SIZE];
itsFixupTable[0] = fixupSite;
}
else {
if (itsFixupTableTop == itsFixupTable.length) {
int oldLength = itsFixupTable.length;
int newTable[] = new int[oldLength + FIXUPTABLE_SIZE];
System.arraycopy(itsFixupTable, 0, newTable, 0, oldLength);
itsFixupTable = newTable;
}
itsFixupTable[itsFixupTableTop++] = fixupSite;
}
}
private short itsPC;
private int itsFixupTable[];
private int itsFixupTableTop;
}
| shawn-vincent/moksa | src/com/svincent/smalljava/rhino/Label.java | Java | gpl-2.0 | 3,032 |
<?php
/*
* @version $Id: HEADER 15930 2011-10-30 15:47:55Z tsmr $
-------------------------------------------------------------------------
ocsinventoryng plugin for GLPI
Copyright (C) 2015-2022 by the ocsinventoryng Development Team.
https://github.com/pluginsGLPI/ocsinventoryng
-------------------------------------------------------------------------
LICENSE
This file is part of ocsinventoryng.
ocsinventoryng 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.
ocsinventoryng 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 ocsinventoryng. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/**
* Class PluginOcsinventoryngRuleImportEntity
*/
class PluginOcsinventoryngRuleImportEntity extends CommonDBTM {
static $rightname = "plugin_ocsinventoryng";
const NO_RULE = 0;
/**
* @param int $nb
*
* @return translated
*/
static function getTypeName($nb = 0) {
return __('Elements not match with the rule', 'ocsinventoryng');
}
/**
* @param $name
*
* @return array
*/
static function cronInfo($name) {
switch ($name) {
case "CheckRuleImportEntity" :
return ['description' => __('OCSNG', 'ocsinventoryng') . " - " .
__('Alerts on computers that no longer respond the rules for assigning an item to an entity', 'ocsinventoryng')];
}
}
/**
* Checking machines that no longer respond the assignment rules
*
* @param $task
*
* @return int
*/
static function cronCheckRuleImportEntity($task) {
global $DB, $CFG_GLPI;
ini_set("memory_limit", "-1");
ini_set("max_execution_time", "0");
if (!$CFG_GLPI["notifications_mailing"]) {
return 0;
}
$CronTask = new CronTask();
if ($CronTask->getFromDBbyName("PluginOcsinventoryngRuleImportEntity", "CheckRuleImportEntity")) {
if ($CronTask->fields["state"] == CronTask::STATE_DISABLE) {
return 0;
}
} else {
return 0;
}
$cron_status = 0;
$plugin_ocsinventoryng_ocsservers_id = 0;
foreach ($DB->request("glpi_plugin_ocsinventoryng_ocsservers", "`is_active` = 1
AND `use_checkruleimportentity` = 1") as $config) {
$plugin_ocsinventoryng_ocsservers_id = $config["id"];
$plugin_ocsinventoryng_ocsservers_name = $config["name"];
if ($plugin_ocsinventoryng_ocsservers_id > 0) {
$computers = self::checkRuleImportEntity($plugin_ocsinventoryng_ocsservers_id);
foreach ($computers as $entities_id => $items) {
$message = $plugin_ocsinventoryng_ocsservers_name . ": <br />" .
sprintf(__('Items that do not meet the allocation rules for the entity %s: %s', 'ocsinventoryng'),
Dropdown::getDropdownName("glpi_entities", $entities_id),
count($items)) . "<br />";
if (NotificationEvent::raiseEvent("CheckRuleImportEntity",
new PluginOcsinventoryngRuleImportEntity(),
['entities_id' => $entities_id,
'items' => $items])) {
$cron_status = 1;
if ($task) {
$task->addVolume(1);
$task->log($message);
} else {
Session::addMessageAfterRedirect($message);
}
} else {
if ($task) {
$task->addVolume(count($items));
$task->log($message . "\n");
} else {
Session::addMessageAfterRedirect($message);
}
}
}
}
}
return $cron_status;
}
/**
* Checks the assignment rules for the server computers
*
* @param $plugin_ocsinventoryng_ocsservers_id
*
* @return array
*/
static function checkRuleImportEntity($plugin_ocsinventoryng_ocsservers_id) {
$data = [];
$computers = self::getComputerOcsLink($plugin_ocsinventoryng_ocsservers_id);
$ruleCollection = new RuleImportEntityCollection();
$ruleAsset = new RuleAssetCollection();
foreach ($computers as $computer) {
$fields = $ruleCollection->processAllRules($computer,
[],
['ocsid' => $computer['ocsid']]);
//case pc matched with a rule
if (isset($fields['_ruleid'])) {
$entities_id = $computer['entities_id'];
//Verification of the entity and location
if (isset($fields['entities_id']) && $fields['entities_id'] != $entities_id) {
if (!isset($data[$entities_id])) {
$data[$entities_id] = [];
}
$data[$entities_id][$computer['id']] = $computer;
$data[$entities_id][$computer['id']]['ruleid'] = $fields['_ruleid'];
$rule = new Rule();
$rule->getFromDB($fields['_ruleid']);
$data[$entities_id][$computer['id']]['rule_name'] = $rule->fields['name'];
if (isset($fields['entities_id']) && $fields['entities_id'] != $entities_id) {
if (!isset($data[$fields['entities_id']])) {
$data[$fields['entities_id']] = [];
}
$data[$entities_id][$computer['id']]['error'][] = 'Entity';
$data[$entities_id][$computer['id']]['dataerror'][] = $fields['entities_id'];
$data[$fields['entities_id']][$computer['id']] = $data[$entities_id][$computer['id']];
}
}
$output = ['locations_id' => $computer['locations_id']];
$fields = $ruleAsset->processAllRules($computer, $output, ['ocsid' => $computer['ocsid']]);
if (isset($fields['locations_id']) && $fields['locations_id'] != $computer['locations_id']
|| !isset($fields['locations_id']) && $computer['locations_id'] != 0) {
if(!isset($data[$entities_id][$computer['id']])) {
$data[$entities_id][$computer['id']] = $computer;
}
$data[$entities_id][$computer['id']]['error'][] = 'Location';
$data[$entities_id][$computer['id']]['dataerror'][] = $fields['locations_id'];
}
} else {
//No rules match
$entities_id = $computer['entities_id'];
if (!isset($data[$entities_id])) {
$data[$entities_id] = [];
}
$data[$entities_id][$computer['id']] = $computer;
$data[$entities_id][$computer['id']]['error'][] = self::NO_RULE;
}
}
return $data;
}
/**
* @param $plugin_ocsinventoryng_ocsservers_id
*
* @return array
*/
static function getComputerOcsLink($plugin_ocsinventoryng_ocsservers_id) {
$ocslink = new PluginOcsinventoryngOcslink();
$ocslinks = $ocslink->find(["plugin_ocsinventoryng_ocsservers_id" => $plugin_ocsinventoryng_ocsservers_id],
["entities_id"]);
$computers = [];
foreach ($ocslinks as $ocs) {
$computer = new Computer();
if ($computer->getFromDB($ocs['computers_id'])) {
$computer_id = $computer->fields['id'];
$computers[$computer_id] = $computer->fields;
$computers[$computer_id]['ocsservers_id'] = $ocs['plugin_ocsinventoryng_ocsservers_id'];
$computers[$computer_id]['ocsid'] = $ocs['ocsid'];
$computers[$computer_id]['_source'] = 'ocsinventoryng';
$computers[$computer_id]['_auto'] = true;
}
}
return $computers;
}
}
| pluginsGLPI/ocsinventoryng | inc/ruleimportentity.class.php | PHP | gpl-2.0 | 8,763 |
package ika.geo.grid;
import ika.geo.GeoGrid;
import ika.geo.GeoObject;
import ika.geoexport.ESRIASCIIGridExporter;
import ika.geoimport.EsriASCIIGridReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Multiply the cell values of two grids.
* @author Bernhard Jenny, Institute of Cartography, ETH Zurich.
*/
public class GridMultiplyOperator implements GridOperator{
public static void main(String[] args) {
try {
String f1 = ika.utils.FileUtils.askFile(null, "Grid 1 (ESRI ASCII format)", true);
if (f1 == null) {
System.exit(0);
}
String f2 = ika.utils.FileUtils.askFile(null, "Grid 2 (ESRI ASCII format)", true);
if (f2 == null) {
System.exit(0);
}
GeoGrid grid1 = EsriASCIIGridReader.read(f1);
GeoGrid grid2 = EsriASCIIGridReader.read(f2);
GeoGrid res = new GridMultiplyOperator().operate(grid1, grid2);
String resFilePath = ika.utils.FileUtils.askFile(null, "Result Grid (ESRI ASCII format)", false);
if (resFilePath != null) {
ESRIASCIIGridExporter.export(res, resFilePath);
}
System.exit(0);
} catch (IOException ex) {
Logger.getLogger(GridMultiplyOperator.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String getName() {
return "Multiply";
}
public GeoObject operate(GeoGrid geoGrid) {
throw new UnsupportedOperationException("Not supported yet.");
}
public GeoGrid operate(GeoGrid grid1, GeoGrid grid2) {
if (!grid1.hasSameExtensionAndResolution(grid2)) {
throw new IllegalArgumentException("grids of different size");
}
final int nrows = grid1.getRows();
final int ncols = grid1.getCols();
GeoGrid newGrid = new GeoGrid(ncols, nrows, grid1.getCellSize());
newGrid.setWest(grid1.getWest());
newGrid.setNorth(grid1.getNorth());
float[][] src1 = grid1.getGrid();
float[][] src2 = grid2.getGrid();
float[][] dstGrid = newGrid.getGrid();
for (int row = 0; row < nrows; ++row) {
float[] srcRow1 = src1[row];
float[] srcRow2 = src2[row];
float[] dstRow = dstGrid[row];
for (int col = 0; col < ncols; ++col) {
dstRow[col] = srcRow1[col] * srcRow2[col];
}
}
return newGrid;
}
}
| OSUCartography/FlexProjector | src/ika/geo/grid/GridMultiplyOperator.java | Java | gpl-2.0 | 2,585 |
""" This is script doc string. """
g = 1 # block 1 at level 0
# this is a comment that starts a line after indent
# this comment starts in column 1
h=2 # another inline comment
# see if this comment is preceded by whitespace
def f(a,b,c): # function with multiple returns
""" This is multi-line
function doc string.
"""
if a > b: # block 2 at level 1
if b > c: # block 3 at level 2
a = c # block 4 at level 3
else: # block 3 at level 2
return # block 4 at level 3 - explicit return
print a # block 2 at level 1
# implicit return
f(1,2,3) # block 1 at level 0
[f(i,3,5) for i in range(5)]
def g(a,b):
a += 1
if a > 'c': print "a is larger"
def h(b):
return b*b
return h(b)
g(3,2)
v = 123
# this function definition shows that parameter names are not
# defined until after the parameter list is completed. That is,
# it is invalid to define: def h(a,b=a): ...
def h(a, b=v,c=(v,),d={'a':(2,4,6)},e=[3,5,7]):
print "b: a=%s b=%s" % (a,b)
def k( a , b ) :
c = a
d = b
if c > d: return d
def kk( c ):
return c*c
return kk(c+d)
class C:
""" This is class doc string."""
def __init__( self ):
""" This is a member function doc string"""
if 1:
return
elif 0: return
class D (object):
def dd( self, *args, **kwds ):
return args, kwds
def main():
"This is single line doc string"
h(3)
c = C()
g(3,2)
f(7,5,3)
# next, test if whitespace affects token sequences
h ( 'a' , 'z' ) [ 1 : ]
# next, test tokenization for statement that crosses lines
h (
'b'
,
'y'
) [
1
:
]
if __name__ == "__main__":
main()
| ipmb/PyMetrics | PyMetrics/examples/sample.py | Python | gpl-2.0 | 1,928 |
package com.dovydasvenckus.timetracker.entry;
import com.dovydasvenckus.timetracker.core.date.clock.DateTimeService;
import com.dovydasvenckus.timetracker.core.pagination.PageSizeResolver;
import com.dovydasvenckus.timetracker.core.security.ClientDetails;
import com.dovydasvenckus.timetracker.project.Project;
import com.dovydasvenckus.timetracker.project.ProjectRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
@Service
public class TimeEntryService {
private final DateTimeService dateTimeService;
private final TimeEntryRepository timeEntryRepository;
private final ProjectRepository projectRepository;
private final PageSizeResolver pageSizeResolver;
public TimeEntryService(DateTimeService dateTimeService,
TimeEntryRepository timeEntryRepository,
ProjectRepository projectRepository,
PageSizeResolver pageSizeResolver) {
this.dateTimeService = dateTimeService;
this.timeEntryRepository = timeEntryRepository;
this.projectRepository = projectRepository;
this.pageSizeResolver = pageSizeResolver;
}
@Transactional(readOnly = true)
Page<TimeEntryDTO> findAll(int page, int pageSize, ClientDetails clientDetails) {
return timeEntryRepository
.findAllByDeleted(
clientDetails.getId(),
false,
PageRequest.of(page, pageSizeResolver.resolvePageSize(pageSize))
)
.map(TimeEntryDTO::new);
}
@Transactional(readOnly = true)
public Page<TimeEntryDTO> findAllByProject(long projectId, int page, int pageSize, ClientDetails clientDetails) {
return timeEntryRepository
.findAllByProject(
projectId,
clientDetails.getId(),
PageRequest.of(page, pageSizeResolver.resolvePageSize(pageSize))
)
.map(TimeEntryDTO::new);
}
@Transactional
public TimeEntry create(TimeEntryDTO timeEntryDTO, ClientDetails clientDetails) {
timeEntryDTO.setId(null);
TimeEntry timeEntry;
timeEntry = new TimeEntry(timeEntryDTO, clientDetails.getId());
Optional<Project> project = projectRepository.findByIdAndCreatedBy(
timeEntryDTO.getProject().getId(),
clientDetails.getId()
);
project.ifPresent(timeEntry::setProject);
timeEntryRepository.save(timeEntry);
return timeEntry;
}
@Transactional
public void stop(TimeEntryDTO timeEntryDTO, ClientDetails clientDetails) {
timeEntryRepository.findByIdAndCreatedBy(timeEntryDTO.getId(), clientDetails.getId())
.ifPresent(entry -> entry.setEndDate(dateTimeService.now()));
}
@Transactional
public void delete(Long id, ClientDetails clientDetails) {
timeEntryRepository.findByIdAndCreatedBy(id, clientDetails.getId())
.ifPresent(timeEntry -> timeEntry.setDeleted(true));
}
Optional<TimeEntryDTO> findCurrentlyActive(ClientDetails clientDetails) {
return timeEntryRepository.findCurrentlyActive(clientDetails.getId())
.map(TimeEntryDTO::new);
}
@Transactional
public TimeEntry startTracking(Long projectId, String description, ClientDetails clientDetails) {
Optional<Project> project = projectRepository.findByIdAndCreatedBy(projectId, clientDetails.getId());
if (project.isPresent()) {
TimeEntry timeEntry = new TimeEntry();
timeEntry.setStartDate(dateTimeService.now());
timeEntry.setDescription(description);
timeEntry.setProject(project.get());
timeEntry.setCreatedBy(clientDetails.getId());
timeEntryRepository.save(timeEntry);
return timeEntry;
}
return null;
}
}
| dovydasvenckus/time-tracker | src/main/java/com/dovydasvenckus/timetracker/entry/TimeEntryService.java | Java | gpl-2.0 | 4,153 |
<?php
//Yii::import('application.extensions.EUploadedImage');
class MarketController extends Controller {
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout = '//layouts/column2';
/**
* @return array action filters
*/
public function filters() {
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules() {
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions' => array('index', 'view', 'rss'),
'users' => array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions' => array('create', 'update', 'join', 'panel', 'panelView', 'list', 'delete', 'expire'),
'users' => array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions' => array('admin'),
'users' => array('admin'),
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id) {
if(!is_numeric($id)){
throw new CHttpException(404, 'Access denied.');
}
$entity_id = Yii::app()->user->getId();
$model = MarketAd::model()->with(
array(
'entities' => array('on' => ($entity_id ? 'entities.id=' . $entity_id : null)),
'joined' => array('on' => ($entity_id ? 'joined.entity_id=' . $entity_id : null))
))->findByPk($id);
$this->render('view', array(
'model' => $model,
));
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionPanel($id) {
if(!is_numeric($id)){
throw new CHttpException(404, 'Access denied.');
}
$model = $this->loadModel($id); //MarketAd::model()->with('users')->findByPk($id);
if (isset(Yii::app()->user->roles[$model->created_by])) {
$criteria = new CDbCriteria;
$criteria->with = array(
'marketAds' => array(
'together' => true,
'condition' => 'marketAds.id=' . $id,
),
'marketJoined' => array(
'together' => true,
'condition' => 'marketJoined.ad_id=' . $id,
),
);
$criteria->compare('marketAds.id', $id);
$dataProvider = new CActiveDataProvider('Entity', array(
'criteria' => $criteria,
));
Notification::shown($model->created_by, Sid::getSID($model));
$this->render('panel', array(
'model' => $model,
'dataProvider' => $dataProvider,
));
} else {
Yii::app()->user->setFlash('error', Yii::t('market', 'You can not access to this advertisement control panel'));
$this->redirect(array('view', 'id' => $id));
}
}
public function actionPanelView($ad_id, $entity_id) {
if(!is_numeric($ad_id) || !is_numeric($entity_id)){
throw new CHttpException(404, 'Access denied.');
}
$ad = $this->loadModel($ad_id);
if (!isset(Yii::app()->user->roles[$model->created_by])) {
$entity = Entity::model()->findByPk($entity_id);
$joined = MarketJoined::model()->with('entity')->findByPk(array('ad_id' => $ad_id, 'entity_id' => $entity_id));
$joined->setScenario('panel');
if (isset($_POST['MarketJoined'])) {
$joined->attributes = $_POST['MarketJoined'];
if ($joined->save()) {
/* if($joined->form_comment != '')
{
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= "From: noreply@instauremoslademocracia.net\r\n";
if (mail($user->email,Yii::t('market','[Comment from DEMOS Market]').' '.$ad->title,
$this->renderPartial('_joinMail',
array('title' => $ad->title,
'message' => $joined->form_comment,
'ad_id' => $ad_id,
'user_id' => $user_id,
),
true),$headers))
Yii::app()->user->setFlash('success',Yii::t('market','Thank you for contacting'));
else
Yii::app()->user->setFlash('error',Yii::t('market','E-mail not sent'));
} */
$this->redirect(array('panel', 'id' => $ad_id));
}
}
Notification::shown($ad->created_by, Sid::getSID($joined));
$this->render('panelView', array(
'entity' => $entity,
'joined' => $joined,
'ad' => $ad,
)
);
} else {
Yii::app()->user->setFlash('error', Yii::t('market', 'You can not access to this advertisement control panel'));
$this->redirect(array('view', 'id' => $ad_id));
}
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate($id = null) {
$model = new MarketAd;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
$entity = Entity::model()->findByPk(Yii::app()->user->logged);
$user = $entity->getObject();
if ($id != null) {
if (isset(Yii::app()->user->roles[$id])) {
$model->created_by = $id;
} else {
throw new CHttpException(404, 'Access denied.');
}
}
if (isset($_POST['MarketAd'])) {
$model->attributes = $_POST['MarketAd'];
if ($model->save()) {
if ($user->blocked) {
ActivityLog::add(Yii::app()->user->logged, ActivityLog::BLOCKED_MARKET_AD, Sid::getSID($model));
}
$this->redirect(array('view', 'id' => $model->id));
}
}
$model->expiration = date('Y-m-d', time() + MarketAd::MAX_EXPIRATION);
$this->render('create', array(
'model' => $model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id) {
if(!is_numeric($id)){
throw new CHttpException(404, 'Access denied.');
}
$model = $this->loadModel($id);
if (!isset(Yii::app()->user->roles[$model->created_by])) {
Yii::app()->user->setFlash('error', Yii::t('market', 'You can not update this advertisement'));
$this->redirect(array('view', 'id' => $id));
return;
}
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['MarketAd'])) {
$model->attributes = $_POST['MarketAd'];
if ($model->save())
$this->redirect(array('view', 'id' => $model->id));
}
$this->render('update', array(
'model' => $model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionExpire($id) {
if(!is_numeric($id)){
throw new CHttpException(404, 'Access denied.');
}
$model = $this->loadModel($id);
if (!isset(Yii::app()->user->roles[$model->created_by])) {
Yii::app()->user->setFlash('error', Yii::t('market', 'You can not update this advertisement'));
$this->redirect(array('view', 'id' => $id));
return;
}
// we only allow deletion via POST request
$model->expiration = '0000-00-00';
$model->save();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if (!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id) {
if(!is_numeric($id)){
throw new CHttpException(404, 'Access denied.');
}
$model = $this->loadModel($id);
if (!isset(Yii::app()->user->roles[$model->created_by])) {
Yii::app()->user->setFlash('error', Yii::t('market', 'You can not delete this advertisement'));
$this->redirect(array('view', 'id' => $id));
return;
}
$model->visible = 0;
$model->save();
Yii::app()->user->setFlash('notice', Yii::t('app', 'The advertisement have been moved away'));
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if (!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
// else
// throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
/**
* Join to a Market Ad a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionJoin($id) {
if(!is_numeric($id)){
throw new CHttpException(404, 'Access denied.');
}
$ad = $this->loadModel($id);
$entity_id = Yii::app()->user->getId();
$model = MarketJoined::model()->findByPk(array('ad_id' => $id, 'entity_id' => $entity_id));
if ($model == null) {
$model = new MarketJoined;
$model->ad_id = $id;
$already_joined = false;
} else {
$already_joined = true;
Yii::app()->user->setFlash('success', Yii::t('market', 'You are already joined, update anything you need.'));
}
$model->setScenario('join');
// uncomment the following code to enable ajax-based validation
/*
if(isset($_POST['ajax']) && $_POST['ajax']==='market-joined-join-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
*/
if (isset($_POST['MarketJoined'])) {
$model->attributes = $_POST['MarketJoined'];
if ($model->validate()) {
// form inputs are valid, do something here
if ($model->save()) {
Yii::app()->user->setFlash('success', Yii::t('market', 'You have successfully joined'));
$this->redirect(array('view', 'id' => $ad->id));
}
}
}
Notification::shown($entity_id, Sid::getSID($model));
$this->render('join', array('model' => $model, 'ad' => $ad));
}
/**
* Lists all models.
*/
public function actionList($mode = null, $tribe_id=null) {
if((!!$mode && !is_numeric($mode)) || (!!$tribe_id && !is_numeric($tribe_id))){
throw new CHttpException(404, 'Access denied.');
}
$this->actionIndex($mode,$tribe_id);
}
/**
* Lists all models.
*/
public function actionIndex($mode = null, $tribe_id=null) {
if((!!$mode && !is_numeric($mode)) || (!!$tribe_id && !is_numeric($tribe_id))){
throw new CHttpException(404, 'Access denied.');
}
$entity_id = Yii::app()->user->getId();
$model = new MarketAd('search');
$model->unsetAttributes(); // clear any default values
$tribe= null;
if ($tribe_id && is_numeric($tribe_id)){
$tribe = Tribe::model()->findByPk($tribe_id);
}
if (isset($_GET['MarketAd']))
$model->attributes = $_GET['MarketAd'];
$dataProvider = MarketAd::getAds($model, $mode, $entity_id,$tribe_id);
$this->render('index', array(
'dataProvider' => $dataProvider,
'model' => $model,
'tribe' => $tribe
));
}
/**
* Manages all models.
*/
public function actionAdmin() {
$model = new MarketAd('search');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['MarketAd']))
$model->attributes = $_GET['MarketAd'];
$this->render('admin', array(
'model' => $model,
));
}
/**
* Manages all models.
*/
public function actionRss() {
$entity_id = Yii::app()->user->getId();
$dataProvider = MarketAd::getAds(null, 3, $entity_id);
$dataProvider->setPagination(false);
$this->renderPartial('rss', array(
'dataProvider' => $dataProvider,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadModel($id) {
if(!is_numeric($id)){
throw new CHttpException(404, 'Access denied.');
}
$model = MarketAd::model()->findByPk($id);
if ($model === null)
throw new CHttpException(404, 'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model) {
if (isset($_POST['ajax']) && $_POST['ajax'] === 'market-ad-form') {
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
| mianfiga/monedademos | protected/controllers/MarketController.php | PHP | gpl-2.0 | 14,834 |
/*
* This source file is part of CaesarJ
* For the latest info, see http://caesarj.org/
*
* Copyright © 2003-2005
* Darmstadt University of Technology, Software Technology Group
* Also see acknowledgements in readme.txt
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: OpcodeNames.java,v 1.2 2005-01-24 16:52:57 aracic Exp $
*/
package org.caesarj.classfile;
/**
* The human-readable name of this opcodes
*/
public class OpcodeNames {
/**
* Returns the name for this opcode
*/
public static String getName(int opcode) {
return opcodeNames[opcode];
}
// --------------------------------------------------------------------
// DATA MEMBERS
// --------------------------------------------------------------------
private static String[] opcodeNames = {
"nop",
"aconst_null",
"iconst_m1",
"iconst_0",
"iconst_1",
"iconst_2",
"iconst_3",
"iconst_4",
"iconst_5",
"lconst_0",
"lconst_1",
"fconst_0",
"fconst_1",
"fconst_2",
"dconst_0",
"dconst_1",
"bipush",
"sipush",
"ldc",
"ldc_w",
"ldc2_w",
"iload",
"lload",
"fload",
"dload",
"aload",
"iload_0",
"iload_1",
"iload_2",
"iload_3",
"lload_0",
"lload_1",
"lload_2",
"lload_3",
"fload_0",
"fload_1",
"fload_2",
"fload_3",
"dload_0",
"dload_1",
"dload_2",
"dload_3",
"aload_0",
"aload_1",
"aload_2",
"aload_3",
"iaload",
"laload",
"faload",
"daload",
"aaload",
"baload",
"caload",
"saload",
"istore",
"lstore",
"fstore",
"dstore",
"astore",
"istore_0",
"istore_1",
"istore_2",
"istore_3",
"lstore_0",
"lstore_1",
"lstore_2",
"lstore_3",
"fstore_0",
"fstore_1",
"fstore_2",
"fstore_3",
"dstore_0",
"dstore_1",
"dstore_2",
"dstore_3",
"astore_0",
"astore_1",
"astore_2",
"astore_3",
"iastore",
"lastore",
"fastore",
"dastore",
"aastore",
"bastore",
"castore",
"sastore",
"pop",
"pop2",
"dup",
"dup_x1",
"dup_x2",
"dup2",
"dup2_x1",
"dup2_x2",
"swap",
"iadd",
"ladd",
"fadd",
"dadd",
"isub",
"lsub",
"fsub",
"dsub",
"imul",
"lmul",
"fmul",
"dmul",
"idiv",
"ldiv",
"fdiv",
"ddiv",
"irem",
"lrem",
"frem",
"drem",
"ineg",
"lneg",
"fneg",
"dneg",
"ishl",
"lshl",
"ishr",
"lshr",
"iushr",
"lushr",
"iand",
"land",
"ior",
"lor",
"ixor",
"lxor",
"iinc",
"i2l",
"i2f",
"i2d",
"l2i",
"l2f",
"l2d",
"f2i",
"f2l",
"f2d",
"d2i",
"d2l",
"d2f",
"i2b",
"i2c",
"i2s",
"lcmp",
"fcmpl",
"fcmpg",
"dcmpl",
"dcmpg",
"ifeq",
"ifne",
"iflt",
"ifge",
"ifgt",
"ifle",
"if_icmpeq",
"if_icmpne",
"if_icmplt",
"if_icmpge",
"if_icmpgt",
"if_icmple",
"if_acmpeq",
"if_acmpne",
"goto",
"jsr",
"ret",
"tableswitch",
"lookupswitch",
"ireturn",
"lreturn",
"freturn",
"dreturn",
"areturn",
"return",
"getstatic",
"putstatic",
"getfield",
"putfield",
"invokevirtual",
"invokespecial",
"invokestatic",
"invokeinterface",
"xxxunusedxxx",
"new",
"newarray",
"anewarray",
"arraylength",
"athrow",
"checkcast",
"instanceof",
"monitorenter",
"monitorexit",
"wide",
"multianewarray",
"ifnull",
"ifnonnull",
"goto_w",
"jsr_w"
};
}
| tud-stg-lang/caesar-compiler | src/org/caesarj/classfile/OpcodeNames.java | Java | gpl-2.0 | 4,355 |
<?php
/**
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
declare(strict_types=1);
namespace eZ\Publish\API\Repository\Values\Content\Search\Facet;
use eZ\Publish\API\Repository\Values\Content\Search\Facet;
/**
* This class represents a field range facet.
*
* @deprecated since eZ Platform 3.2.0, to be removed in eZ Platform 4.0.0.
*/
class FieldRangeFacet extends Facet
{
/**
* Number of documents not containing any terms in the queried fields.
*
* @var int
*/
public $missingCount;
/**
* The number of terms which are not in the queried top list.
*
* @var int
*/
public $otherCount;
/**
* The total count of terms found.
*
* @var int
*/
public $totalCount;
/**
* For each interval there is an entry with statistical data.
*
* @var \eZ\Publish\API\Repository\Values\Content\Search\Facet\RangeFacetEntry[]
*/
public $entries;
}
| gggeek/ezpublish-kernel | eZ/Publish/API/Repository/Values/Content/Search/Facet/FieldRangeFacet.php | PHP | gpl-2.0 | 1,081 |