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 |
|---|---|---|---|---|---|
using System;
using Microsoft.VisualStudio.TestTools.UITesting.WpfControls;
namespace CaptainPav.Testing.UI.CodedUI.PageModeling.Wpf
{
/// <summary>
/// Default implementation of a Wpf page model
/// </summary>
public abstract class WpfPageModelBase<T> : PageModelBase<T> where T : WpfControl
{
protected readonly WpfWindow parent;
protected WpfPageModelBase(WpfWindow bw)
{
if (null == bw)
{
throw new ArgumentNullException(nameof(bw));
}
this.parent = bw;
}
protected WpfWindow DocumentWindow => this.parent;
}
} | lazyRiffs/CodedUIFluentExtensions | CodedUIExtensions/CaptainPav.Testing.UI.CodedUI.PageModeling/Wpf/WpfBaseModels.cs | C# | gpl-2.0 | 624 |
/****************************************************************************
*
* ViSP, open source Visual Servoing Platform software.
* Copyright (C) 2005 - 2019 by Inria. All rights reserved.
*
* This software 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.
* See the file LICENSE.txt at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using ViSP with software that can not be combined with the GNU
* GPL, please contact Inria about acquiring a ViSP Professional
* Edition License.
*
* See http://visp.inria.fr for more information.
*
* This software was developed at:
* Inria Rennes - Bretagne Atlantique
* Campus Universitaire de Beaulieu
* 35042 Rennes Cedex
* France
*
* If you have questions regarding the use of this file, please contact
* Inria at visp@inria.fr
*
* This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
* WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Description:
* Test for Afma 6 dof robot.
*
* Authors:
* Fabien Spindler
*
*****************************************************************************/
/*!
\example testRobotAfma6.cpp
Example of a real robot control, the Afma6 robot (cartesian robot, with 6
degrees of freedom).
*/
#include <visp3/core/vpCameraParameters.h>
#include <visp3/core/vpDebug.h>
#include <visp3/robot/vpRobotAfma6.h>
#include <iostream>
#ifdef VISP_HAVE_AFMA6
int main()
{
try {
std::cout << "a test for vpRobotAfma6 class..." << std::endl;
vpRobotAfma6 afma6;
vpCameraParameters cam;
std::cout << "-- Default settings for Afma6 ---" << std::endl;
std::cout << afma6 << std::endl;
afma6.getCameraParameters(cam, 640, 480);
std::cout << cam << std::endl;
std::cout << "-- Settings associated to the CCMOP tool without distortion ---" << std::endl;
afma6.init(vpAfma6::TOOL_CCMOP);
std::cout << afma6 << std::endl;
afma6.getCameraParameters(cam, 640, 480);
std::cout << cam << std::endl;
std::cout << "-- Settings associated to CCMOP tool with distortion ------" << std::endl;
afma6.init(vpAfma6::TOOL_CCMOP, vpCameraParameters::perspectiveProjWithDistortion);
std::cout << afma6 << std::endl;
afma6.getCameraParameters(cam, 640, 480);
std::cout << cam << std::endl;
std::cout << "-- Settings associated to the gripper tool without distortion ---" << std::endl;
afma6.init(vpAfma6::TOOL_GRIPPER);
std::cout << afma6 << std::endl;
afma6.getCameraParameters(cam, 640, 480);
std::cout << cam << std::endl;
std::cout << "-- Settings associated to gripper tool with distortion ------" << std::endl;
afma6.init(vpAfma6::TOOL_GRIPPER, vpCameraParameters::perspectiveProjWithDistortion);
std::cout << afma6 << std::endl;
afma6.getCameraParameters(cam, 640, 480);
std::cout << cam << std::endl;
} catch (const vpException &e) {
std::cout << "Catch an exception: " << e << std::endl;
}
return 0;
}
#else
int main()
{
std::cout << "The real Afma6 robot controller is not available." << std::endl;
return 0;
}
#endif
| lagadic/visp | modules/robot/test/servo-afma6/testRobotAfma6.cpp | C++ | gpl-2.0 | 3,333 |
/*
* Copyright (C) 2008, 2009, 2010 Apple Inc. All Rights Reserved.
* Copyright (C) 2009 Jan Michael Alonzo
*
* 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 APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "AccessibilityController.h"
#if HAVE(ACCESSIBILITY)
#include "AccessibilityCallbacks.h"
#include "AccessibilityUIElement.h"
#include "DumpRenderTree.h"
#include <atk/atk.h>
bool loggingAccessibilityEvents = false;
AccessibilityController::AccessibilityController()
: m_globalNotificationHandler(nullptr)
{
}
AccessibilityController::~AccessibilityController()
{
}
AccessibilityUIElement AccessibilityController::elementAtPoint(int x, int y)
{
// FIXME: implement
return nullptr;
}
void AccessibilityController::platformResetToConsistentState()
{
}
void AccessibilityController::setLogFocusEvents(bool)
{
}
void AccessibilityController::setLogScrollingStartEvents(bool)
{
}
void AccessibilityController::setLogValueChangeEvents(bool)
{
}
void AccessibilityController::setLogAccessibilityEvents(bool logAccessibilityEvents)
{
if (logAccessibilityEvents == loggingAccessibilityEvents)
return;
if (!logAccessibilityEvents) {
loggingAccessibilityEvents = false;
disconnectAccessibilityCallbacks();
return;
}
connectAccessibilityCallbacks();
loggingAccessibilityEvents = true;
}
bool AccessibilityController::addNotificationListener(JSObjectRef functionCallback)
{
if (!functionCallback)
return false;
// Only one global notification listener.
if (m_globalNotificationHandler)
return false;
m_globalNotificationHandler = AccessibilityNotificationHandler::create();
m_globalNotificationHandler->setNotificationFunctionCallback(functionCallback);
return true;
}
void AccessibilityController::removeNotificationListener()
{
// Programmers should not be trying to remove a listener that's already removed.
ASSERT(m_globalNotificationHandler);
m_globalNotificationHandler = nullptr;
}
JSRetainPtr<JSStringRef> AccessibilityController::platformName() const
{
JSRetainPtr<JSStringRef> platformName(Adopt, JSStringCreateWithUTF8CString("atk"));
return platformName;
}
AtkObject* AccessibilityController::childElementById(AtkObject* parent, const char* id)
{
if (!ATK_IS_OBJECT(parent))
return nullptr;
bool parentFound = false;
AtkAttributeSet* attributeSet(atk_object_get_attributes(parent));
for (AtkAttributeSet* attributes = attributeSet; attributes; attributes = attributes->next) {
AtkAttribute* attribute = static_cast<AtkAttribute*>(attributes->data);
if (!strcmp(attribute->name, "html-id")) {
if (!strcmp(attribute->value, id))
parentFound = true;
break;
}
}
atk_attribute_set_free(attributeSet);
if (parentFound)
return parent;
int childCount = atk_object_get_n_accessible_children(parent);
for (int i = 0; i < childCount; i++) {
AtkObject* result = childElementById(atk_object_ref_accessible_child(parent, i), id);
if (ATK_IS_OBJECT(result))
return result;
}
return nullptr;
}
#endif
| loveyoupeng/rt | modules/web/src/main/native/Tools/DumpRenderTree/atk/AccessibilityControllerAtk.cpp | C++ | gpl-2.0 | 4,399 |
module Admin
class JobsController < AdminController
def initialize(repository = Delayed::Job)
@repository = repository
super()
end
def index
@jobs = @repository.order(created_at: :desc)
end
def show
@job = @repository.find(params[:id])
end
def update
@job = @repository.find(params[:id])
@job.invoke_job
redirect_to admin_jobs_path
end
def destroy
@job = @repository.find(params[:id])
@job.destroy
redirect_to admin_jobs_path
end
end
end
| mokhan/cakeside | app/controllers/admin/jobs_controller.rb | Ruby | gpl-2.0 | 546 |
/**
Copyright (C) SYSTAP, LLC 2006-2012. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.bigdata.rdf.graph.analytics;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.openrdf.model.Value;
import org.openrdf.sail.SailConnection;
import com.bigdata.rdf.graph.IGASContext;
import com.bigdata.rdf.graph.IGASEngine;
import com.bigdata.rdf.graph.IGASState;
import com.bigdata.rdf.graph.IGASStats;
import com.bigdata.rdf.graph.IGraphAccessor;
import com.bigdata.rdf.graph.analytics.CC.VS;
import com.bigdata.rdf.graph.impl.sail.AbstractSailGraphTestCase;
/**
* Test class for Breadth First Search (BFS) traversal.
*
* @see BFS
*
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a>
*/
public class TestCC extends AbstractSailGraphTestCase {
public TestCC() {
}
public TestCC(String name) {
super(name);
}
public void testCC() throws Exception {
/*
* Load two graphs. These graphs are not connected with one another (no
* shared vertices). This means that each graph will be its own
* connected component (all vertices in each source graph are
* connected within that source graph).
*/
final SmallGraphProblem p1 = setupSmallGraphProblem();
final SSSPGraphProblem p2 = setupSSSPGraphProblem();
final IGASEngine gasEngine = getGraphFixture()
.newGASEngine(1/* nthreads */);
try {
final SailConnection cxn = getGraphFixture().getSail()
.getConnection();
try {
final IGraphAccessor graphAccessor = getGraphFixture()
.newGraphAccessor(cxn);
final CC gasProgram = new CC();
final IGASContext<CC.VS, CC.ES, Value> gasContext = gasEngine
.newGASContext(graphAccessor, gasProgram);
final IGASState<CC.VS, CC.ES, Value> gasState = gasContext
.getGASState();
// Converge.
final IGASStats stats = gasContext.call();
if(log.isInfoEnabled())
log.info(stats);
/*
* Check the #of connected components that are self-reported and
* the #of vertices in each connected component. This helps to
* detect vertices that should have been visited but were not
* due to the initial frontier. E.g., "DC" will not be reported
* as a connected component of size (1) unless it gets into the
* initial frontier (it has no edges, only an attribute).
*/
final Map<Value, AtomicInteger> labels = gasProgram
.getConnectedComponents(gasState);
// the size of the connected component for this vertex.
{
final VS valueState = gasState.getState(p1.getFoafPerson());
final Value label = valueState != null?valueState.getLabel():null;
assertEquals(4, labels.get(label).get());
}
// the size of the connected component for this vertex.
{
final VS valueState = gasState.getState(p2.get_v1());
final Value label = valueState != null?valueState.getLabel():null;
final AtomicInteger ai = labels.get(label);
final int count = ai!=null?ai.get():-1;
assertEquals(5, count);
}
if (false) {
/*
* The size of the connected component for this vertex.
*
* Note: The vertex sampling code ignores self-loops and
* ignores vertices that do not have ANY edges. Thus "DC" is
* not put into the frontier and is not visited.
*/
final Value label = gasState.getState(p1.getDC())
.getLabel();
assertNotNull(label);
/*
* If DC was not put into the initial frontier, then it will
* be missing here.
*/
assertNotNull(labels.get(label));
assertEquals(1, labels.get(label).get());
}
// the #of connected components.
assertEquals(2, labels.size());
/*
* Most vertices in problem1 have the same label (the exception
* is DC, which is it its own connected component).
*/
Value label1 = null;
for (Value v : p1.getVertices()) {
final CC.VS vs = gasState.getState(v);
if (log.isInfoEnabled())
log.info("v=" + v + ", label=" + vs.getLabel());
if(v.equals(p1.getDC())) {
/*
* This vertex is in its own connected component and is
* therefore labeled by itself.
*/
assertEquals("vertex=" + v, v, vs.getLabel());
continue;
}
if (label1 == null) {
label1 = vs.getLabel();
assertNotNull(label1);
}
assertEquals("vertex=" + v, label1, vs.getLabel());
}
// All vertices in problem2 have the same label.
Value label2 = null;
for (Value v : p2.getVertices()) {
final CC.VS vs = gasState.getState(v);
if (log.isInfoEnabled())
log.info("v=" + v + ", label=" + vs.getLabel());
if (label2 == null) {
label2 = vs.getLabel();
assertNotNull(label2);
}
assertEquals("vertex=" + v, label2, vs.getLabel());
}
// The labels for the two connected components are distinct.
assertNotSame(label1, label2);
} finally {
try {
cxn.rollback();
} finally {
cxn.close();
}
}
} finally {
gasEngine.shutdownNow();
}
}
}
| blazegraph/database | bigdata-gas/src/test/java/com/bigdata/rdf/graph/analytics/TestCC.java | Java | gpl-2.0 | 7,408 |
/*
* Copyright (C) 2016 robert
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.rcebula.code_generation.final_steps;
import java.util.ArrayList;
import java.util.List;
import pl.rcebula.code_generation.intermediate.intermediate_code_structure.IField;
import pl.rcebula.code_generation.intermediate.intermediate_code_structure.IntermediateCode;
import pl.rcebula.code_generation.intermediate.intermediate_code_structure.Line;
import pl.rcebula.code_generation.intermediate.intermediate_code_structure.StringField;
/**
*
* @author robert
*/
public class AddInformationsAboutModules
{
private final IntermediateCode ic;
private final List<String> modulesName;
public AddInformationsAboutModules(IntermediateCode ic, List<String> modulesName)
{
this.ic = ic;
this.modulesName = modulesName;
analyse();
}
private void analyse()
{
// tworzymy pola
List<IField> fields = new ArrayList<>();
for (String m : modulesName)
{
IField f = new StringField(m);
fields.add(f);
}
// wstawiamy pustą linię na początek
ic.insertLine(Line.generateEmptyStringLine(), 0);
// tworzymy linię i wstawiamy na początek
Line line = new Line(fields);
ic.insertLine(line, 0);
}
}
| bercik/BIO | impl/bioc/src/pl/rcebula/code_generation/final_steps/AddInformationsAboutModules.java | Java | gpl-2.0 | 1,977 |
<?php
/*
*
* Copyright 2001, 2010 Thomas Belliard, Laurent Delineau, Edouard Hue, Eric Lebrun, Gabriel Fischer, Didier Blanqui
*
* This file is part of GEPI.
*
* GEPI 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.
*
* GEPI 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 GEPI; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// On empêche l'accès direct au fichier
if (basename($_SERVER["SCRIPT_NAME"])==basename(__File__)){
die();
};
?>
<div id="result">
<div id="wrap" >
<h3><font class="red">Bilans des incidents pour la période du: <?php echo $_SESSION['stats_periodes']['du'];?> au <?php echo $_SESSION['stats_periodes']['au'];?> </font> </h3>
<?php ClassVue::afficheVue('parametres.php',$vars) ?>
</div>
<div id="tableaux">
<div id="banner">
<ul class="css-tabs" id="menutabs">
<?php $i=0;
foreach ($incidents as $titre=>$incidents_titre) :?>
<?php if($titre=='L\'Etablissement') {
if($affichage_etab) : ?>
<li><a href="#tab<?php echo $i;?>" title="Bilan des incidents" name="Etablissement-onglet-01"><?php echo $titre;?></a></li>
<li><a href="#tab<?php echo $i+1;?>" name="Etablissement-onglet-02"><img src="apps/img/user.png" alt="Synthèse individuelle" title="Synthèse individuelle"/></a> </li>
<?php $i=$i+2;
endif;
} else if ($titre=='Tous les élèves' ||$titre=='Tous les personnels' ) { ?>
<li><a href="#tab<?php echo $i;?>" title="Bilan des incidents" name="<?php echo $titre;?>-onglet-01"><?php echo $titre;?></a></li>
<li><a href="#tab<?php echo $i+1;?>" name="<?php echo $titre;?>-onglet-02"><img src="apps/img/user.png" alt="Synthèse individuelle" title="Synthèse individuelle"/></a> </li>
<?php $i=$i+2;
} else { ?>
<li><a href="#tab<?php echo $i;?>" name="<?php echo $titre;?>-onglet-01" title="Bilan des incidents">
<?php if (isset($infos_individus[$titre])) {
echo mb_substr($infos_individus[$titre]['prenom'],0,1).'.'.$infos_individus[$titre]['nom'];
if (isset($infos_individus[$titre]['classe'])) echo'('.$infos_individus[$titre]['classe'].')';
}
else echo $titre;?></a>
</li>
<?php if (isset($infos_individus[$titre]['classe'])|| !isset($infos_individus[$titre])) { ?>
<li><a href="#tab<?php echo $i+1;?>" name="<?php echo $titre;?>-onglet-02"><img src="apps/img/user.png" alt="Synthèse par élève" title="Synthèse par élève"/></a> </li>
<?php
$i=$i+2;
}
else {
$i=$i+1;
}
}
endforeach ?>
</ul>
</div>
<div class="css-panes" id="containDiv">
<?php
$i=0;
foreach ($incidents as $titre=>$incidents_titre) {
if ($titre!=='L\'Etablissement' || ($titre=='L\'Etablissement' && !is_null($affichage_etab) ) ) {?>
<div class="panel" id="tab<?php echo $i;?>">
<?php
if (isset($incidents_titre['error'])) {?>
<table class="boireaus">
<tr ><td class="nouveau"><font class='titre'>Bilan des incidents concernant :</font>
<?php if (isset($infos_individus[$titre])) {
echo $infos_individus[$titre]['prenom'].' '.$infos_individus[$titre]['nom'];
if (isset($infos_individus[$titre]['classe'])) echo'('.$infos_individus[$titre]['classe'].')';
}
else echo $titre;?>
</td></tr>
<tr><td class='nouveau'>Pas d'incidents avec les critères sélectionnés...</td></tr>
</table><br /><br />
<?php echo'</div>';?>
<?php if ($titre!=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels') {?>
<div class="panel" id="tab<?php echo $i+1;?>">
<table class="boireaus">
<tr><td class="nouveau"><strong>Bilan individuel</strong> </td></tr>
<tr><td class="nouveau">Pas d'incidents avec les critères sélectionnés...</td></tr>
</table>
</div>
<?php
$i=$i+2;
}
} else { ?>
<table class="boireaus">
<tr >
<td rowspan="6" colspan="5" class='nouveau'>
<p><font class='titre'>Bilan des incidents concernant : </font>
<?php if (isset($infos_individus[$titre])) {
echo $infos_individus[$titre]['prenom'].' '.$infos_individus[$titre]['nom'];
if (isset($infos_individus[$titre]['classe'])) echo'('.$infos_individus[$titre]['classe'].')';
}
else echo $titre;?>
</p>
<?php if($filtres_categories||$filtres_mesures||$filtres_roles||$filtres_sanctions) { ?><p>avec les filtres selectionnés</p><?php }?>
</td>
<td <?php if ($titre=='L\'Etablissement' ) {?> colspan="3" <?php }?> class='nouveau'><font class='titre'>Nombres d'incidents sur la période:</font> <?php echo $totaux[$titre]['incidents']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php echo round((100*($totaux[$titre]['incidents']/$totaux['L\'Etablissement']['incidents'])),2);?></td><?php } ?></tr>
<tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total de mesures prises pour ces incidents :</font> <?php echo $totaux[$titre]['mesures_prises']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['mesures_prises']) echo round((100*($totaux[$titre]['mesures_prises']/$totaux['L\'Etablissement']['mesures_prises'])),2); else echo'0';?></td><?php } ?></tr>
<tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total de mesures demandées pour ces incidents :</font> <?php echo $totaux[$titre]['mesures_demandees']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['mesures_demandees']) echo round((100*($totaux[$titre]['mesures_demandees']/$totaux['L\'Etablissement']['mesures_demandees'])),2); else echo'0';?></td><?php } ?></tr>
<tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total de sanctions prises pour ces incidents:</font> <?php echo $totaux[$titre]['sanctions']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['sanctions']) echo round((100*($totaux[$titre]['sanctions']/$totaux['L\'Etablissement']['sanctions'])),2); else echo'0';?></td><?php } ?></tr>
<tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total d'heures de retenues pour ces incidents:</font> <?php echo $totaux[$titre]['heures_retenues']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['heures_retenues']) echo round((100*($totaux[$titre]['heures_retenues']/$totaux['L\'Etablissement']['heures_retenues'])),2); else echo '0'; ?></td><?php } ?></tr>
<tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total de jours d'exclusions pour ces incidents:</font> <?php echo $totaux[$titre]['jours_exclusions']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['jours_exclusions']) echo round((100*($totaux[$titre]['jours_exclusions']/$totaux['L\'Etablissement']['jours_exclusions'])),2); else echo '0'; ?></td><?php } ?></tr>
</table>
<?php if($mode_detaille) { ?>
<table class="sortable resizable boireaus" id="table<?php echo $i;?>">
<thead>
<tr><th><font class='titre'>Date</font></th><th class="text"><font class='titre'>Déclarant</font></th><th><font class='titre'>Heure</font></th><th class="text"><font class='titre'>Nature</font></th>
<th><font class='titre' title="Catégories">Cat.</font></th><th class="text" ><font class='titre'>Description</font></th><th width="50%" class="nosort"><font class='titre'>Suivi</font></th></tr>
</thead>
<?php $alt_b=1;
foreach($incidents_titre as $incident) {
$alt_b=$alt_b*(-1);?>
<tr class='lig<?php echo $alt_b;?>'><td><?php echo $incident->date; ?></td><td><?php echo $incident->declarant; ?></td><td><?php echo $incident->heure; ?></td>
<td><?php echo $incident->nature; ?></td><td><?php if(!is_null($incident->id_categorie))echo $incident->sigle_categorie;else echo'-'; ?></td><td><?php echo $incident->description; ?></td>
<td class="nouveau"><?php if(!isset($protagonistes[$incident->id_incident]))echo'<h3 class="red">Aucun protagoniste défini pour cet incident</h3>';
else { ?>
<table class="boireaus" width="100%" >
<?php foreach($protagonistes[$incident->id_incident] as $protagoniste) {?>
<tr><td>
<?php echo $protagoniste->prenom.' '.$protagoniste->nom.' <br/> ';
echo $protagoniste->statut.' ';
if($protagoniste->classe) echo $protagoniste->classe .' - '; else echo ' - ' ;
if($protagoniste->qualite=="") echo'<font class="red">Aucun rôle affecté.</font><br />';
else echo $protagoniste->qualite.'<br />';
?></td><td ><?php
if (isset($mesures[$incident->id_incident][$protagoniste->login])) { ?>
<p><strong>Mesures :</strong></p>
<table class="boireaus" >
<tr><th><font class='titre'>Nature</font></th><th><font class='titre'>Mesure</font></th></tr>
<?php
$alt_c=1;
foreach ($mesures[$incident->id_incident][$protagoniste->login] as $mesure) {
$alt_c=$alt_c*(-1); ?>
<tr class="lig<?php echo $alt_c;?>"><td><?php echo $mesure->mesure; ?></td>
<td><?php echo $mesure->type.' par '.$mesure->login_u; ?></td></tr> <?php } ?>
</table>
<?php }
if (isset($sanctions[$incident->id_incident][$protagoniste->login])) { ?>
<p><strong>Sanctions :</strong></p>
<table class="boireaus" width="100%">
<tr><th><font class='titre'>Nature</font></th><th><font class='titre'>Effectuée</font></th><th><font class='titre'>Date</font></th>
<th><font class='titre'>Durée</font></th>
</tr>
<?php
$alt_d=1;
foreach ($sanctions[$incident->id_incident][$protagoniste->login] as $sanction) {
$alt_d=$alt_d*(-1); ?>
<tr class="lig<?php echo $alt_d;?>"><td><?php echo $sanction->nature; ?></td>
<td><?php echo $sanction->effectuee; ?></td>
<td><?php if($sanction->nature=='retenue')echo $sanction->ret_date;
if($sanction->nature=='exclusion')echo 'Du '.$sanction->exc_date_debut.' au '.$sanction->exc_date_fin;
if($sanction->nature=='travail')echo 'Pour le '.$sanction->trv_date_retour;?>
</td>
<td><?php if($sanction->nature=='retenue') {
echo $sanction->ret_duree.' heure';
if ($sanction->ret_duree >1) echo 's';
}else if($sanction->nature=='exclusion') {
echo $sanction->exc_duree.' jour';
if ($sanction->exc_duree >1) echo 's';
}else{
echo'-';
}
?>
</td>
</tr>
<?php } ?>
</table>
<?php } ?>
</td></tr>
<?php } ?></table>
<?php } ?></td></tr>
<?php }
}?>
</table>
<br /><br /><a href="#wrap"><img src="apps/img/retour_haut.png" alt="simple" title="simplifié"/>Retour aux selections </a>
</div>
<?php if (isset($liste_eleves[$titre])): ?>
<div class="panel" id="tab<?php echo $i+1;?>">
<table class="boireaus"> <tr><td class="nouveau" colspan="11"><strong>Bilan individuel</strong></td><td><a href="#" class="export_csv" name="<?php echo $temp_dir.'/separateur/'.$titre;?>"><img src="../../images/notes_app_csv.png" alt="export_csv"/></a></td></tr></table>
<table class="sortable resizable ">
<thead>
<tr>
<?php if($titre=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels' ){?>
<th colspan="3"
<?php } else { ?>
<th colspan="2"
<?php } ?>
<?php
if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Individu</th>
<th >Incidents</th><th colspan="2" <?php if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Mesures prises</th>
<th colspan="2" <?php if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Sanctions prises</th>
<th colspan="2" <?php if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Heures de retenues</th>
<th colspan="2" <?php if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Jours d'exclusion</th>
</tr>
<tr>
<th>Nom</th><th>Prénom</th>
<?php if($titre=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels' ){?>
<th class="text">Classe</th>
<?php } ?>
<th>Nombre</th><th>Nombre</th><th>%/Etab</th><th>Nombre</th><th>%/Etab</th><th>Nombre</th><th>%/Etab</th><th>Nombre</th><th>%/Etab</th>
</tr>
</thead>
<tbody>
<?php
$alt_b=1;
foreach ($liste_eleves[$titre] as $eleve) {
$alt_b=$alt_b*(-1);?>
<tr <?php if ($alt_b==1) echo"class='alt'";?>>
<td><a href="index.php?ctrl=Bilans&action=add_selection&login=<?php echo $eleve?>"><?php echo $totaux_indiv[$eleve]['nom']; ?></a></td>
<td><?php
// 20200718
echo "<span style='display:none'>".$totaux_indiv[$eleve]['prenom']."</span>";
echo "<div style='float:right; width:16px; margin-left:3px;'>
<a href='../../eleves/visu_eleve.php?ele_login=".$eleve."&onglet=discipline' target='_blank' title=\"Voir la fiche élève dans un nouvel onglet.\"><img src='../../images/icons/ele_onglets.png' class='icone16' /></a>
</div>";
echo $totaux_indiv[$eleve]['prenom'];
?>
</td>
<?php if($titre=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels' ){?>
<td><?php echo $totaux_indiv[$eleve]['classe']; ?></td>
<?php } ?>
<td><?php echo $totaux_indiv[$eleve]['incidents']; ?></td><td><?php if(isset($totaux_indiv[$eleve]['mesures'])) echo $totaux_indiv[$eleve]['mesures'];else echo'0'; ?></td><td><?php if($totaux['L\'Etablissement']['mesures_prises'])echo str_replace(",",".",round(100*($totaux_indiv[$eleve]['mesures']/$totaux['L\'Etablissement']['mesures_prises']),2)); else echo'0';?></td>
<td><?php if(isset($totaux_indiv[$eleve]['sanctions'])) echo $totaux_indiv[$eleve]['sanctions']; else echo '0';?></td><td><?php if($totaux['L\'Etablissement']['sanctions']) echo str_replace(",",".",round(100* ($totaux_indiv[$eleve]['sanctions']/$totaux['L\'Etablissement']['sanctions']),2)); else echo'0';?></td>
<td><?php if(isset($totaux_indiv[$eleve]['heures_retenues'])) echo $totaux_indiv[$eleve]['heures_retenues'];else echo '0'; ?></td><td><?php if($totaux['L\'Etablissement']['heures_retenues'])echo str_replace(",",".",round(100*($totaux_indiv[$eleve]['heures_retenues']/$totaux['L\'Etablissement']['heures_retenues']),2));else echo'0';?></td>
<td><?php if(isset($totaux_indiv[$eleve]['jours_exclusions'])) echo $totaux_indiv[$eleve]['jours_exclusions'];else echo '0'; ?></td><td><?php if($totaux['L\'Etablissement']['jours_exclusions'])echo str_replace(",",".",round(100*($totaux_indiv[$eleve]['jours_exclusions']/$totaux['L\'Etablissement']['jours_exclusions']),2));else echo'0';?></td></tr>
<?php }?>
</tbody>
<?php if (!isset($totaux_indiv[$titre])) { ?>
<tfoot>
<tr>
<?php if($titre=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels' ){?>
<td colspan="3">
<?php } else{ ?>
<td colspan="2">
<?php } ?>
Total</td>
<td><?php if(isset($totaux_par_classe[$titre]['incidents']))echo $totaux_par_classe[$titre]['incidents']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['mesures_prises'])) echo $totaux_par_classe[$titre]['mesures']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['mesures_prises']) && $totaux['L\'Etablissement']['mesures_prises']>0) echo round(100*($totaux_par_classe[$titre]['mesures']/$totaux['L\'Etablissement']['mesures_prises']),2); else echo'0';?></td>
<td><?php if(isset($totaux_par_classe[$titre]['sanctions'])) echo $totaux_par_classe[$titre]['sanctions']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['sanctions']) && $totaux['L\'Etablissement']['sanctions']>0) echo round(100*($totaux_par_classe[$titre]['sanctions']/$totaux['L\'Etablissement']['sanctions']),2); else echo'0';?></td>
<td><?php if(isset($totaux_par_classe[$titre]['heures_retenues'])) echo $totaux_par_classe[$titre]['heures_retenues']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['heures_retenues']) && $totaux['L\'Etablissement']['heures_retenues']>0) echo round(100*($totaux_par_classe[$titre]['heures_retenues']/$totaux['L\'Etablissement']['heures_retenues']),2); else echo'0';?></td>
<td><?php if(isset($totaux_par_classe[$titre]['jours_exclusions'])) echo $totaux_par_classe[$titre]['jours_exclusions']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['jours_exclusions']) && $totaux['L\'Etablissement']['jours_exclusions']>0) echo round(100*($totaux_par_classe[$titre]['jours_exclusions']/$totaux['L\'Etablissement']['jours_exclusions']),2);else echo'0';?></td>
</tr>
</tfoot>
<?php }?>
</table>
</div>
<?php $i=$i+2;
else :
$i=$i+1;
endif;
}
}
}?>
</div>
</div>
</div>
| tbelliard/gepi | mod_discipline/stats2/apps/vues/bilans.php | PHP | gpl-2.0 | 21,097 |
/* -*- compile-command: "cd ../../../../../; ant debug install"; -*- */
/*
* Copyright 2010 by Eric House (xwords@eehouse.org). All rights
* reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.oliversride.wordryo;
import junit.framework.Assert;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
public class XWActivity extends Activity
implements DlgDelegate.DlgClickNotify, MultiService.MultiEventListener {
private final static String TAG = "XWActivity";
private DlgDelegate m_delegate;
@Override
protected void onCreate( Bundle savedInstanceState )
{
DbgUtils.logf( "%s.onCreate(this=%H)", getClass().getName(), this );
super.onCreate( savedInstanceState );
m_delegate = new DlgDelegate( this, this, savedInstanceState );
}
@Override
protected void onStart()
{
DbgUtils.logf( "%s.onStart(this=%H)", getClass().getName(), this );
super.onStart();
}
@Override
protected void onResume()
{
DbgUtils.logf( "%s.onResume(this=%H)", getClass().getName(), this );
BTService.setListener( this );
SMSService.setListener( this );
super.onResume();
}
@Override
protected void onPause()
{
DbgUtils.logf( "%s.onPause(this=%H)", getClass().getName(), this );
BTService.setListener( null );
SMSService.setListener( null );
super.onPause();
}
@Override
protected void onStop()
{
DbgUtils.logf( "%s.onStop(this=%H)", getClass().getName(), this );
super.onStop();
}
@Override
protected void onDestroy()
{
DbgUtils.logf( "%s.onDestroy(this=%H); isFinishing=%b",
getClass().getName(), this, isFinishing() );
super.onDestroy();
}
@Override
protected void onSaveInstanceState( Bundle outState )
{
super.onSaveInstanceState( outState );
m_delegate.onSaveInstanceState( outState );
}
@Override
protected Dialog onCreateDialog( int id )
{
Dialog dialog = super.onCreateDialog( id );
if ( null == dialog ) {
DbgUtils.logf( "%s.onCreateDialog() called", getClass().getName() );
dialog = m_delegate.onCreateDialog( id );
}
return dialog;
}
// these are duplicated in XWListActivity -- sometimes multiple
// inheritance would be nice to have...
protected void showAboutDialog()
{
m_delegate.showAboutDialog();
}
protected void showNotAgainDlgThen( int msgID, int prefsKey,
int action )
{
m_delegate.showNotAgainDlgThen( msgID, prefsKey, action );
}
protected void showNotAgainDlgThen( int msgID, int prefsKey )
{
m_delegate.showNotAgainDlgThen( msgID, prefsKey );
}
protected void showOKOnlyDialog( int msgID )
{
m_delegate.showOKOnlyDialog( msgID );
}
protected void showOKOnlyDialog( String msg )
{
m_delegate.showOKOnlyDialog( msg );
}
protected void showDictGoneFinish()
{
m_delegate.showDictGoneFinish();
}
protected void showConfirmThen( int msgID, int action )
{
m_delegate.showConfirmThen( getString(msgID), action );
}
protected void showConfirmThen( String msg, int action )
{
m_delegate.showConfirmThen( msg, action );
}
protected void showConfirmThen( int msg, int posButton, int action )
{
m_delegate.showConfirmThen( getString(msg), posButton, action );
}
public void showEmailOrSMSThen( int action )
{
m_delegate.showEmailOrSMSThen( action );
}
protected void doSyncMenuitem()
{
m_delegate.doSyncMenuitem();
}
protected void launchLookup( String[] words, int lang )
{
m_delegate.launchLookup( words, lang, false );
}
protected void startProgress( int id )
{
m_delegate.startProgress( id );
}
protected void stopProgress()
{
m_delegate.stopProgress();
}
protected boolean post( Runnable runnable )
{
return m_delegate.post( runnable );
}
// DlgDelegate.DlgClickNotify interface
public void dlgButtonClicked( int id, int which )
{
Assert.fail();
}
// BTService.MultiEventListener interface
public void eventOccurred( MultiService.MultiEvent event,
final Object ... args )
{
m_delegate.eventOccurred( event, args );
}
}
| oliversride/Wordryo | src/main/java/com/oliversride/wordryo/XWActivity.java | Java | gpl-2.0 | 5,258 |
<?php
/**
* Twenty Fifteen Customizer functionality
*
* @package WordPress
* @subpackage Twenty_Fifteen
* @since Twenty Fifteen 1.0
*/
/**
* Add postMessage support for site title and description for the Customizer.
*
* @since Twenty Fifteen 1.0
*
* @param WP_Customize_Manager $wp_customize
* Customizer object.
*/
function twentyfifteen_customize_register($wp_customize) {
$color_scheme = twentyfifteen_get_color_scheme ();
$wp_customize->get_setting ( 'blogname' )->transport = 'postMessage';
$wp_customize->get_setting ( 'blogdescription' )->transport = 'postMessage';
// Add color scheme setting and control.
$wp_customize->add_setting ( 'color_scheme', array (
'default' => 'default',
'sanitize_callback' => 'twentyfifteen_sanitize_color_scheme',
'transport' => 'postMessage'
) );
$wp_customize->add_control ( 'color_scheme', array (
'label' => __ ( 'Base Color Scheme', 'twentyfifteen' ),
'section' => 'colors',
'type' => 'select',
'choices' => twentyfifteen_get_color_scheme_choices (),
'priority' => 1
) );
// Add custom header and sidebar text color setting and control.
$wp_customize->add_setting ( 'sidebar_textcolor', array (
'default' => $color_scheme [4],
'sanitize_callback' => 'sanitize_hex_color',
'transport' => 'postMessage'
) );
$wp_customize->add_control ( new WP_Customize_Color_Control ( $wp_customize, 'sidebar_textcolor', array (
'label' => __ ( 'Header and Sidebar Text Color', 'twentyfifteen' ),
'description' => __ ( 'Applied to the header on small screens and the sidebar on wide screens.', 'twentyfifteen' ),
'section' => 'colors'
) ) );
// Remove the core header textcolor control, as it shares the sidebar text color.
$wp_customize->remove_control ( 'header_textcolor' );
// Add custom header and sidebar background color setting and control.
$wp_customize->add_setting ( 'header_background_color', array (
'default' => $color_scheme [1],
'sanitize_callback' => 'sanitize_hex_color',
'transport' => 'postMessage'
) );
$wp_customize->add_control ( new WP_Customize_Color_Control ( $wp_customize, 'header_background_color', array (
'label' => __ ( 'Header and Sidebar Background Color', 'twentyfifteen' ),
'description' => __ ( 'Applied to the header on small screens and the sidebar on wide screens.', 'twentyfifteen' ),
'section' => 'colors'
) ) );
// Add an additional description to the header image section.
$wp_customize->get_section ( 'header_image' )->description = __ ( 'Applied to the header on small screens and the sidebar on wide screens.', 'twentyfifteen' );
}
add_action ( 'customize_register', 'twentyfifteen_customize_register', 11 );
/**
* Register color schemes for Twenty Fifteen.
*
* Can be filtered with {@see 'twentyfifteen_color_schemes'}.
*
* The order of colors in a colors array:
* 1. Main Background Color.
* 2. Sidebar Background Color.
* 3. Box Background Color.
* 4. Main Text and Link Color.
* 5. Sidebar Text and Link Color.
* 6. Meta Box Background Color.
*
* @since Twenty Fifteen 1.0
*
* @return array An associative array of color scheme options.
*/
function twentyfifteen_get_color_schemes() {
return apply_filters ( 'twentyfifteen_color_schemes', array (
'default' => array (
'label' => __ ( 'Default', 'twentyfifteen' ),
'colors' => array (
'#f1f1f1',
'#ffffff',
'#ffffff',
'#333333',
'#333333',
'#f7f7f7'
)
),
'dark' => array (
'label' => __ ( 'Dark', 'twentyfifteen' ),
'colors' => array (
'#111111',
'#202020',
'#202020',
'#bebebe',
'#bebebe',
'#1b1b1b'
)
),
'yellow' => array (
'label' => __ ( 'Yellow', 'twentyfifteen' ),
'colors' => array (
'#f4ca16',
'#ffdf00',
'#ffffff',
'#111111',
'#111111',
'#f1f1f1'
)
),
'pink' => array (
'label' => __ ( 'Pink', 'twentyfifteen' ),
'colors' => array (
'#ffe5d1',
'#e53b51',
'#ffffff',
'#352712',
'#ffffff',
'#f1f1f1'
)
),
'purple' => array (
'label' => __ ( 'Purple', 'twentyfifteen' ),
'colors' => array (
'#674970',
'#2e2256',
'#ffffff',
'#2e2256',
'#ffffff',
'#f1f1f1'
)
),
'blue' => array (
'label' => __ ( 'Blue', 'twentyfifteen' ),
'colors' => array (
'#e9f2f9',
'#55c3dc',
'#ffffff',
'#22313f',
'#ffffff',
'#f1f1f1'
)
)
) );
}
if (! function_exists ( 'twentyfifteen_get_color_scheme' )) :
/**
* Get the current Twenty Fifteen color scheme.
*
* @since Twenty Fifteen 1.0
*
* @return array An associative array of either the current or default color scheme hex values.
*/
function twentyfifteen_get_color_scheme() {
$color_scheme_option = get_theme_mod ( 'color_scheme', 'default' );
$color_schemes = twentyfifteen_get_color_schemes ();
if (array_key_exists ( $color_scheme_option, $color_schemes )) {
return $color_schemes [$color_scheme_option] ['colors'];
}
return $color_schemes ['default'] ['colors'];
}
endif; // twentyfifteen_get_color_scheme
if (! function_exists ( 'twentyfifteen_get_color_scheme_choices' )) :
/**
* Returns an array of color scheme choices registered for Twenty Fifteen.
*
* @since Twenty Fifteen 1.0
*
* @return array Array of color schemes.
*/
function twentyfifteen_get_color_scheme_choices() {
$color_schemes = twentyfifteen_get_color_schemes ();
$color_scheme_control_options = array ();
foreach ( $color_schemes as $color_scheme => $value ) {
$color_scheme_control_options [$color_scheme] = $value ['label'];
}
return $color_scheme_control_options;
}
endif; // twentyfifteen_get_color_scheme_choices
if (! function_exists ( 'twentyfifteen_sanitize_color_scheme' )) :
/**
* Sanitization callback for color schemes.
*
* @since Twenty Fifteen 1.0
*
* @param string $value
* Color scheme name value.
* @return string Color scheme name.
*/
function twentyfifteen_sanitize_color_scheme($value) {
$color_schemes = twentyfifteen_get_color_scheme_choices ();
if (! array_key_exists ( $value, $color_schemes )) {
$value = 'default';
}
return $value;
}
endif; // twentyfifteen_sanitize_color_scheme
/**
* Enqueues front-end CSS for color scheme.
*
* @since Twenty Fifteen 1.0
*
* @see wp_add_inline_style()
*/
function twentyfifteen_color_scheme_css() {
$color_scheme_option = get_theme_mod ( 'color_scheme', 'default' );
// Don't do anything if the default color scheme is selected.
if ('default' === $color_scheme_option) {
return;
}
$color_scheme = twentyfifteen_get_color_scheme ();
// Convert main and sidebar text hex color to rgba.
$color_textcolor_rgb = twentyfifteen_hex2rgb ( $color_scheme [3] );
$color_sidebar_textcolor_rgb = twentyfifteen_hex2rgb ( $color_scheme [4] );
$colors = array (
'background_color' => $color_scheme [0],
'header_background_color' => $color_scheme [1],
'box_background_color' => $color_scheme [2],
'textcolor' => $color_scheme [3],
'secondary_textcolor' => vsprintf ( 'rgba( %1$s, %2$s, %3$s, 0.7)', $color_textcolor_rgb ),
'border_color' => vsprintf ( 'rgba( %1$s, %2$s, %3$s, 0.1)', $color_textcolor_rgb ),
'border_focus_color' => vsprintf ( 'rgba( %1$s, %2$s, %3$s, 0.3)', $color_textcolor_rgb ),
'sidebar_textcolor' => $color_scheme [4],
'sidebar_border_color' => vsprintf ( 'rgba( %1$s, %2$s, %3$s, 0.1)', $color_sidebar_textcolor_rgb ),
'sidebar_border_focus_color' => vsprintf ( 'rgba( %1$s, %2$s, %3$s, 0.3)', $color_sidebar_textcolor_rgb ),
'secondary_sidebar_textcolor' => vsprintf ( 'rgba( %1$s, %2$s, %3$s, 0.7)', $color_sidebar_textcolor_rgb ),
'meta_box_background_color' => $color_scheme [5]
);
$color_scheme_css = twentyfifteen_get_color_scheme_css ( $colors );
wp_add_inline_style ( 'twentyfifteen-style', $color_scheme_css );
}
add_action ( 'wp_enqueue_scripts', 'twentyfifteen_color_scheme_css' );
/**
* Binds JS listener to make Customizer color_scheme control.
*
* Passes color scheme data as colorScheme global.
*
* @since Twenty Fifteen 1.0
*/
function twentyfifteen_customize_control_js() {
wp_enqueue_script ( 'color-scheme-control', get_template_directory_uri () . '/js/color-scheme-control.js', array (
'customize-controls',
'iris',
'underscore',
'wp-util'
), '20141216', true );
wp_localize_script ( 'color-scheme-control', 'colorScheme', twentyfifteen_get_color_schemes () );
}
add_action ( 'customize_controls_enqueue_scripts', 'twentyfifteen_customize_control_js' );
/**
* Binds JS handlers to make the Customizer preview reload changes asynchronously.
*
* @since Twenty Fifteen 1.0
*/
function twentyfifteen_customize_preview_js() {
wp_enqueue_script ( 'twentyfifteen-customize-preview', get_template_directory_uri () . '/js/customize-preview.js', array (
'customize-preview'
), '20141216', true );
}
add_action ( 'customize_preview_init', 'twentyfifteen_customize_preview_js' );
/**
* Returns CSS for the color schemes.
*
* @since Twenty Fifteen 1.0
*
* @param array $colors
* Color scheme colors.
* @return string Color scheme CSS.
*/
function twentyfifteen_get_color_scheme_css($colors) {
$colors = wp_parse_args ( $colors, array (
'background_color' => '',
'header_background_color' => '',
'box_background_color' => '',
'textcolor' => '',
'secondary_textcolor' => '',
'border_color' => '',
'border_focus_color' => '',
'sidebar_textcolor' => '',
'sidebar_border_color' => '',
'sidebar_border_focus_color' => '',
'secondary_sidebar_textcolor' => '',
'meta_box_background_color' => ''
) );
$css = <<<CSS
/* Color Scheme */
/* Background Color */
body {
background-color: {$colors['background_color']};
}
/* Sidebar Background Color */
body:before,
.site-header {
background-color: {$colors['header_background_color']};
}
/* Box Background Color */
.post-navigation,
.pagination,
.secondary,
.site-footer,
.hentry,
.page-header,
.page-content,
.comments-area,
.widecolumn {
background-color: {$colors['box_background_color']};
}
/* Box Background Color */
button,
input[type="button"],
input[type="reset"],
input[type="submit"],
.pagination .prev,
.pagination .next,
.widget_calendar tbody a,
.widget_calendar tbody a:hover,
.widget_calendar tbody a:focus,
.page-links a,
.page-links a:hover,
.page-links a:focus,
.sticky-post {
color: {$colors['box_background_color']};
}
/* Main Text Color */
button,
input[type="button"],
input[type="reset"],
input[type="submit"],
.pagination .prev,
.pagination .next,
.widget_calendar tbody a,
.page-links a,
.sticky-post {
background-color: {$colors['textcolor']};
}
/* Main Text Color */
body,
blockquote cite,
blockquote small,
a,
.dropdown-toggle:after,
.image-navigation a:hover,
.image-navigation a:focus,
.comment-navigation a:hover,
.comment-navigation a:focus,
.widget-title,
.entry-footer a:hover,
.entry-footer a:focus,
.comment-metadata a:hover,
.comment-metadata a:focus,
.pingback .edit-link a:hover,
.pingback .edit-link a:focus,
.comment-list .reply a:hover,
.comment-list .reply a:focus,
.site-info a:hover,
.site-info a:focus {
color: {$colors['textcolor']};
}
/* Main Text Color */
.entry-content a,
.entry-summary a,
.page-content a,
.comment-content a,
.pingback .comment-body > a,
.author-description a,
.taxonomy-description a,
.textwidget a,
.entry-footer a:hover,
.comment-metadata a:hover,
.pingback .edit-link a:hover,
.comment-list .reply a:hover,
.site-info a:hover {
border-color: {$colors['textcolor']};
}
/* Secondary Text Color */
button:hover,
button:focus,
input[type="button"]:hover,
input[type="button"]:focus,
input[type="reset"]:hover,
input[type="reset"]:focus,
input[type="submit"]:hover,
input[type="submit"]:focus,
.pagination .prev:hover,
.pagination .prev:focus,
.pagination .next:hover,
.pagination .next:focus,
.widget_calendar tbody a:hover,
.widget_calendar tbody a:focus,
.page-links a:hover,
.page-links a:focus {
background-color: {$colors['textcolor']}; /* Fallback for IE7 and IE8 */
background-color: {$colors['secondary_textcolor']};
}
/* Secondary Text Color */
blockquote,
a:hover,
a:focus,
.main-navigation .menu-item-description,
.post-navigation .meta-nav,
.post-navigation a:hover .post-title,
.post-navigation a:focus .post-title,
.image-navigation,
.image-navigation a,
.comment-navigation,
.comment-navigation a,
.widget,
.author-heading,
.entry-footer,
.entry-footer a,
.taxonomy-description,
.page-links > .page-links-title,
.entry-caption,
.comment-author,
.comment-metadata,
.comment-metadata a,
.pingback .edit-link,
.pingback .edit-link a,
.post-password-form label,
.comment-form label,
.comment-notes,
.comment-awaiting-moderation,
.logged-in-as,
.form-allowed-tags,
.no-comments,
.site-info,
.site-info a,
.wp-caption-text,
.gallery-caption,
.comment-list .reply a,
.widecolumn label,
.widecolumn .mu_register label {
color: {$colors['textcolor']}; /* Fallback for IE7 and IE8 */
color: {$colors['secondary_textcolor']};
}
/* Secondary Text Color */
blockquote,
.logged-in-as a:hover,
.comment-author a:hover {
border-color: {$colors['textcolor']}; /* Fallback for IE7 and IE8 */
border-color: {$colors['secondary_textcolor']};
}
/* Border Color */
hr,
.dropdown-toggle:hover,
.dropdown-toggle:focus {
background-color: {$colors['textcolor']}; /* Fallback for IE7 and IE8 */
background-color: {$colors['border_color']};
}
/* Border Color */
pre,
abbr[title],
table,
th,
td,
input,
textarea,
.main-navigation ul,
.main-navigation li,
.post-navigation,
.post-navigation div + div,
.pagination,
.comment-navigation,
.widget li,
.widget_categories .children,
.widget_nav_menu .sub-menu,
.widget_pages .children,
.site-header,
.site-footer,
.hentry + .hentry,
.author-info,
.entry-content .page-links a,
.page-links > span,
.page-header,
.comments-area,
.comment-list + .comment-respond,
.comment-list article,
.comment-list .pingback,
.comment-list .trackback,
.comment-list .reply a,
.no-comments {
border-color: {$colors['textcolor']}; /* Fallback for IE7 and IE8 */
border-color: {$colors['border_color']};
}
/* Border Focus Color */
a:focus,
button:focus,
input:focus {
outline-color: {$colors['textcolor']}; /* Fallback for IE7 and IE8 */
outline-color: {$colors['border_focus_color']};
}
input:focus,
textarea:focus {
border-color: {$colors['textcolor']}; /* Fallback for IE7 and IE8 */
border-color: {$colors['border_focus_color']};
}
/* Sidebar Link Color */
.secondary-toggle:before {
color: {$colors['sidebar_textcolor']};
}
.site-title a,
.site-description {
color: {$colors['sidebar_textcolor']};
}
/* Sidebar Text Color */
.site-title a:hover,
.site-title a:focus {
color: {$colors['secondary_sidebar_textcolor']};
}
/* Sidebar Border Color */
.secondary-toggle {
border-color: {$colors['sidebar_textcolor']}; /* Fallback for IE7 and IE8 */
border-color: {$colors['sidebar_border_color']};
}
/* Sidebar Border Focus Color */
.secondary-toggle:hover,
.secondary-toggle:focus {
border-color: {$colors['sidebar_textcolor']}; /* Fallback for IE7 and IE8 */
border-color: {$colors['sidebar_border_focus_color']};
}
.site-title a {
outline-color: {$colors['sidebar_textcolor']}; /* Fallback for IE7 and IE8 */
outline-color: {$colors['sidebar_border_focus_color']};
}
/* Meta Background Color */
.entry-footer {
background-color: {$colors['meta_box_background_color']};
}
@media screen and (min-width: 38.75em) {
/* Main Text Color */
.page-header {
border-color: {$colors['textcolor']};
}
}
@media screen and (min-width: 59.6875em) {
/* Make sure its transparent on desktop */
.site-header,
.secondary {
background-color: transparent;
}
/* Sidebar Background Color */
.widget button,
.widget input[type="button"],
.widget input[type="reset"],
.widget input[type="submit"],
.widget_calendar tbody a,
.widget_calendar tbody a:hover,
.widget_calendar tbody a:focus {
color: {$colors['header_background_color']};
}
/* Sidebar Link Color */
.secondary a,
.dropdown-toggle:after,
.widget-title,
.widget blockquote cite,
.widget blockquote small {
color: {$colors['sidebar_textcolor']};
}
.widget button,
.widget input[type="button"],
.widget input[type="reset"],
.widget input[type="submit"],
.widget_calendar tbody a {
background-color: {$colors['sidebar_textcolor']};
}
.textwidget a {
border-color: {$colors['sidebar_textcolor']};
}
/* Sidebar Text Color */
.secondary a:hover,
.secondary a:focus,
.main-navigation .menu-item-description,
.widget,
.widget blockquote,
.widget .wp-caption-text,
.widget .gallery-caption {
color: {$colors['secondary_sidebar_textcolor']};
}
.widget button:hover,
.widget button:focus,
.widget input[type="button"]:hover,
.widget input[type="button"]:focus,
.widget input[type="reset"]:hover,
.widget input[type="reset"]:focus,
.widget input[type="submit"]:hover,
.widget input[type="submit"]:focus,
.widget_calendar tbody a:hover,
.widget_calendar tbody a:focus {
background-color: {$colors['secondary_sidebar_textcolor']};
}
.widget blockquote {
border-color: {$colors['secondary_sidebar_textcolor']};
}
/* Sidebar Border Color */
.main-navigation ul,
.main-navigation li,
.widget input,
.widget textarea,
.widget table,
.widget th,
.widget td,
.widget pre,
.widget li,
.widget_categories .children,
.widget_nav_menu .sub-menu,
.widget_pages .children,
.widget abbr[title] {
border-color: {$colors['sidebar_border_color']};
}
.dropdown-toggle:hover,
.dropdown-toggle:focus,
.widget hr {
background-color: {$colors['sidebar_border_color']};
}
.widget input:focus,
.widget textarea:focus {
border-color: {$colors['sidebar_border_focus_color']};
}
.sidebar a:focus,
.dropdown-toggle:focus {
outline-color: {$colors['sidebar_border_focus_color']};
}
}
CSS;
return $css;
}
/**
* Output an Underscore template for generating CSS for the color scheme.
*
* The template generates the css dynamically for instant display in the Customizer
* preview.
*
* @since Twenty Fifteen 1.0
*/
function twentyfifteen_color_scheme_css_template() {
$colors = array (
'background_color' => '{{ data.background_color }}',
'header_background_color' => '{{ data.header_background_color }}',
'box_background_color' => '{{ data.box_background_color }}',
'textcolor' => '{{ data.textcolor }}',
'secondary_textcolor' => '{{ data.secondary_textcolor }}',
'border_color' => '{{ data.border_color }}',
'border_focus_color' => '{{ data.border_focus_color }}',
'sidebar_textcolor' => '{{ data.sidebar_textcolor }}',
'sidebar_border_color' => '{{ data.sidebar_border_color }}',
'sidebar_border_focus_color' => '{{ data.sidebar_border_focus_color }}',
'secondary_sidebar_textcolor' => '{{ data.secondary_sidebar_textcolor }}',
'meta_box_background_color' => '{{ data.meta_box_background_color }}'
);
?>
<script type="text/html" id="tmpl-twentyfifteen-color-scheme">
<?php echo twentyfifteen_get_color_scheme_css( $colors ); ?>
</script>
<?php
}
add_action ( 'customize_controls_print_footer_scripts', 'twentyfifteen_color_scheme_css_template' );
| AgnaldoJaws/On-The-Bass. | wp-content/themes/twentyfifteen/inc/customizer.php | PHP | gpl-2.0 | 19,694 |
<?php //$Id: mod_form.php,v 1.2.2.3 2009/03/19 12:23:11 mudrd8mz Exp $
/**
* This file defines the main deva configuration form
* It uses the standard core Moodle (>1.8) formslib. For
* more info about them, please visit:
*
* http://docs.moodle.org/en/Development:lib/formslib.php
*
* The form must provide support for, at least these fields:
* - name: text element of 64cc max
*
* Also, it's usual to use these fields:
* - intro: one htmlarea element to describe the activity
* (will be showed in the list of activities of
* deva type (index.php) and in the header
* of the deva main page (view.php).
* - introformat: The format used to write the contents
* of the intro field. It automatically defaults
* to HTML when the htmleditor is used and can be
* manually selected if the htmleditor is not used
* (standard formats are: MOODLE, HTML, PLAIN, MARKDOWN)
* See lib/weblib.php Constants and the format_text()
* function for more info
*/
require_once($CFG->dirroot.'/course/moodleform_mod.php');
class mod_deva_mod_form extends moodleform_mod {
function definition() {
global $COURSE;
$mform =& $this->_form;
//-------------------------------------------------------------------------------
/// Adding the "general" fieldset, where all the common settings are showed
$mform->addElement('header', 'general', get_string('general', 'form'));
/// Adding the standard "name" field
$mform->addElement('text', 'name', get_string('devaname', 'deva'), array('size'=>'64'));
$mform->setType('name', PARAM_TEXT);
$mform->addRule('name', null, 'required', null, 'client');
$mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'client');
/// Adding the required "intro" field to hold the description of the instance
$mform->addElement('htmleditor', 'intro', get_string('devaintro', 'deva'));
$mform->setType('intro', PARAM_RAW);
$mform->addRule('intro', get_string('required'), 'required', null, 'client');
$mform->setHelpButton('intro', array('writing', 'richtext'), false, 'editorhelpbutton');
/// Adding "introformat" field
$mform->addElement('format', 'introformat', get_string('format'));
//-------------------------------------------------------------------------------
/// Adding the rest of deva settings, spreeading all them into this fieldset
/// or adding more fieldsets ('header' elements) if needed for better logic
$mform->addElement('static', 'label1', 'devasetting1', 'Your deva fields go here. Replace me!');
$mform->addElement('header', 'devafieldset', get_string('devafieldset', 'deva'));
$mform->addElement('static', 'label2', 'devasetting2', 'Your deva fields go here. Replace me!');
//-------------------------------------------------------------------------------
// add standard elements, common to all modules
$this->standard_coursemodule_elements();
//-------------------------------------------------------------------------------
// add standard buttons, common to all modules
$this->add_action_buttons();
}
}
?>
| IT-Scholars/Moodle-ITScholars-LMS | mod/deva/mod_form.php | PHP | gpl-2.0 | 3,290 |
<?php
/**
* Order tracking form
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.0.0
*
* Edited by WebMan
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $woocommerce, $post;
?>
<form action="<?php echo esc_url( get_permalink($post->ID) ); ?>" method="post" class="track_order">
<p><?php _e( 'To track your order please enter your Order ID in the box below and press return. This was given to you on your receipt and in the confirmation email you should have received.', 'woocommerce' ); ?></p>
<div class="clear mt20"></div>
<p class="form-row column col-12"><label for="orderid"><?php _e('Order ID', 'woocommerce'); ?></label> <input class="input-text" type="text" name="orderid" id="orderid" placeholder="<?php _e('Found in your order confirmation email.', 'woocommerce'); ?>" /></p>
<p class="form-row column col-12 last"><label for="order_email"><?php _e('Billing Email', 'woocommerce'); ?></label> <input class="input-text" type="text" name="order_email" id="order_email" placeholder="<?php _e('Email you used during checkout.', 'woocommerce'); ?>" /></p>
<div class="clear"></div>
<p class="form-row"><input type="submit" class="button" name="track" value="<?php _e( 'Track', 'woocommerce' ); ?>" /></p>
<?php $woocommerce->nonce_field('order_tracking') ?>
</form> | samuelmolinski/miniature-octo-archer | wp-content/themes/atlantes/woocommerce/order/form-tracking.php | PHP | gpl-2.0 | 1,333 |
<?php // no direct access
defined('_JEXEC') or die('Restricted access'); ?>
<script language="javascript" type="text/javascript">
function tableOrdering( order, dir, task )
{
var form = document.adminForm;
form.filter_order.value = order;
form.filter_order_Dir.value = dir;
document.adminForm.submit( task );
}
</script>
<form action="<?php echo $this->action; ?>" method="post" name="adminForm">
<?php if ($this->params->get('filter') || $this->params->get('show_pagination_limit')) : ?>
<?php if ($this->params->get('show_pagination_limit')) : ?>
<div class="jsn-infofilter">
<?php if ($this->params->get('filter')) : ?>
<span class="jsn-titlefilter">
<?php echo JText::_($this->params->get('filter_type') . ' Filter').' '; ?>
<input type="text" name="filter" value="<?php echo $this->escape($this->lists['filter']);?>" class="inputbox" onchange="document.adminForm.submit();" />
</span>
<?php endif; ?>
<?php
echo ' '.JText::_('Display Num').' ';
echo $this->pagination->getLimitBox();
?>
</div>
<?php endif; ?>
<?php endif; ?>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="jsn-infotable">
<?php if ($this->params->get('show_headings')) : ?>
<tr class="jsn-tableheader">
<td class="sectiontableheader" align="right" width="5%">
<?php echo JText::_('Num'); ?>
</td>
<?php if ($this->params->get('show_title')) : ?>
<td class="sectiontableheader" width="45%">
<?php echo JHTML::_('grid.sort', 'Item Title', 'a.title', $this->lists['order_Dir'], $this->lists['order'] ); ?>
</td>
<?php endif; ?>
<?php if ($this->params->get('show_date')) : ?>
<td class="sectiontableheader" width="25%">
<?php echo JHTML::_('grid.sort', 'Date', 'a.created', $this->lists['order_Dir'], $this->lists['order'] ); ?>
</td>
<?php endif; ?>
<?php if ($this->params->get('show_author')) : ?>
<td class="sectiontableheader" width="20%">
<?php echo JHTML::_('grid.sort', 'Author', 'author', $this->lists['order_Dir'], $this->lists['order'] ); ?>
</td>
<?php endif; ?>
<?php if ($this->params->get('show_hits')) : ?>
<td align="center" class="sectiontableheader" width="5%" nowrap="nowrap">
<?php echo JHTML::_('grid.sort', 'Hits', 'a.hits', $this->lists['order_Dir'], $this->lists['order'] ); ?>
</td>
<?php endif; ?>
</tr>
<?php endif; ?>
<?php foreach ($this->items as $item) : ?>
<tr class="sectiontableentry<?php echo ($item->odd +1 ) ." ". $this->params->get( 'pageclass_sfx' ); ?>" >
<td align="right">
<?php echo $this->pagination->getRowOffset( $item->count ); ?>
</td>
<?php if ($this->params->get('show_title')) : ?>
<?php if ($item->access <= $this->user->get('aid', 0)) : ?>
<td>
<a href="<?php echo $item->link; ?>">
<?php echo $item->title; ?></a>
<?php $this->item = $item; echo JHTML::_('icon.edit', $item, $this->params, $this->access) ?>
</td>
<?php else : ?>
<td>
<?php
echo $this->escape($item->title).' : ';
$link = JRoute::_('index.php?option=com_user&view=login');
$returnURL = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug, $item->sectionid), false);
$fullURL = new JURI($link);
$fullURL->setVar('return', base64_encode($returnURL));
$link = $fullURL->toString();
?>
<a href="<?php echo $link; ?>">
<?php echo JText::_( 'Register to read more...' ); ?></a>
</td>
<?php endif; ?>
<?php endif; ?>
<?php if ($this->params->get('show_date')) : ?>
<td>
<?php echo $item->created; ?>
</td>
<?php endif; ?>
<?php if ($this->params->get('show_author')) : ?>
<td >
<?php echo $item->created_by_alias ? $item->created_by_alias : $item->author; ?>
</td>
<?php endif; ?>
<?php if ($this->params->get('show_hits')) : ?>
<td align="center">
<?php echo $item->hits ? $item->hits : '-'; ?>
</td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</table>
<?php if ($this->params->get('show_pagination', 2)) : ?>
<div class="jsn-pagination"><?php echo $this->pagination->getPagesLinks(); ?></div>
<?php endif; ?>
<?php if ($this->params->get('show_pagination_results', 1)) : ?>
<p class="jsn-pageinfo"><?php echo $this->pagination->getPagesCounter(); ?></p>
<?php endif; ?>
<input type="hidden" name="id" value="<?php echo $this->category->id; ?>" />
<input type="hidden" name="sectionid" value="<?php echo $this->category->sectionid; ?>" />
<input type="hidden" name="task" value="<?php echo $this->lists['task']; ?>" />
<input type="hidden" name="filter_order" value="" />
<input type="hidden" name="filter_order_Dir" value="" />
<input type="hidden" name="limitstart" value="0" />
</form> | w2/ctb | templates/jsn_dome_free/html/com_content2/category/default_items.php | PHP | gpl-2.0 | 4,614 |
package kc.spark.pixels.android.ui.assets;
import static org.solemnsilence.util.Py.map;
import java.util.Map;
import android.content.Context;
import android.graphics.Typeface;
public class Typefaces {
// NOTE: this is tightly coupled to the filenames in assets/fonts
public static enum Style {
BOLD("Arial.ttf"),
BOLD_ITALIC("Arial.ttf"),
BOOK("Arial.ttf"),
BOOK_ITALIC("Arial.ttf"),
LIGHT("Arial.ttf"),
LIGHT_ITALIC("Arial.ttf"),
MEDIUM("Arial.ttf"),
MEDIUM_ITALIC("Arial.ttf");
// BOLD("gotham_bold.otf"),
// BOLD_ITALIC("gotham_bold_ita.otf"),
// BOOK("gotham_book.otf"),
// BOOK_ITALIC("gotham_book_ita.otf"),
// LIGHT("gotham_light.otf"),
// LIGHT_ITALIC("gotham_light_ita.otf"),
// MEDIUM("gotham_medium.otf"),
// MEDIUM_ITALIC("gotham_medium_ita.otf");
public final String fileName;
private Style(String name) {
fileName = name;
}
}
private static final Map<Style, Typeface> typefaces = map();
public static Typeface getTypeface(Context ctx, Style style) {
Typeface face = typefaces.get(style);
if (face == null) {
face = Typeface.createFromAsset(ctx.getAssets(), "fonts/" + style.fileName);
typefaces.put(style, face);
}
return face;
}
}
| sparcules/Spark_Pixels | AndroidApp/SparkPixels/src/kc/spark/pixels/android/ui/assets/Typefaces.java | Java | gpl-2.0 | 1,212 |
/*
* Copyright (c) 2003, 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.
*/
/* @test
@bug 4922813
@summary Check the new impl of encodePath will not cause regression
@key randomness
*/
import java.util.BitSet;
import java.io.File;
import java.util.Random;
import sun.net.www.ParseUtil;
public class ParseUtil_4922813 {
public static void main(String[] argv) throws Exception {
int num = 400;
while (num-- >= 0) {
String source = getTestSource();
String ec = sun.net.www.ParseUtil.encodePath(source);
String v117 = ParseUtil_V117.encodePath(source);
if (!ec.equals(v117)) {
throw new RuntimeException("Test Failed for : \n"
+ " source =<"
+ getUnicodeString(source)
+ ">");
}
}
}
static int maxCharCount = 200;
static int maxCodePoint = 0x10ffff;
static Random random;
static String getTestSource() {
if (random == null) {
long seed = System.currentTimeMillis();
random = new Random(seed);
}
String source = "";
int i = 0;
int count = random.nextInt(maxCharCount) + 1;
while (i < count) {
int codepoint = random.nextInt(127);
source = source + String.valueOf((char)codepoint);
codepoint = random.nextInt(0x7ff);
source = source + String.valueOf((char)codepoint);
codepoint = random.nextInt(maxCodePoint);
source = source + new String(Character.toChars(codepoint));
i += 3;
}
return source;
}
static String getUnicodeString(String s){
String unicodeString = "";
for(int j=0; j< s.length(); j++){
unicodeString += "0x"+ Integer.toString(s.charAt(j), 16);
}
return unicodeString;
}
}
class ParseUtil_V117 {
static BitSet encodedInPath;
static {
encodedInPath = new BitSet(256);
// Set the bits corresponding to characters that are encoded in the
// path component of a URI.
// These characters are reserved in the path segment as described in
// RFC2396 section 3.3.
encodedInPath.set('=');
encodedInPath.set(';');
encodedInPath.set('?');
encodedInPath.set('/');
// These characters are defined as excluded in RFC2396 section 2.4.3
// and must be escaped if they occur in the data part of a URI.
encodedInPath.set('#');
encodedInPath.set(' ');
encodedInPath.set('<');
encodedInPath.set('>');
encodedInPath.set('%');
encodedInPath.set('"');
encodedInPath.set('{');
encodedInPath.set('}');
encodedInPath.set('|');
encodedInPath.set('\\');
encodedInPath.set('^');
encodedInPath.set('[');
encodedInPath.set(']');
encodedInPath.set('`');
// US ASCII control characters 00-1F and 7F.
for (int i=0; i<32; i++)
encodedInPath.set(i);
encodedInPath.set(127);
}
/**
* Constructs an encoded version of the specified path string suitable
* for use in the construction of a URL.
*
* A path separator is replaced by a forward slash. The string is UTF8
* encoded. The % escape sequence is used for characters that are above
* 0x7F or those defined in RFC2396 as reserved or excluded in the path
* component of a URL.
*/
public static String encodePath(String path) {
StringBuffer sb = new StringBuffer();
int n = path.length();
for (int i=0; i<n; i++) {
char c = path.charAt(i);
if (c == File.separatorChar)
sb.append('/');
else {
if (c <= 0x007F) {
if (encodedInPath.get(c))
escape(sb, c);
else
sb.append(c);
} else if (c > 0x07FF) {
escape(sb, (char)(0xE0 | ((c >> 12) & 0x0F)));
escape(sb, (char)(0x80 | ((c >> 6) & 0x3F)));
escape(sb, (char)(0x80 | ((c >> 0) & 0x3F)));
} else {
escape(sb, (char)(0xC0 | ((c >> 6) & 0x1F)));
escape(sb, (char)(0x80 | ((c >> 0) & 0x3F)));
}
}
}
return sb.toString();
}
/**
* Appends the URL escape sequence for the specified char to the
* specified StringBuffer.
*/
private static void escape(StringBuffer s, char c) {
s.append('%');
s.append(Character.forDigit((c >> 4) & 0xF, 16));
s.append(Character.forDigit(c & 0xF, 16));
}
}
| openjdk/jdk8u | jdk/test/sun/net/www/ParseUtil_4922813.java | Java | gpl-2.0 | 5,843 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. currentmodule:: __init__.py
.. moduleauthor:: Pat Daburu <pat@daburu.net>
Provide a brief description of the module.
""" | patdaburu/mothergeo-py | mothergeo/db/postgis/__init__.py | Python | gpl-2.0 | 175 |
<?php
/**
* 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; under version 2
* of the License (non-upgradable).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Copyright (c) 2013 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT);
*
* @author Jérôme Bogaerts, <jerome@taotesting.com>
* @license GPLv2
* @package
*/
namespace qtism\data\storage\xml\marshalling;
use qtism\data\content\ModalFeedbackCollection;
use qtism\data\content\StylesheetCollection;
use qtism\data\state\OutcomeDeclarationCollection;
use qtism\data\state\ResponseDeclarationCollection;
use qtism\data\state\TemplateDeclarationCollection;
use qtism\data\QtiComponent;
use qtism\data\AssessmentItem;
use \DOMElement;
/**
* Marshalling/Unmarshalling implementation for AssessmentItem.
*
* @author Jérôme Bogaerts <jerome@taotesting.com>
*
*/
class AssessmentItemMarshaller extends Marshaller {
/**
* Marshall an AssessmentItem object into a DOMElement object.
*
* @param QtiComponent $component An AssessmentItem object.
* @return DOMElement The according DOMElement object.
*/
protected function marshall(QtiComponent $component) {
$element = static::getDOMCradle()->createElement($component->getQtiClassName());
self::setDOMElementAttribute($element, 'identifier', $component->getIdentifier());
self::setDOMElementAttribute($element, 'title', $component->getTitle());
self::setDOMElementAttribute($element, 'timeDependent', $component->isTimeDependent());
self::setDOMElementAttribute($element, 'adaptive', $component->isAdaptive());
if ($component->hasLang() === true) {
self::setDOMElementAttribute($element, 'lang', $component->getLang());
}
if ($component->hasLabel() === true) {
self::setDOMElementAttribute($element, 'label', $component->getLabel());
}
if ($component->hasToolName() === true) {
self::setDOMElementAttribute($element, 'toolName', $component->getToolName());
}
if ($component->hasToolVersion() === true) {
self::setDOMElementAttribute($element, 'toolVersion', $component->getToolVersion());
}
foreach ($component->getResponseDeclarations() as $responseDeclaration) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($responseDeclaration);
$element->appendChild($marshaller->marshall($responseDeclaration));
}
foreach ($component->getOutcomeDeclarations() as $outcomeDeclaration) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($outcomeDeclaration);
$element->appendChild($marshaller->marshall($outcomeDeclaration));
}
foreach ($component->getTemplateDeclarations() as $templateDeclaration) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($templateDeclaration);
$element->appendChild($marshaller->marshall($templateDeclaration));
}
if ($component->hasTemplateProcessing() === true) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($component->getTemplateProcessing());
$element->appendChild($marshaller->marshall($component->getTemplateProcessing()));
}
foreach ($component->getStylesheets() as $stylesheet) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($stylesheet);
$element->appendChild($marshaller->marshall($stylesheet));
}
if ($component->hasItemBody() === true) {
$itemBody = $component->getItemBody();
$marshaller = $this->getMarshallerFactory()->createMarshaller($itemBody);
$element->appendChild($marshaller->marshall($itemBody));
}
if ($component->hasResponseProcessing() === true) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($component->getResponseProcessing());
$element->appendChild($marshaller->marshall($component->getResponseProcessing()));
}
foreach ($component->getModalFeedbacks() as $modalFeedback) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($modalFeedback);
$element->appendChild($marshaller->marshall($modalFeedback));
}
return $element;
}
/**
* Unmarshall a DOMElement object corresponding to a QTI assessmentItem element.
*
* If $assessmentItem is provided, it will be used as the unmarshalled component instead of creating
* a new one.
*
* @param DOMElement $element A DOMElement object.
* @param AssessmentItem $assessmentItem An optional AssessmentItem object to be decorated.
* @return QtiComponent An AssessmentItem object.
* @throws UnmarshallingException
*/
protected function unmarshall(DOMElement $element, AssessmentItem $assessmentItem = null) {
if (($identifier = static::getDOMElementAttributeAs($element, 'identifier')) !== null) {
if (($timeDependent = static::getDOMElementAttributeAs($element, 'timeDependent', 'boolean')) !== null) {
if (($title= static::getDOMElementAttributeAs($element, 'title')) !== null) {
if (empty($assessmentItem)) {
$object = new AssessmentItem($identifier, $title, $timeDependent);
}
else {
$object = $assessmentItem;
$object->setIdentifier($identifier);
$object->setTimeDependent($timeDependent);
}
if (($lang = static::getDOMElementAttributeAs($element, 'lang')) !== null) {
$object->setLang($lang);
}
if (($label = static::getDOMElementAttributeAs($element, 'label')) !== null) {
$object->setLabel($label);
}
if (($adaptive = static::getDOMElementAttributeAs($element, 'adaptive', 'boolean')) !== null) {
$object->setAdaptive($adaptive);
}
if (($toolName = static::getDOMElementAttributeAs($element, 'toolName')) !== null) {
$object->setToolName($toolName);
}
if (($toolVersion = static::getDOMElementAttributeAs($element, 'toolVersion')) !== null) {
$object->setToolVersion($toolVersion);
}
$responseDeclarationElts = static::getChildElementsByTagName($element, 'responseDeclaration');
if (!empty($responseDeclarationElts)) {
$responseDeclarations = new ResponseDeclarationCollection();
foreach ($responseDeclarationElts as $responseDeclarationElt) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($responseDeclarationElt);
$responseDeclarations[] = $marshaller->unmarshall($responseDeclarationElt);
}
$object->setResponseDeclarations($responseDeclarations);
}
$outcomeDeclarationElts = static::getChildElementsByTagName($element, 'outcomeDeclaration');
if (!empty($outcomeDeclarationElts)) {
$outcomeDeclarations = new OutcomeDeclarationCollection();
foreach ($outcomeDeclarationElts as $outcomeDeclarationElt) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($outcomeDeclarationElt);
$outcomeDeclarations[] = $marshaller->unmarshall($outcomeDeclarationElt);
}
$object->setOutcomeDeclarations($outcomeDeclarations);
}
$templateDeclarationElts = static::getChildElementsByTagName($element, 'templateDeclaration');
if (!empty($templateDeclarationElts)) {
$templateDeclarations = new TemplateDeclarationCollection();
foreach ($templateDeclarationElts as $templateDeclarationElt) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($templateDeclarationElt);
$templateDeclarations[] = $marshaller->unmarshall($templateDeclarationElt);
}
$object->setTemplateDeclarations($templateDeclarations);
}
$templateProcessingElts = static::getChildElementsByTagName($element, 'templateProcessing');
if (!empty($templateProcessingElts)) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($templateProcessingElts[0]);
$object->setTemplateProcessing($marshaller->unmarshall($templateProcessingElts[0]));
}
$stylesheetElts = static::getChildElementsByTagName($element, 'stylesheet');
if (!empty($stylesheetElts)) {
$stylesheets = new StylesheetCollection();
foreach ($stylesheetElts as $stylesheetElt) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($stylesheetElt);
$stylesheets[] = $marshaller->unmarshall($stylesheetElt);
}
$object->setStylesheets($stylesheets);
}
$itemBodyElts = static::getChildElementsByTagName($element, 'itemBody');
if (count($itemBodyElts) > 0) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($itemBodyElts[0]);
$object->setItemBody($marshaller->unmarshall($itemBodyElts[0]));
}
$responseProcessingElts = static::getChildElementsByTagName($element, 'responseProcessing');
if (!empty($responseProcessingElts)) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($responseProcessingElts[0]);
$object->setResponseProcessing($marshaller->unmarshall($responseProcessingElts[0]));
}
$modalFeedbackElts = static::getChildElementsByTagName($element, 'modalFeedback');
if (!empty($modalFeedbackElts)) {
$modalFeedbacks = new ModalFeedbackCollection();
foreach ($modalFeedbackElts as $modalFeedbackElt) {
$marshaller = $this->getMarshallerFactory()->createMarshaller($modalFeedbackElt);
$modalFeedbacks[] = $marshaller->unmarshall($modalFeedbackElt);
}
$object->setModalFeedbacks($modalFeedbacks);
}
return $object;
}
else {
$msg = "The mandatory attribute 'title' is missing from element '" . $element->localName . "'.";
throw new UnmarshallingException($msg, $element);
}
}
else {
$msg = "The mandatory attribute 'timeDependent' is missing from element '" . $element->localName . "'.";
throw new UnmarshallingException($msg, $element);
}
}
else {
$msg = "The mandatory attribute 'identifier' is missing from element '" . $element->localName . "'.";
throw new UnmarshallingException($msg, $element);
}
}
public function getExpectedQtiClassName() {
return 'assessmentItem';
}
}
| dhx/tao-comp | vendor/qtism/qtism/qtism/data/storage/xml/marshalling/AssessmentItemMarshaller.php | PHP | gpl-2.0 | 11,567 |
<?php
/*
* @package Joomla.Framework
* @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*
* @component Phoca Component
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License version 2 or later;
*/
defined('_JEXEC') or die();
jimport('joomla.application.component.modellist');
class PhocaGalleryCpModelPhocaGalleryRa extends JModelList
{
protected $option = 'com_phocagallery';
public function __construct($config = array())
{
if (empty($config['filter_fields'])) {
$config['filter_fields'] = array(
'id', 'a.id',
'title', 'a.title',
'username','ua.username',
'date', 'a.date',
'alias', 'a.alias',
'checked_out', 'a.checked_out',
'checked_out_time', 'a.checked_out_time',
'category_id', 'category_id',
'state', 'a.state',
'ordering', 'a.ordering',
'language', 'a.language',
'hits', 'a.hits',
'published','a.published',
'rating', 'a.rating',
'category_title', 'category_title'
);
}
parent::__construct($config);
}
protected function populateState($ordering = null, $direction = null)
{
// Initialise variables.
$app = JFactory::getApplication('administrator');
// Load the filter state.
$search = $app->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
$this->setState('filter.search', $search);
/*
$accessId = $app->getUserStateFromRequest($this->context.'.filter.access', 'filter_access', null, 'int');
$this->setState('filter.access', $accessId);
$state = $app->getUserStateFromRequest($this->context.'.filter.state', 'filter_published', '', 'string');
$this->setState('filter.state', $state);
*/
$categoryId = $app->getUserStateFromRequest($this->context.'.filter.category_id', 'filter_category_id', null);
$this->setState('filter.category_id', $categoryId);
/*
$language = $app->getUserStateFromRequest($this->context.'.filter.language', 'filter_language', '');
$this->setState('filter.language', $language);
*/
// Load the parameters.
$params = JComponentHelper::getParams('com_phocagallery');
$this->setState('params', $params);
// List state information.
parent::populateState('ua.username', 'asc');
}
protected function getStoreId($id = '')
{
// Compile the store id.
$id .= ':'.$this->getState('filter.search');
//$id .= ':'.$this->getState('filter.access');
//$id .= ':'.$this->getState('filter.state');
$id .= ':'.$this->getState('filter.category_id');
return parent::getStoreId($id);
}
protected function getListQuery()
{
/*
$query = ' SELECT a.*, cc.title AS category, ua.name AS editor, u.id AS ratinguserid, u.username AS ratingusername '
. ' FROM #__phocagallery_votes AS a '
. ' LEFT JOIN #__phocagallery_categories AS cc ON cc.id = a.catid '
. ' LEFT JOIN #__users AS ua ON ua.id = a.checked_out '
. ' LEFT JOIN #__users AS u ON u.id = a.userid'
. $where
. ' GROUP by a.id'
. $orderby
;
*/
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
// Select the required fields from the table.
$query->select(
$this->getState(
'list.select',
'a.*'
)
);
$query->from('`#__phocagallery_votes` AS a');
// Join over the language
$query->select('l.title AS language_title');
$query->join('LEFT', '`#__languages` AS l ON l.lang_code = a.language');
// Join over the users for the checked out user.
$query->select('ua.id AS ratinguserid, ua.username AS ratingusername, ua.name AS ratingname');
$query->join('LEFT', '#__users AS ua ON ua.id=a.userid');
$query->select('uc.name AS editor');
$query->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');
/* // Join over the asset groups.
$query->select('ag.title AS access_level');
$query->join('LEFT', '#__viewlevels AS ag ON ag.id = a.access');
*/
// Join over the categories.
$query->select('c.title AS category_title, c.id AS category_id');
$query->join('LEFT', '#__phocagallery_categories AS c ON c.id = a.catid');
// Filter by access level.
/* if ($access = $this->getState('filter.access')) {
$query->where('a.access = '.(int) $access);
}*/
// Filter by published state.
$published = $this->getState('filter.state');
if (is_numeric($published)) {
$query->where('a.published = '.(int) $published);
}
else if ($published === '') {
$query->where('(a.published IN (0, 1))');
}
// Filter by category.
$categoryId = $this->getState('filter.category_id');
if (is_numeric($categoryId)) {
$query->where('a.catid = ' . (int) $categoryId);
}
// Filter by search in title
$search = $this->getState('filter.search');
if (!empty($search))
{
if (stripos($search, 'id:') === 0) {
$query->where('a.id = '.(int) substr($search, 3));
}
else
{
$search = $db->Quote('%'.$db->escape($search, true).'%');
$query->where('( ua.name LIKE '.$search.' OR ua.username LIKE '.$search.')');
}
}
//$query->group('a.id');
// Add the list ordering clause.
$orderCol = $this->state->get('list.ordering');
$orderDirn = $this->state->get('list.direction');
if ($orderCol == 'a.ordering' || $orderCol == 'category_title') {
$orderCol = 'category_title '.$orderDirn.', a.ordering';
}
$query->order($db->escape($orderCol.' '.$orderDirn));
//echo nl2br(str_replace('#__','jos_',$query));
return $query;
}
function delete($cid = array()) {
if (count( $cid )) {
\Joomla\Utilities\ArrayHelper::toInteger($cid);
$cids = implode( ',', $cid );
//Select affected catids
$query = 'SELECT v.catid AS catid'
. ' FROM #__phocagallery_votes AS v'
. ' WHERE v.id IN ( '.$cids.' )';
$catids = $this->_getList($query);
//Delete it from DB
$query = 'DELETE FROM #__phocagallery_votes'
. ' WHERE id IN ( '.$cids.' )';
$this->_db->setQuery( $query );
if(!$this->_db->query()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
phocagalleryimport('phocagallery.rate.ratecategory');
foreach ($catids as $valueCatid) {
$updated = PhocaGalleryRateCategory::updateVoteStatistics( $valueCatid->catid );
if(!$updated) {
return false;
}
}
}
return true;
}
protected function prepareTable($table)
{
jimport('joomla.filter.output');
$date = JFactory::getDate();
$user = JFactory::getUser();
$table->title = htmlspecialchars_decode($table->title, ENT_QUOTES);
$table->alias = \JApplicationHelper::stringURLSafe($table->alias);
if (empty($table->alias)) {
$table->alias = \JApplicationHelper::stringURLSafe($table->title);
}
if (empty($table->id)) {
// Set the values
//$table->created = $date->toSql();
// Set ordering to the last item if not set
if (empty($table->ordering)) {
$db = JFactory::getDbo();
$db->setQuery('SELECT MAX(ordering) FROM #__phocagallery_votes WHERE catid = '.(int) $table->catid);
$max = $db->loadResult();
$table->ordering = $max+1;
}
}
else {
// Set the values
//$table->modified = $date->toSql();
//$table->modified_by = $user->get('id');
}
}
}
?>
| renebentes/joomla-3.x | administrator/components/com_phocagallery/models/phocagalleryra.php | PHP | gpl-2.0 | 7,227 |
/**************************************************************************
Copyright (C) 2000 - 2010 Novell, Inc.
All Rights Reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; 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.
**************************************************************************/
/*---------------------------------------------------------------------\
| |
| __ __ ____ _____ ____ |
| \ \ / /_ _/ ___|_ _|___ \ |
| \ V / _` \___ \ | | __) | |
| | | (_| |___) || | / __/ |
| |_|\__,_|____/ |_| |_____| |
| |
| core system |
| (c) SuSE Linux AG |
\----------------------------------------------------------------------/
File: YQZyppSolverDialogPluginStub.cc
Authors: Stefan Schubert <schubi@suse.de>
Textdomain "qt-pkg"
/-*/
#include <qmessagebox.h>
#include "YQZyppSolverDialogPluginStub.h"
#define YUILogComponent "qt-ui"
#include "YUILog.h"
#include "YQi18n.h"
#define PLUGIN_BASE_NAME "qt_zypp_solver_dialog"
using std::endl;
YQZyppSolverDialogPluginStub::YQZyppSolverDialogPluginStub()
: YUIPlugin( PLUGIN_BASE_NAME )
{
if ( success() )
{
yuiMilestone() << "Loaded " << PLUGIN_BASE_NAME
<< " plugin successfully from " << pluginLibFullPath()
<< endl;
}
impl = (YQZyppSolverDialogPluginIf*) locateSymbol("ZYPPDIALOGP");
if ( ! impl )
{
yuiError() << "Plugin " << PLUGIN_BASE_NAME << " does not provide ZYPPP symbol" << endl;
}
}
YQZyppSolverDialogPluginStub::~YQZyppSolverDialogPluginStub()
{
// NOP
}
bool
YQZyppSolverDialogPluginStub::createZyppSolverDialog( const zypp::PoolItem item )
{
if ( ! impl )
{
QMessageBox::information( 0,
_("Missing package") ,
_("Package libqdialogsolver is required for this feature."));
return false;
}
return impl->createZyppSolverDialog( item );
}
| gabi2/libyui-qt-pkg | src/YQZyppSolverDialogPluginStub.cc | C++ | gpl-2.0 | 2,581 |
package org.webbuilder.web.service.script;
import org.springframework.stereotype.Service;
import org.webbuilder.utils.script.engine.DynamicScriptEngine;
import org.webbuilder.utils.script.engine.DynamicScriptEngineFactory;
import org.webbuilder.utils.script.engine.ExecuteResult;
import org.webbuilder.web.po.script.DynamicScript;
import javax.annotation.Resource;
import java.util.Map;
/**
* Created by 浩 on 2015-10-29 0029.
*/
@Service
public class DynamicScriptExecutor {
@Resource
private DynamicScriptService dynamicScriptService;
public ExecuteResult exec(String id, Map<String, Object> param) throws Exception {
DynamicScript data = dynamicScriptService.selectByPk(id);
if (data == null) {
ExecuteResult result = new ExecuteResult();
result.setResult(String.format("script %s not found!", id));
result.setSuccess(false);
return result;
}
DynamicScriptEngine engine = DynamicScriptEngineFactory.getEngine(data.getType());
return engine.execute(id, param);
}
}
| wb-goup/webbuilder | wb-core/src/main/java/org/webbuilder/web/service/script/DynamicScriptExecutor.java | Java | gpl-2.0 | 1,079 |
/*
* Copyright (C) 2013-2016 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public License
* version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
package org.n52.io.measurement.img;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Before;
import org.junit.Test;
import org.n52.io.IoStyleContext;
import org.n52.io.MimeType;
import org.n52.io.request.RequestSimpleParameterSet;
import org.n52.io.response.dataset.DataCollection;
import org.n52.io.response.dataset.measurement.MeasurementData;
public class ChartRendererTest {
private static final String VALID_ISO8601_RELATIVE_START = "PT6H/2013-08-13TZ";
private static final String VALID_ISO8601_ABSOLUTE_START = "2013-07-13TZ/2013-08-13TZ";
private static final String VALID_ISO8601_DAYLIGHT_SAVING_SWITCH = "2013-10-28T02:00:00+02:00/2013-10-28T02:00:00+01:00";
private MyChartRenderer chartRenderer;
@Before
public void
setUp() {
this.chartRenderer = new MyChartRenderer(IoStyleContext.createEmpty());
}
@Test
public void
shouldParseBeginFromIso8601PeriodWithRelativeStart() {
Date start = chartRenderer.getStartTime(VALID_ISO8601_RELATIVE_START);
assertThat(start, is(DateTime.parse("2013-08-13TZ").minusHours(6).toDate()));
}
@Test
public void
shouldParseBeginFromIso8601PeriodWithAbsoluteStart() {
Date start = chartRenderer.getStartTime(VALID_ISO8601_ABSOLUTE_START);
assertThat(start, is(DateTime.parse("2013-08-13TZ").minusMonths(1).toDate()));
}
@Test
public void
shouldParseBeginAndEndFromIso8601PeriodContainingDaylightSavingTimezoneSwith() {
Date start = chartRenderer.getStartTime(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH);
Date end = chartRenderer.getEndTime(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH);
assertThat(start, is(DateTime.parse("2013-10-28T00:00:00Z").toDate()));
assertThat(end, is(DateTime.parse("2013-10-28T01:00:00Z").toDate()));
}
@Test
public void
shouldHaveCETTimezoneIncludedInDomainAxisLabel() {
IoStyleContext context = IoStyleContext.createEmpty();
context.getChartStyleDefinitions().setTimespan(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH);
this.chartRenderer = new MyChartRenderer(context);
String label = chartRenderer.getXYPlot().getDomainAxis().getLabel();
assertThat(label, is("Time (+01:00)"));
}
@Test
public void
shouldHandleEmptyTimespanWhenIncludingTimezoneInDomainAxisLabel() {
IoStyleContext context = IoStyleContext.createEmpty();
context.getChartStyleDefinitions().setTimespan(null);
this.chartRenderer = new MyChartRenderer(context);
String label = chartRenderer.getXYPlot().getDomainAxis().getLabel();
//assertThat(label, is("Time (+01:00)"));
}
@Test
public void
shouldHaveUTCTimezoneIncludedInDomainAxisLabel() {
IoStyleContext context = IoStyleContext.createEmpty();
context.getChartStyleDefinitions().setTimespan(VALID_ISO8601_ABSOLUTE_START);
this.chartRenderer = new MyChartRenderer(context);
String label = chartRenderer.getXYPlot().getDomainAxis().getLabel();
ISODateTimeFormat.dateTimeParser().withOffsetParsed().parseDateTime(VALID_ISO8601_ABSOLUTE_START.split("/")[1]);
assertThat(label, is("Time (UTC)"));
}
static class MyChartRenderer extends ChartIoHandler {
public MyChartRenderer(IoStyleContext context) {
super(new RequestSimpleParameterSet(), null, context);
}
public MyChartRenderer() {
super(new RequestSimpleParameterSet(), null, null);
}
@Override
public void setMimeType(MimeType mimetype) {
throw new UnsupportedOperationException();
}
@Override
public void writeDataToChart(DataCollection<MeasurementData> data) {
throw new UnsupportedOperationException();
}
}
}
| ridoo/timeseries-api | io/src/test/java/org/n52/io/measurement/img/ChartRendererTest.java | Java | gpl-2.0 | 5,333 |
<?php
class highlighter {
public function register_shortcode($shortcodeName) {
function shortcode_highlighter($atts, $content = null) {
extract( shortcode_atts( array(
'type' => 'colored'
), $atts ) );
return "<span class='highlighted_".$type."'>".$content."</span>";
}
add_shortcode($shortcodeName, 'shortcode_highlighter');
}
}
#Shortcode name
$shortcodeName="highlighter";
#Compile UI for admin panel
#Don't change this line
$gt3_compileShortcodeUI = "<div class='whatInsert whatInsert_".$shortcodeName."'>".$gt3_defaultUI."</div>";
#This function is executed each time when you click "Insert" shortcode button.
$gt3_compileShortcodeUI .= "
<table>
<tr>
<td>Type:</td>
<td>
<select name='".$shortcodeName."_separator_type' class='".$shortcodeName."_type'>";
if (is_array($GLOBALS["pbconfig"]['all_available_highlighters'])) {
foreach ($GLOBALS["pbconfig"]['all_available_highlighters'] as $value => $caption) {
$gt3_compileShortcodeUI .= "<option value='".$value."'>".$caption."</option>";
}
}
$gt3_compileShortcodeUI .= "</select>
</td>
</tr>
</table>
<script>
function ".$shortcodeName."_handler() {
/* YOUR CODE HERE */
var type = jQuery('.".$shortcodeName."_type').val();
/* END YOUR CODE */
/* COMPILE SHORTCODE LINE */
var compileline = '[".$shortcodeName." type=\"'+type+'\"][/".$shortcodeName."]';
/* DO NOT CHANGE THIS LINE */
jQuery('.whatInsert_".$shortcodeName."').html(compileline);
}
</script>
";
#Register shortcode & set parameters
$highlighter = new highlighter();
$highlighter->register_shortcode($shortcodeName);
shortcodesUI::getInstance()->add('highlighter', array("name" => $shortcodeName, "caption" => "Highlighter", "handler" => $gt3_compileShortcodeUI));
unset($gt3_compileShortcodeUI);
?> | jasonglisson/susannerossi | wp-content/plugins/gt3-pagebuilder-custom/core/shortcodes/highlighter.php | PHP | gpl-2.0 | 1,874 |
<html>
<head>
<script>
window.onload = function() {
var d = new Date().getTime();
document.getElementById("tid").value = d;
};
</script>
</head>
<body>
<?php
if(isset($_GET['token']))
{
$token = $_GET['token'];
$name = $_GET['name'];
$token = $_GET['token'];
$token1 = substr($token,6);
$email = $_GET['email'];
$quantity = (int)1;
$currency = $_GET['curr'];
$fees = $_GET['fees'];
$server = 'http://'.$_SERVER['SERVER_NAME'];
?>
<form method="post" id="customerData" name="customerData" action="ccavRequestHandler.php">
<input type="text" name="tid" id="tid" readonly />
<input type="text" name="merchant_id" value="79450"/>
<input type="text" name="order_id" value="<?php echo trim($token1); ?>"/>
<input type="text" name="amount" value="<?php echo trim($fees); ?>"/>
<input type="text" name="currency" value="<?php echo trim($currency); ?>"/>
<input type="text" name="redirect_url" value="<?php echo $server.'/ccavenue/nonseam/ccavResponseHandler.php' ?>"/>
<input type="text" name="cancel_url" value="<?php echo $server.'/ccavenue/nonseam/ccavResponseHandler.php?payment=fail' ?>"/>
<input type="text" name="language" value="EN"/>
<input type="text" name="billing_name" value="<?php echo trim($name); ?>"/>
<input type="text" name="billing_email" value="<?php echo trim($email); ?>"/>
<input type="text" name="billing_address" value="Dummy Address. Please ignore details."/>
<input type="text" name="billing_city" value="Ignore City"/>
<input type="text" name="billing_state" value="Ignore State"/>
<input type="text" name="billing_country" value="India"/>
<input type="text" name="billing_zip" value="123456"/>
<input type="text" name="billing_tel" value="1234567891"/>
<input type="submit" value="CheckOut" />
<?php
}
?>
</form>
<script language='javascript'>document.customerData.submit();</script>
</body>
</html>
| luffy22/aisha | ccavenue/nonseam/ccavenue_payment.php | PHP | gpl-2.0 | 2,167 |
<?php
/**
* jsonRPCClient.php
*
* Written using the JSON RPC specification -
* http://json-rpc.org/wiki/specification
*
* @author Kacper Rowinski <krowinski@implix.com>
* http://implix.com
*/
class jsonRPCClient
{
protected $url = null, $is_debug = false, $parameters_structure = 'array';
/**
* Default options for curl
*
* @var array
*/
protected $curl_options = array(
CURLOPT_CONNECTTIMEOUT => 8,
CURLOPT_TIMEOUT => 8
);
/**
* Http error statuses
*
* Source: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
*
* @var array
*/
private $httpErrors = array(
400 => '400 Bad Request',
401 => '401 Unauthorized',
403 => '403 Forbidden',
404 => '404 Not Found',
405 => '405 Method Not Allowed',
406 => '406 Not Acceptable',
408 => '408 Request Timeout',
500 => '500 Internal Server Error',
502 => '502 Bad Gateway',
503 => '503 Service Unavailable'
);
/**
* Takes the connection parameter and checks for extentions
*
* @param string $pUrl - url name like http://example.com/
*/
public function __construct($pUrl)
{
$this->validate(false === extension_loaded('curl'), 'The curl extension must be loaded for using this class!');
$this->validate(false === extension_loaded('json'), 'The json extension must be loaded for using this class!');
// set an url to connect to
$this->url = $pUrl;
}
/**
* Return http error message
*
* @param $pErrorNumber
*
* @return string|null
*/
private function getHttpErrorMessage($pErrorNumber)
{
return isset($this->httpErrors[$pErrorNumber]) ? $this->httpErrors[$pErrorNumber] : null;
}
/**
* Set debug mode
*
* @param boolean $pIsDebug
*
* @return jsonRPCClient
*/
public function setDebug($pIsDebug)
{
$this->is_debug = !empty($pIsDebug);
return $this;
}
/**
* Set structure to use for parameters
*
* @param string $pParametersStructure 'array' or 'object'
*
* @throws UnexpectedValueException
* @return jsonRPCClient
*/
public function setParametersStructure($pParametersStructure)
{
if (in_array($pParametersStructure, array('array', 'object')))
{
$this->parameters_structure = $pParametersStructure;
}
else
{
throw new UnexpectedValueException('Invalid parameters structure type.');
}
return $this;
}
/**
* Set extra options for curl connection
*
* @param array $pOptionsArray
*
* @throws InvalidArgumentException
* @return jsonRPCClient
*/
public function setCurlOptions($pOptionsArray)
{
if (is_array($pOptionsArray))
{
$this->curl_options = $pOptionsArray + $this->curl_options;
}
else
{
throw new InvalidArgumentException('Invalid options type.');
}
return $this;
}
/**
* Performs a request and gets the results
*
* @param string $pMethod - A String containing the name of the method to be invoked.
* @param array $pParams - An Array of objects to pass as arguments to the method.
*
* @throws RuntimeException
* @return array
*/
public function __call($pMethod, $pParams)
{
static $requestId = 0;
// generating uniuqe id per process
$requestId++;
// check if given params are correct
$this->validate(false === is_scalar($pMethod), 'Method name has no scalar value');
$this->validate(false === is_array($pParams), 'Params must be given as array');
// send params as an object or an array
$pParams = ($this->parameters_structure == 'object') ? $pParams[0] : array_values($pParams);
// Request (method invocation)
$request = json_encode(array('jsonrpc' => '2.0', 'method' => $pMethod, 'params' => $pParams, 'id' => $requestId));
// if is_debug mode is true then add url and request to is_debug
$this->debug('Url: ' . $this->url . "\r\n", false);
$this->debug('Request: ' . $request . "\r\n", false);
$responseMessage = $this->getResponse($request);
// if is_debug mode is true then add response to is_debug and display it
$this->debug('Response: ' . $responseMessage . "\r\n", true);
// decode and create array ( can be object, just set to false )
$responseDecoded = json_decode($responseMessage, true);
// check if decoding json generated any errors
$jsonErrorMsg = $this->getJsonLastErrorMsg();
$this->validate( !is_null($jsonErrorMsg), $jsonErrorMsg . ': ' . $responseMessage);
// check if response is correct
$this->validate(empty($responseDecoded['id']), 'Invalid response data structure: ' . $responseMessage);
$this->validate($responseDecoded['id'] != $requestId, 'Request id: ' . $requestId . ' is different from Response id: ' . $responseDecoded['id']);
if (isset($responseDecoded['error']))
{
$errorMessage = 'Request have return error: ' . $responseDecoded['error']['message'] . '; ' . "\n" .
'Request: ' . $request . '; ';
if (isset($responseDecoded['error']['data']))
{
$errorMessage .= "\n" . 'Error data: ' . $responseDecoded['error']['data'];
}
$this->validate( !is_null($responseDecoded['error']), $errorMessage);
}
return $responseDecoded['result'];
}
/**
* When the method invocation completes, the service must reply with a response.
* The response is a single object serialized using JSON
*
* @param string $pRequest
*
* @throws RuntimeException
* @return string
*/
protected function & getResponse(&$pRequest)
{
// do the actual connection
$ch = curl_init();
if ( !$ch)
{
throw new RuntimeException('Could\'t initialize a cURL session');
}
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $pRequest);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ( !curl_setopt_array($ch, $this->curl_options))
{
throw new RuntimeException('Error while setting curl options');
}
// send the request
$response = curl_exec($ch);
// check http status code
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (isset($this->httpErrors[$httpCode]))
{
throw new RuntimeException('Response Http Error - ' . $this->httpErrors[$httpCode]);
}
// check for curl error
if (0 < curl_errno($ch))
{
throw new RuntimeException('Unable to connect to '.$this->url . ' Error: ' . curl_error($ch));
}
// close the connection
curl_close($ch);
return $response;
}
/**
* Throws exception if validation is failed
*
* @param bool $pFailed
* @param string $pErrMsg
*
* @throws RuntimeException
*/
protected function validate($pFailed, $pErrMsg)
{
if ($pFailed)
{
throw new RuntimeException($pErrMsg);
}
}
/**
* For is_debug and performance stats
*
* @param string $pAdd
* @param bool $pShow
*/
protected function debug($pAdd, $pShow = false)
{
static $debug, $startTime;
// is_debug off return
if (false === $this->is_debug)
{
return;
}
// add
$debug .= $pAdd;
// get starttime
$startTime = empty($startTime) ? array_sum(explode(' ', microtime())) : $startTime;
if (true === $pShow and !empty($debug))
{
// get endtime
$endTime = array_sum(explode(' ', microtime()));
// performance summary
$debug .= 'Request time: ' . round($endTime - $startTime, 3) . ' s Memory usage: ' . round(memory_get_usage() / 1024) . " kb\r\n";
echo nl2br($debug);
// send output imidiately
flush();
// clean static
$debug = $startTime = null;
}
}
/**
* Getting JSON last error message
* Function json_last_error_msg exists from PHP 5.5
*
* @return string
*/
function getJsonLastErrorMsg()
{
if (!function_exists('json_last_error_msg'))
{
function json_last_error_msg()
{
static $errors = array(
JSON_ERROR_NONE => 'No error',
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
JSON_ERROR_SYNTAX => 'Syntax error',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
);
$error = json_last_error();
return array_key_exists($error, $errors) ? $errors[$error] : 'Unknown error (' . $error . ')';
}
}
// Fix PHP 5.2 error caused by missing json_last_error function
if (function_exists('json_last_error'))
{
return json_last_error() ? json_last_error_msg() : null;
}
else
{
return null;
}
}
}
| mssdeepakkumar/keenlo | wp-content/plugins/formcraft-add-on-pack/getresponse.php | PHP | gpl-2.0 | 9,967 |
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.bind.v2.util;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
/**
* {@link Stack}-like data structure that allows the following efficient operations:
*
* <ol>
* <li>Push/pop operation.
* <li>Duplicate check. When an object that's already in the stack is pushed,
* this class will tell you so.
* </ol>
*
* <p>
* Object equality is their identity equality.
*
* <p>
* This class implements {@link List} for accessing items in the stack,
* but {@link List} methods that alter the stack is not supported.
*
* @author Kohsuke Kawaguchi
*/
public final class CollisionCheckStack<E> extends AbstractList<E> {
private Object[] data;
private int[] next;
private int size = 0;
/**
* True if the check shall be done by using the object identity.
* False if the check shall be done with the equals method.
*/
private boolean useIdentity = true;
// for our purpose, there isn't much point in resizing this as we don't expect
// the stack to grow that much.
private final int[] initialHash;
public CollisionCheckStack() {
initialHash = new int[17];
data = new Object[16];
next = new int[16];
}
/**
* Set to false to use {@link Object#equals(Object)} to detect cycles.
* This method can be only used when the stack is empty.
*/
public void setUseIdentity(boolean useIdentity) {
this.useIdentity = useIdentity;
}
public boolean getUseIdentity() {
return useIdentity;
}
/**
* Pushes a new object to the stack.
*
* @return
* true if this object has already been pushed
*/
public boolean push(E o) {
if(data.length==size)
expandCapacity();
data[size] = o;
int hash = hash(o);
boolean r = findDuplicate(o, hash);
next[size] = initialHash[hash];
initialHash[hash] = size+1;
size++;
return r;
}
/**
* Pushes a new object to the stack without making it participate
* with the collision check.
*/
public void pushNocheck(E o) {
if(data.length==size)
expandCapacity();
data[size] = o;
next[size] = -1;
size++;
}
@Override
public E get(int index) {
return (E)data[index];
}
@Override
public int size() {
return size;
}
private int hash(Object o) {
return ((useIdentity?System.identityHashCode(o):o.hashCode())&0x7FFFFFFF) % initialHash.length;
}
/**
* Pops an object from the stack
*/
public E pop() {
size--;
Object o = data[size];
data[size] = null; // keeping references too long == memory leak
int n = next[size];
if(n<0) {
// pushed by nocheck. no need to update hash
} else {
int hash = hash(o);
assert initialHash[hash]==size+1;
initialHash[hash] = n;
}
return (E)o;
}
/**
* Returns the top of the stack.
*/
public E peek() {
return (E)data[size-1];
}
private boolean findDuplicate(E o, int hash) {
int p = initialHash[hash];
while(p!=0) {
p--;
Object existing = data[p];
if (useIdentity) {
if(existing==o) return true;
} else {
if (o.equals(existing)) return true;
}
p = next[p];
}
return false;
}
private void expandCapacity() {
int oldSize = data.length;
int newSize = oldSize * 2;
Object[] d = new Object[newSize];
int[] n = new int[newSize];
System.arraycopy(data,0,d,0,oldSize);
System.arraycopy(next,0,n,0,oldSize);
data = d;
next = n;
}
/**
* Clears all the contents in the stack.
*/
public void reset() {
if(size>0) {
size = 0;
Arrays.fill(initialHash,0);
}
}
/**
* String that represents the cycle.
*/
public String getCycleString() {
StringBuilder sb = new StringBuilder();
int i=size()-1;
E obj = get(i);
sb.append(obj);
Object x;
do {
sb.append(" -> ");
x = get(--i);
sb.append(x);
} while(obj!=x);
return sb.toString();
}
}
| samskivert/ikvm-openjdk | build/linux-amd64/impsrc/com/sun/xml/internal/bind/v2/util/CollisionCheckStack.java | Java | gpl-2.0 | 5,703 |
/*
* #%L
* OME SCIFIO package for reading and converting scientific file formats.
* %%
* Copyright (C) 2005 - 2012 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package loci.common;
import java.io.IOException;
/**
* A legacy delegator class for ome.scifio.common.IniWriter.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/common/src/loci/common/IniWriter.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/common/src/loci/common/IniWriter.java;hb=HEAD">Gitweb</a></dd></dl>
*
* @author Melissa Linkert melissa at glencoesoftware.com
*/
public class IniWriter {
// -- Fields --
private ome.scifio.common.IniWriter writer;
// -- Constructor --
public IniWriter() {
writer = new ome.scifio.common.IniWriter();
}
// -- IniWriter API methods --
/**
* Saves the given IniList to the given file.
* If the given file already exists, then the IniList will be appended.
*/
public void saveINI(IniList ini, String path) throws IOException {
writer.saveINI(ini.list, path);
}
/** Saves the given IniList to the given file. */
public void saveINI(IniList ini, String path, boolean append)
throws IOException
{
writer.saveINI(ini.list, path, append);
}
// -- Object delegators --
@Override
public boolean equals(Object obj) {
return writer.equals(obj);
}
@Override
public int hashCode() {
return writer.hashCode();
}
@Override
public String toString() {
return writer.toString();
}
}
| ximenesuk/bioformats | components/loci-legacy/src/loci/common/IniWriter.java | Java | gpl-2.0 | 3,258 |
var mysql_wn_data_noun_quantity = {
"morsel":[["noun.quantity"],["morsel","small indefinite quantity"]],
"section":[["noun.quantity","noun.group","noun.location","verb.contact:section","noun.group"],["section","square mile","section2","team","platoon1","section1","area1","section4","discussion section","class3"]],
"mate":[["noun.quantity","noun.person","noun.person","adj.all:friendly1^matey","noun.location:Australia","noun.location:Britain","noun.person","verb.contact:mate","noun.Tops:animal"],["mate","fellow","singleton","couple","mate2","first mate","officer4","mate3","friend","mate1"]],
"exposure":[["noun.quantity","verb.perception:expose1"],["exposure","light unit"]],
"parking":[["noun.quantity","verb.contact:park"],["parking","room"]],
"shtik":[["noun.quantity","noun.communication:Yiddish"],["shtik","shtick","schtik","schtick","small indefinite quantity"]],
"basket":[["noun.quantity","noun.artifact","noun.person:basketeer"],["basket","basketful","containerful","basket1","basketball hoop","hoop3","goal","basketball equipment"]],
"correction":[["noun.quantity","noun.communication"],["correction","fudge factor","indefinite quantity","correction1","editing"]],
"footstep":[["noun.quantity","verb.change:pace","verb.motion:pace1","verb.motion:pace","verb.change:step","verb.motion:step3","verb.motion:step1","verb.motion:step","verb.motion:stride3","verb.motion:stride"],["footstep","pace1","step","stride","indefinite quantity"]],
"addition":[["noun.quantity","verb.change:increase2","verb.change:increase"],["addition","increase","gain","indefinite quantity"]],
"circulation":[["noun.quantity","verb.motion:circulate3","noun.quantity","noun.cognition:library science"],["circulation","count","circulation1","count"]],
"breakage":[["noun.quantity"],["breakage","indefinite quantity"]],
"craps":[["noun.quantity"],["craps","snake eyes","two"]],
"utility":[["noun.quantity","noun.cognition:economics"],["utility","system of measurement"]],
"blood count":[["noun.quantity"],["blood count","count"]],
"sperm count":[["noun.quantity"],["sperm count","count"]],
"eyedrop":[["noun.quantity"],["eyedrop","eye-drop","drop"]],
"picking":[["noun.quantity","verb.contact:pick1"],["picking","pick","output"]],
"capacity":[["noun.quantity","adj.all:large^capacious","verb.stative:contain13"],["capacity","content","volume"]],
"pitcher":[["noun.quantity"],["pitcher","pitcherful","containerful"]],
"tankage":[["noun.quantity"],["tankage","indefinite quantity"]],
"nip":[["noun.quantity","verb.contact","noun.act:nip1"],["nip","shot","small indefinite quantity","nip2","bite"]],
"headroom":[["noun.quantity"],["headroom","headway","clearance","room"]],
"population":[["noun.quantity","noun.group","noun.Tops:group"],["population","integer","population1"]],
"nit":[["noun.quantity"],["nit","luminance unit"]],
"quetzal":[["noun.quantity"],["quetzal","Guatemalan monetary unit"]],
"lari":[["noun.quantity"],["lari","Georgian monetary unit"]],
"agora":[["noun.quantity"],["agora","shekel","Israeli monetary unit"]],
"barn":[["noun.quantity","noun.cognition:atomic physics"],["barn","b","area unit"]],
"barrow":[["noun.quantity"],["barrow","barrowful","containerful"]],
"basin":[["noun.quantity"],["basin","basinful","containerful"]],
"bit":[["noun.quantity","noun.artifact","noun.artifact"],["bit","unit of measurement","byte","bit1","stable gear","bridle","bit2","part","key"]],
"carton":[["noun.quantity"],["carton","cartonful","containerful"]],
"cordage":[["noun.quantity","noun.Tops:measure"],["cordage"]],
"cutoff":[["noun.quantity"],["cutoff","limit"]],
"dustpan":[["noun.quantity"],["dustpan","dustpanful","containerful"]],
"firkin":[["noun.quantity"],["firkin","British capacity unit","kilderkin"]],
"flask":[["noun.quantity"],["flask","flaskful","containerful"]],
"frail":[["noun.quantity"],["frail","weight unit"]],
"keg":[["noun.quantity"],["keg","kegful","containerful"]],
"kettle":[["noun.quantity","noun.artifact","noun.person:tympanist","noun.person:timpanist","noun.person:tympanist","noun.person:timpanist","adj.pert:tympanic1","noun.person:timpanist"],["kettle","kettleful","containerful","kettle1","kettledrum","tympanum","tympani","timpani","percussion instrument"]],
"load":[["noun.quantity","noun.artifact","verb.contact","noun.artifact:load","noun.artifact:load2","noun.person:loader","noun.act:loading","noun.artifact:lading","verb.change:fill1","verb.possession","noun.cognition:computer science","verb.contact","noun.artifact:load1","noun.person:loader1","noun.artifact:charge","verb.change:fill1","verb.contact","noun.artifact:load2","noun.artifact:load","noun.person:loader","noun.act:loading"],["load","loading","indefinite quantity","load3","electrical device","load1","lade1","laden1","load up","frames:1","21","load12","transfer1","load2","charge2","load10","put"]],
"reservoir":[["noun.quantity","noun.artifact","noun.object:lake"],["reservoir","supply","reservoir1","artificial lake","man-made lake","water system"]],
"seventy-eight":[["noun.quantity"],["seventy-eight","78\"","LXXVIII","large integer"]],
"sextant":[["noun.quantity","noun.attribute:circumference1"],["sextant","angular unit"]],
"singleton":[["noun.quantity"],["singleton","one"]],
"skeleton":[["noun.quantity"],["skeleton","minimum"]],
"standard":[["noun.quantity","verb.change:standardize","verb.change:standardise"],["standard","volume unit"]],
"teacup":[["noun.quantity"],["teacup","teacupful","containerful"]],
"thimble":[["noun.quantity"],["thimble","thimbleful","containerful"]],
"tub":[["noun.quantity"],["tub","tubful","containerful"]],
"twenty-two":[["noun.quantity"],["twenty-two","22\"","XXII","large integer"]],
"yard":[["noun.quantity","verb.change:pace","noun.location","noun.artifact","noun.location:field","noun.artifact","noun.location:tract"],["yard","pace","linear unit","fathom1","chain","rod1","lea","yard1","tract","yard2","grounds","curtilage","yard3","railway yard","railyard"]],
"yarder":[["noun.quantity","noun.communication:combining form"],["yarder","linear unit"]],
"common denominator":[["noun.quantity"],["common denominator","denominator"]],
"volume":[["noun.quantity","adj.all:large^voluminous","noun.Tops:quantity","noun.quantity","noun.Tops:quantity"],["volume","volume1"]],
"magnetization":[["noun.quantity","verb.communication:magnetize","verb.change:magnetize","noun.Tops:measure"],["magnetization","magnetisation"]],
"precipitation":[["noun.quantity","verb.weather:precipitate"],["precipitation","indefinite quantity"]],
"degree":[["noun.quantity","noun.state","noun.Tops:state","noun.quantity"],["degree","arcdegree","angular unit","oxtant","sextant","degree1","level","stage","point","degree3","temperature unit"]],
"solubility":[["noun.quantity","adj.all:soluble1","noun.substance:solution"],["solubility","definite quantity"]],
"lumen":[["noun.quantity"],["lumen","lm","luminous flux unit"]],
"headful":[["noun.quantity"],["headful","containerful"]],
"palm":[["noun.quantity","verb.contact:palm"],["palm","linear unit"]],
"digit":[["noun.quantity","verb.change:digitize","verb.change:digitise","verb.change:digitalize"],["digit","figure","integer"]],
"point system":[["noun.quantity"],["point system","system of measurement"]],
"constant":[["noun.quantity"],["constant","number"]],
"one":[["noun.quantity"],["one","1\"","I","ace","single","unity","digit"]],
"region":[["noun.quantity","noun.location","noun.Tops:location"],["region","neighborhood","indefinite quantity","region1"]],
"word":[["noun.quantity","noun.communication","verb.communication:word","noun.communication"],["word","kilobyte","computer memory unit","word3","statement","word6","order3"]],
"quota":[["noun.quantity"],["quota","number"]],
"dollar":[["noun.quantity","noun.possession"],["dollar","monetary unit","dollar1","coin2"]],
"e":[["noun.quantity"],["e","transcendental number"]],
"gamma":[["noun.quantity"],["gamma","oersted","field strength unit"]],
"pi":[["noun.quantity"],["pi","transcendental number"]],
"radical":[["noun.quantity","noun.Tops:measure","noun.cognition:mathematics"],["radical"]],
"pascal":[["noun.quantity"],["pascal","Pa","pressure unit"]],
"guarani":[["noun.quantity"],["guarani","Paraguayan monetary unit"]],
"pengo":[["noun.quantity"],["pengo","Hungarian monetary unit"]],
"outage":[["noun.quantity"],["outage","indefinite quantity"]],
"couple":[["noun.quantity","verb.contact:couple2","verb.contact:pair3","verb.contact:pair4","verb.contact","noun.artifact:coupler","noun.artifact:coupling"],["couple","pair","twosome","twain","brace","span2","yoke","couplet","distich","duo","duet","dyad","duad","two","couple1","uncouple","couple on","couple up","attach1"]],
"yuan":[["noun.quantity"],["yuan","kwai","Chinese monetary unit"]],
"battalion":[["noun.quantity","adj.all:incalculable^multitudinous"],["battalion","large number","multitude","plurality1","pack","large indefinite quantity"]],
"moiety":[["noun.quantity"],["moiety","mediety","one-half"]],
"maximum":[["noun.quantity","verb.change:maximize1","verb.change:maximize","verb.change:maximise1","verb.change:maximise"],["maximum","minimum","upper limit","extremum","large indefinite quantity"]],
"minimum":[["noun.quantity","verb.communication:minimize1","verb.communication:minimize","verb.change:minimize","verb.communication:minimise1","verb.change:minimise"],["minimum","maximum","lower limit","extremum","small indefinite quantity"]],
"cordoba":[["noun.quantity"],["cordoba","Nicaraguan monetary unit"]],
"troy":[["noun.quantity"],["troy","troy weight","system of weights"]],
"acre":[["noun.quantity","noun.location"],["acre","area unit","Acre1","district","Brazil"]],
"sucre":[["noun.quantity"],["sucre","Ecuadoran monetary unit"]],
"tanga":[["noun.quantity"],["tanga","Tajikistani monetary unit"]],
"lepton":[["noun.quantity"],["lepton","drachma","Greek monetary unit"]],
"ocean":[["noun.quantity","adj.all:unlimited^oceanic"],["ocean","sea","large indefinite quantity"]],
"para":[["noun.quantity"],["para","Yugoslavian monetary unit","Yugoslavian dinar"]],
"swath":[["noun.quantity","noun.shape:space"],["swath"]],
"bel":[["noun.quantity"],["Bel","B3","sound unit"]],
"denier":[["noun.quantity"],["denier","unit of measurement"]],
"miler":[["noun.quantity","noun.quantity:mile6","noun.quantity:mile5","noun.quantity:mile4","noun.quantity:mile3","noun.quantity:mile2","noun.quantity:mile1","noun.event:mile","noun.communication:combining form"],["miler","linear unit"]],
"welterweight":[["noun.quantity","noun.person","noun.person"],["welterweight","weight unit","welterweight1","wrestler","welterweight2","boxer"]],
"balboa":[["noun.quantity"],["balboa","Panamanian monetary unit"]],
"bolivar":[["noun.quantity"],["bolivar","Venezuelan monetary unit"]],
"cicero":[["noun.quantity"],["cicero","linear unit"]],
"coulomb":[["noun.quantity"],["coulomb","C","ampere-second","charge unit","abcoulomb","ampere-minute"]],
"curie":[["noun.quantity","noun.person"],["curie","Ci","radioactivity unit","Curie1","Pierre Curie","physicist"]],
"gauss":[["noun.quantity"],["gauss","flux density unit","tesla"]],
"gilbert":[["noun.quantity","noun.person","noun.person","noun.person","adj.pert:gilbertian"],["gilbert","Gb1","Gi","magnetomotive force unit","Gilbert1","Humphrey Gilbert","Sir Humphrey Gilbert","navigator","Gilbert2","William Gilbert","physician","physicist","Gilbert3","William Gilbert1","William S. Gilbert","William Schwenk Gilbert","Sir William Gilbert","librettist","poet"]],
"gram":[["noun.quantity"],["gram","gramme","gm","g","metric weight unit","dekagram"]],
"henry":[["noun.quantity","noun.person","noun.person"],["henry","H","inductance unit","Henry1","Patrick Henry","American Revolutionary leader","orator","Henry2","William Henry","chemist"]],
"joule":[["noun.quantity"],["joule","J","watt second","work unit"]],
"kelvin":[["noun.quantity"],["kelvin","K5","temperature unit"]],
"lambert":[["noun.quantity"],["lambert","L7","illumination unit"]],
"langley":[["noun.quantity"],["langley","unit of measurement"]],
"maxwell":[["noun.quantity"],["maxwell","Mx","flux unit","weber"]],
"newton":[["noun.quantity"],["newton","N1","force unit","sthene"]],
"oersted":[["noun.quantity"],["oersted","field strength unit"]],
"ohm":[["noun.quantity","adj.pert:ohmic"],["ohm","resistance unit","megohm"]],
"rand":[["noun.quantity"],["rand","South African monetary unit"]],
"roentgen":[["noun.quantity"],["roentgen","R","radioactivity unit"]],
"rutherford":[["noun.quantity","noun.person"],["rutherford","radioactivity unit","Rutherford1","Daniel Rutherford","chemist"]],
"sabin":[["noun.quantity"],["sabin","absorption unit"]],
"tesla":[["noun.quantity"],["tesla","flux density unit"]],
"watt":[["noun.quantity"],["watt","W","power unit","kilowatt","horsepower"]],
"weber":[["noun.quantity","noun.person","noun.person","noun.person","noun.person"],["weber","Wb","flux unit","Weber1","Carl Maria von Weber","Baron Karl Maria Friedrich Ernst von Weber","conductor","composer","Weber2","Max Weber","sociologist","Weber3","Max Weber1","painter","Weber4","Wilhelm Eduard Weber","physicist"]],
"scattering":[["noun.quantity","verb.contact:sprinkle1"],["scattering","sprinkling","small indefinite quantity"]],
"accretion":[["noun.quantity","adj.all:increasing^accretionary","noun.process","adj.all:increasing^accretionary","noun.cognition:geology","noun.process","adj.all:increasing^accretionary","verb.change:accrete1","noun.cognition:biology","noun.process","adj.all:increasing^accretionary","noun.cognition:astronomy"],["accretion","addition","accretion1","increase","accretion2","increase","accretion3","increase"]],
"dividend":[["noun.quantity"],["dividend","number"]],
"linage":[["noun.quantity"],["linage","lineage","number"]],
"penny":[["noun.quantity"],["penny","fractional monetary unit","Irish pound","British pound"]],
"double eagle":[["noun.quantity","noun.act:golf"],["double eagle","score"]],
"spoilage":[["noun.quantity"],["spoilage","indefinite quantity"]],
"fundamental quantity":[["noun.quantity","noun.Tops:measure"],["fundamental quantity","fundamental measure"]],
"definite quantity":[["noun.quantity","noun.Tops:measure"],["definite quantity"]],
"indefinite quantity":[["noun.quantity","noun.Tops:measure"],["indefinite quantity"]],
"relative quantity":[["noun.quantity","noun.Tops:measure"],["relative quantity"]],
"system of measurement":[["noun.quantity","noun.Tops:measure"],["system of measurement","metric"]],
"system of weights and measures":[["noun.quantity"],["system of weights and measures","system of measurement"]],
"british imperial system":[["noun.quantity"],["British Imperial System","English system","British system","system of weights and measures"]],
"metric system":[["noun.quantity"],["metric system","system of weights and measures"]],
"cgs":[["noun.quantity"],["cgs","cgs system","metric system"]],
"systeme international d'unites":[["noun.quantity"],["Systeme International d'Unites","Systeme International","SI system","SI","SI unit","International System of Units","International System","metric system"]],
"united states customary system":[["noun.quantity"],["United States Customary System","system of weights and measures"]],
"information measure":[["noun.quantity"],["information measure","system of measurement"]],
"bandwidth":[["noun.quantity"],["bandwidth","information measure"]],
"baud":[["noun.quantity","noun.cognition:computer science"],["baud","baud rate","information measure"]],
"octane number":[["noun.quantity","noun.Tops:measure"],["octane number","octane rating"]],
"marginal utility":[["noun.quantity","noun.cognition:economics"],["marginal utility","utility"]],
"enough":[["noun.quantity","adj.all:sufficient^enough","adj.all:sufficient","verb.stative:suffice"],["enough","sufficiency","relative quantity"]],
"absolute value":[["noun.quantity"],["absolute value","numerical value","definite quantity"]],
"acid value":[["noun.quantity","noun.cognition:chemistry"],["acid value","definite quantity"]],
"chlorinity":[["noun.quantity"],["chlorinity","definite quantity"]],
"quire":[["noun.quantity"],["quire","definite quantity","ream"]],
"toxicity":[["noun.quantity","adj.all:toxic"],["toxicity","definite quantity"]],
"cytotoxicity":[["noun.quantity"],["cytotoxicity","toxicity"]],
"unit of measurement":[["noun.quantity","verb.social:unitize","verb.change:unitize"],["unit of measurement","unit","definite quantity"]],
"measuring unit":[["noun.quantity"],["measuring unit","measuring block","unit of measurement"]],
"diopter":[["noun.quantity"],["diopter","dioptre","unit of measurement"]],
"karat":[["noun.quantity"],["karat","carat2","kt","unit of measurement"]],
"decimal":[["noun.quantity","verb.change:decimalize","verb.change:decimalise"],["decimal1","number"]],
"avogadro's number":[["noun.quantity"],["Avogadro's number","Avogadro number","constant"]],
"boltzmann's constant":[["noun.quantity"],["Boltzmann's constant","constant"]],
"coefficient":[["noun.quantity"],["coefficient","constant"]],
"absorption coefficient":[["noun.quantity"],["absorption coefficient","coefficient of absorption","absorptance","coefficient"]],
"drag coefficient":[["noun.quantity"],["drag coefficient","coefficient of drag","coefficient"]],
"coefficient of friction":[["noun.quantity"],["coefficient of friction","coefficient"]],
"coefficient of mutual induction":[["noun.quantity"],["coefficient of mutual induction","mutual inductance","coefficient"]],
"coefficient of self induction":[["noun.quantity"],["coefficient of self induction","self-inductance","coefficient"]],
"modulus":[["noun.quantity","noun.cognition:physics","noun.quantity","noun.quantity"],["modulus","coefficient","modulus1","absolute value","modulus2","integer"]],
"coefficient of elasticity":[["noun.quantity","noun.cognition:physics"],["coefficient of elasticity","modulus of elasticity","elastic modulus","modulus"]],
"bulk modulus":[["noun.quantity"],["bulk modulus","coefficient of elasticity"]],
"modulus of rigidity":[["noun.quantity"],["modulus of rigidity","coefficient of elasticity"]],
"young's modulus":[["noun.quantity"],["Young's modulus","coefficient of elasticity"]],
"coefficient of expansion":[["noun.quantity"],["coefficient of expansion","expansivity","coefficient"]],
"coefficient of reflection":[["noun.quantity"],["coefficient of reflection","reflection factor","reflectance","reflectivity","coefficient"]],
"transmittance":[["noun.quantity"],["transmittance","transmission","coefficient"]],
"coefficient of viscosity":[["noun.quantity"],["coefficient of viscosity","absolute viscosity","dynamic viscosity","coefficient"]],
"cosmological constant":[["noun.quantity"],["cosmological constant","constant"]],
"equilibrium constant":[["noun.quantity","noun.cognition:chemistry"],["equilibrium constant","constant"]],
"dissociation constant":[["noun.quantity"],["dissociation constant","equilibrium constant"]],
"gas constant":[["noun.quantity","noun.cognition:physics"],["gas constant","universal gas constant","R1","constant"]],
"gravitational constant":[["noun.quantity","noun.cognition:law of gravitation","noun.cognition:physics"],["gravitational constant","universal gravitational constant","constant of gravitation","G8","constant"]],
"hubble's constant":[["noun.quantity","noun.cognition:cosmology"],["Hubble's constant","Hubble constant","Hubble's parameter","Hubble parameter","constant"]],
"ionic charge":[["noun.quantity"],["ionic charge","constant"]],
"planck's constant":[["noun.quantity"],["Planck's constant","h1","factor of proportionality"]],
"oxidation number":[["noun.quantity"],["oxidation number","oxidation state","number"]],
"cardinality":[["noun.quantity","noun.cognition:mathematics"],["cardinality","number"]],
"body count":[["noun.quantity"],["body count","count"]],
"head count":[["noun.quantity"],["head count","headcount","count"]],
"pollen count":[["noun.quantity"],["pollen count","count"]],
"conversion factor":[["noun.quantity"],["conversion factor","factor1"]],
"factor of proportionality":[["noun.quantity"],["factor of proportionality","constant of proportionality","factor1","constant"]],
"fibonacci number":[["noun.quantity"],["Fibonacci number","number"]],
"prime factor":[["noun.quantity"],["prime factor","divisor1"]],
"prime number":[["noun.quantity"],["prime number","prime"]],
"composite number":[["noun.quantity"],["composite number","number"]],
"double-bogey":[["noun.quantity","verb.contact:double bogey","noun.act:golf"],["double-bogey","score"]],
"compound number":[["noun.quantity"],["compound number","number"]],
"ordinal number":[["noun.quantity","adj.all:ordinal"],["ordinal number","ordinal","no.","number"]],
"cardinal number":[["noun.quantity"],["cardinal number","cardinal","number"]],
"floating-point number":[["noun.quantity"],["floating-point number","number"]],
"fixed-point number":[["noun.quantity"],["fixed-point number","number"]],
"googol":[["noun.quantity"],["googol","cardinal number"]],
"googolplex":[["noun.quantity"],["googolplex","cardinal number"]],
"atomic number":[["noun.quantity"],["atomic number","number"]],
"magic number":[["noun.quantity"],["magic number","atomic number"]],
"baryon number":[["noun.quantity"],["baryon number","number"]],
"long measure":[["noun.quantity"],["long measure","linear unit"]],
"magnetic flux":[["noun.quantity"],["magnetic flux","magnetization"]],
"absorption unit":[["noun.quantity"],["absorption unit","unit of measurement"]],
"acceleration unit":[["noun.quantity"],["acceleration unit","unit of measurement"]],
"angular unit":[["noun.quantity"],["angular unit","unit of measurement"]],
"area unit":[["noun.quantity"],["area unit","square measure","unit of measurement"]],
"volume unit":[["noun.quantity"],["volume unit","capacity unit","capacity measure","cubage unit","cubic measure","cubic content unit","displacement unit","cubature unit","unit of measurement","volume"]],
"cubic inch":[["noun.quantity"],["cubic inch","cu in","volume unit"]],
"cubic foot":[["noun.quantity"],["cubic foot","cu ft","volume unit"]],
"computer memory unit":[["noun.quantity"],["computer memory unit","unit of measurement"]],
"electromagnetic unit":[["noun.quantity"],["electromagnetic unit","emu","unit of measurement"]],
"explosive unit":[["noun.quantity"],["explosive unit","unit of measurement"]],
"force unit":[["noun.quantity"],["force unit","unit of measurement"]],
"linear unit":[["noun.quantity"],["linear unit","linear measure","unit of measurement"]],
"metric unit":[["noun.quantity"],["metric unit","metric1","unit of measurement"]],
"miles per gallon":[["noun.quantity"],["miles per gallon","unit of measurement"]],
"monetary unit":[["noun.quantity"],["monetary unit","unit of measurement"]],
"megaflop":[["noun.quantity","noun.cognition:computer science"],["megaflop","MFLOP","million floating point operations per second","unit of measurement","teraflop"]],
"teraflop":[["noun.quantity","noun.cognition:computer science"],["teraflop","trillion floating point operations per second","unit of measurement"]],
"mips":[["noun.quantity","noun.cognition:computer science"],["MIPS","million instructions per second","unit of measurement"]],
"pain unit":[["noun.quantity"],["pain unit","unit of measurement"]],
"pressure unit":[["noun.quantity"],["pressure unit","unit of measurement"]],
"printing unit":[["noun.quantity"],["printing unit","unit of measurement"]],
"sound unit":[["noun.quantity"],["sound unit","unit of measurement"]],
"telephone unit":[["noun.quantity"],["telephone unit","unit of measurement"]],
"temperature unit":[["noun.quantity"],["temperature unit","unit of measurement"]],
"weight unit":[["noun.quantity"],["weight unit","weight","unit of measurement"]],
"mass unit":[["noun.quantity"],["mass unit","unit of measurement"]],
"unit of viscosity":[["noun.quantity"],["unit of viscosity","unit of measurement"]],
"work unit":[["noun.quantity"],["work unit","heat unit","energy unit","unit of measurement"]],
"brinell number":[["noun.quantity"],["Brinell number","unit of measurement"]],
"brix scale":[["noun.quantity"],["Brix scale","system of measurement"]],
"set point":[["noun.quantity","noun.act:tennis"],["set point","point1"]],
"match point":[["noun.quantity","noun.act:tennis"],["match point","point1"]],
"circular measure":[["noun.quantity"],["circular measure","system of measurement"]],
"mil":[["noun.quantity","noun.quantity","noun.quantity"],["mil3","angular unit","mil1","linear unit","inch","mil4","Cypriot pound","Cypriot monetary unit"]],
"microradian":[["noun.quantity"],["microradian","angular unit","milliradian"]],
"milliradian":[["noun.quantity"],["milliradian","angular unit","radian"]],
"radian":[["noun.quantity"],["radian","rad1","angular unit"]],
"grad":[["noun.quantity","noun.shape:right angle"],["grad","grade","angular unit"]],
"oxtant":[["noun.quantity"],["oxtant","angular unit"]],
"straight angle":[["noun.quantity","noun.attribute:circumference1"],["straight angle","angular unit"]],
"steradian":[["noun.quantity","noun.shape:sphere1"],["steradian","sr","angular unit"]],
"square inch":[["noun.quantity"],["square inch","sq in","area unit"]],
"square foot":[["noun.quantity"],["square foot","sq ft","area unit"]],
"square yard":[["noun.quantity"],["square yard","sq yd","area unit"]],
"square meter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["square meter","square metre","centare","area unit"]],
"square mile":[["noun.quantity"],["square mile","area unit"]],
"quarter section":[["noun.quantity"],["quarter section","area unit"]],
"are":[["noun.quantity"],["are","ar","area unit","hectare"]],
"hectare":[["noun.quantity"],["hectare","area unit"]],
"arpent":[["noun.quantity"],["arpent","area unit"]],
"dessiatine":[["noun.quantity"],["dessiatine","area unit"]],
"morgen":[["noun.quantity"],["morgen","area unit"]],
"liquid unit":[["noun.quantity"],["liquid unit","liquid measure","capacity unit"]],
"dry unit":[["noun.quantity"],["dry unit","dry measure","capacity unit"]],
"united states liquid unit":[["noun.quantity"],["United States liquid unit","liquid unit"]],
"british capacity unit":[["noun.quantity"],["British capacity unit","Imperial capacity unit","liquid unit","dry unit"]],
"metric capacity unit":[["noun.quantity"],["metric capacity unit","capacity unit","metric unit"]],
"ardeb":[["noun.quantity"],["ardeb","dry unit"]],
"arroba":[["noun.quantity","noun.quantity"],["arroba2","liquid unit","arroba1","weight unit"]],
"cran":[["noun.quantity"],["cran","capacity unit"]],
"ephah":[["noun.quantity"],["ephah","epha","dry unit","homer"]],
"field capacity":[["noun.quantity"],["field capacity","capacity unit"]],
"hin":[["noun.quantity"],["hin","capacity unit"]],
"acre-foot":[["noun.quantity"],["acre-foot","volume unit"]],
"acre inch":[["noun.quantity"],["acre inch","volume unit"]],
"board measure":[["noun.quantity"],["board measure","system of measurement"]],
"board foot":[["noun.quantity"],["board foot","volume unit"]],
"cubic yard":[["noun.quantity"],["cubic yard","yard1","volume unit"]],
"mutchkin":[["noun.quantity"],["mutchkin","liquid unit"]],
"oka":[["noun.quantity","noun.quantity"],["oka2","liquid unit","oka1","weight unit"]],
"minim":[["noun.quantity","noun.quantity"],["minim1","United States liquid unit","fluidram1","minim2","British capacity unit","fluidram2"]],
"fluidram":[["noun.quantity","noun.quantity"],["fluidram1","fluid dram1","fluid drachm1","drachm1","United States liquid unit","fluidounce1","fluidram2","fluid dram2","fluid drachm2","drachm2","British capacity unit","fluidounce2"]],
"fluidounce":[["noun.quantity","noun.quantity"],["fluidounce1","fluid ounce1","United States liquid unit","gill1","fluidounce2","fluid ounce2","British capacity unit","gill2"]],
"pint":[["noun.quantity","noun.quantity","noun.quantity"],["pint1","United States liquid unit","quart1","pint3","dry pint","United States dry unit","quart3","pint2","British capacity unit","quart2"]],
"quart":[["noun.quantity","noun.quantity","noun.quantity"],["quart1","United States liquid unit","gallon1","quart3","dry quart","United States dry unit","peck1","quart2","British capacity unit","gallon2"]],
"gallon":[["noun.quantity","noun.quantity"],["gallon1","gal","United States liquid unit","barrel1","gallon2","Imperial gallon","congius","British capacity unit","bushel1","barrel1","firkin"]],
"united states dry unit":[["noun.quantity"],["United States dry unit","dry unit"]],
"bushel":[["noun.quantity","noun.quantity"],["bushel2","United States dry unit","bushel1","British capacity unit","quarter4"]],
"kilderkin":[["noun.quantity"],["kilderkin","British capacity unit"]],
"chaldron":[["noun.quantity"],["chaldron","British capacity unit"]],
"cubic millimeter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["cubic millimeter","cubic millimetre","metric capacity unit","milliliter"]],
"milliliter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["milliliter","millilitre","mil2","ml","cubic centimeter","cubic centimetre","cc","metric capacity unit","centiliter"]],
"centiliter":[["noun.quantity"],["centiliter","centilitre","cl","metric capacity unit","deciliter"]],
"deciliter":[["noun.quantity"],["deciliter","decilitre","dl","metric capacity unit","liter"]],
"liter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["liter","litre","l","cubic decimeter","cubic decimetre","metric capacity unit","dekaliter"]],
"dekaliter":[["noun.quantity"],["dekaliter","dekalitre","decaliter","decalitre","dal","dkl","metric capacity unit","hectoliter"]],
"hectoliter":[["noun.quantity"],["hectoliter","hectolitre","hl","metric capacity unit","kiloliter"]],
"kiloliter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["kiloliter","kilolitre","cubic meter","cubic metre","metric capacity unit","cubic kilometer"]],
"cubic kilometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["cubic kilometer","cubic kilometre","metric capacity unit"]],
"parity bit":[["noun.quantity","noun.cognition:computer science"],["parity bit","parity","check bit","bit"]],
"nybble":[["noun.quantity","verb.consumption:nibble1","verb.contact:nibble"],["nybble","nibble","byte","computer memory unit"]],
"byte":[["noun.quantity"],["byte","computer memory unit","word"]],
"bad block":[["noun.quantity","noun.cognition:computer science"],["bad block","block"]],
"allocation unit":[["noun.quantity"],["allocation unit","computer memory unit"]],
"kilobyte":[["noun.quantity","noun.quantity"],["kilobyte","kibibyte","K","KB","kB1","KiB","mebibyte","computer memory unit","kilobyte1","K1","KB2","kB3","megabyte1","computer memory unit"]],
"kilobit":[["noun.quantity"],["kilobit","kbit","kb4","megabit","computer memory unit"]],
"kibibit":[["noun.quantity"],["kibibit","kibit","mebibit","computer memory unit"]],
"megabyte":[["noun.quantity","noun.quantity"],["megabyte","mebibyte","M2","MB","MiB","gibibyte","computer memory unit","megabyte1","M3","MB1","gigabyte1","computer memory unit"]],
"megabit":[["noun.quantity"],["megabit","Mbit","Mb2","gigabit","computer memory unit"]],
"mebibit":[["noun.quantity"],["mebibit","Mibit","gibibit","computer memory unit"]],
"gigabyte":[["noun.quantity","noun.quantity"],["gigabyte","gibibyte","G2","GB2","GiB","tebibyte","computer memory unit","gigabyte1","G3","GB3","terabyte1","computer memory unit"]],
"gigabit":[["noun.quantity"],["gigabit","Gbit","Gb4","terabit","computer memory unit"]],
"gibibit":[["noun.quantity"],["gibibit","Gibit","tebibit","computer memory unit"]],
"terabyte":[["noun.quantity","noun.quantity"],["terabyte","tebibyte","TB","TiB","pebibyte","computer memory unit","terabyte1","TB1","petabyte1","computer memory unit"]],
"terabit":[["noun.quantity"],["terabit","Tbit","Tb2","petabit","computer memory unit"]],
"tebibit":[["noun.quantity"],["tebibit","Tibit","pebibit","computer memory unit"]],
"petabyte":[["noun.quantity","noun.quantity"],["petabyte","pebibyte","PB","PiB","exbibyte","computer memory unit","petabyte1","PB1","exabyte1","computer memory unit"]],
"petabit":[["noun.quantity"],["petabit","Pbit","Pb2","exabit","computer memory unit"]],
"pebibit":[["noun.quantity"],["pebibit","Pibit","exbibit","computer memory unit"]],
"exabyte":[["noun.quantity","noun.quantity"],["exabyte","exbibyte","EB","EiB","zebibyte","computer memory unit","exabyte1","EB1","zettabyte1","computer memory unit"]],
"exabit":[["noun.quantity"],["exabit","Ebit","Eb2","zettabit","computer memory unit"]],
"exbibit":[["noun.quantity"],["exbibit","Eibit","zebibit","computer memory unit"]],
"zettabyte":[["noun.quantity","noun.quantity"],["zettabyte","zebibyte","ZB","ZiB","yobibyte","computer memory unit","zettabyte1","ZB1","yottabyte1","computer memory unit"]],
"zettabit":[["noun.quantity"],["zettabit","Zbit","Zb2","yottabit","computer memory unit"]],
"zebibit":[["noun.quantity"],["zebibit","Zibit","yobibit","computer memory unit"]],
"yottabyte":[["noun.quantity","noun.quantity"],["yottabyte","yobibyte","YB","YiB","computer memory unit","yottabyte1","YB1","computer memory unit"]],
"yottabit":[["noun.quantity"],["yottabit","Ybit","Yb2","computer memory unit"]],
"yobibit":[["noun.quantity"],["yobibit","Yibit","computer memory unit"]],
"capacitance unit":[["noun.quantity"],["capacitance unit","electromagnetic unit"]],
"charge unit":[["noun.quantity"],["charge unit","quantity unit","electromagnetic unit"]],
"conductance unit":[["noun.quantity"],["conductance unit","electromagnetic unit"]],
"current unit":[["noun.quantity"],["current unit","electromagnetic unit"]],
"elastance unit":[["noun.quantity"],["elastance unit","electromagnetic unit"]],
"field strength unit":[["noun.quantity"],["field strength unit","electromagnetic unit"]],
"flux density unit":[["noun.quantity"],["flux density unit","electromagnetic unit"]],
"flux unit":[["noun.quantity"],["flux unit","magnetic flux unit","magnetic flux"]],
"inductance unit":[["noun.quantity"],["inductance unit","electromagnetic unit"]],
"light unit":[["noun.quantity"],["light unit","electromagnetic unit"]],
"magnetomotive force unit":[["noun.quantity"],["magnetomotive force unit","electromagnetic unit"]],
"potential unit":[["noun.quantity"],["potential unit","electromagnetic unit"]],
"power unit":[["noun.quantity"],["power unit","electromagnetic unit"]],
"radioactivity unit":[["noun.quantity"],["radioactivity unit","electromagnetic unit"]],
"resistance unit":[["noun.quantity"],["resistance unit","electromagnetic unit"]],
"electrostatic unit":[["noun.quantity"],["electrostatic unit","unit of measurement"]],
"picofarad":[["noun.quantity"],["picofarad","capacitance unit","microfarad"]],
"microfarad":[["noun.quantity"],["microfarad","capacitance unit","millifarad"]],
"millifarad":[["noun.quantity"],["millifarad","capacitance unit","farad"]],
"farad":[["noun.quantity"],["farad","F","capacitance unit","abfarad"]],
"abfarad":[["noun.quantity"],["abfarad","capacitance unit"]],
"abcoulomb":[["noun.quantity"],["abcoulomb","charge unit"]],
"ampere-minute":[["noun.quantity"],["ampere-minute","charge unit","ampere-hour"]],
"ampere-hour":[["noun.quantity"],["ampere-hour","charge unit"]],
"mho":[["noun.quantity"],["mho","siemens","reciprocal ohm","S","conductance unit"]],
"ampere":[["noun.quantity","noun.quantity"],["ampere","amp","A","current unit","abampere","ampere2","international ampere","current unit"]],
"milliampere":[["noun.quantity"],["milliampere","mA","current unit","ampere"]],
"abampere":[["noun.quantity"],["abampere","abamp","current unit"]],
"daraf":[["noun.quantity"],["daraf","elastance unit"]],
"microgauss":[["noun.quantity"],["microgauss","flux density unit","gauss"]],
"abhenry":[["noun.quantity"],["abhenry","inductance unit","henry"]],
"millihenry":[["noun.quantity"],["millihenry","inductance unit","henry"]],
"illumination unit":[["noun.quantity"],["illumination unit","light unit"]],
"luminance unit":[["noun.quantity"],["luminance unit","light unit"]],
"luminous flux unit":[["noun.quantity"],["luminous flux unit","light unit"]],
"luminous intensity unit":[["noun.quantity"],["luminous intensity unit","candlepower unit","light unit"]],
"footcandle":[["noun.quantity"],["footcandle","illumination unit"]],
"lux":[["noun.quantity"],["lux","lx1","illumination unit","phot"]],
"phot":[["noun.quantity"],["phot","illumination unit"]],
"foot-lambert":[["noun.quantity"],["foot-lambert","ft-L","luminance unit"]],
"international candle":[["noun.quantity"],["international candle","luminous intensity unit"]],
"ampere-turn":[["noun.quantity"],["ampere-turn","magnetomotive force unit"]],
"magneton":[["noun.quantity"],["magneton","magnetomotive force unit"]],
"abvolt":[["noun.quantity"],["abvolt","potential unit","volt"]],
"millivolt":[["noun.quantity"],["millivolt","mV","potential unit","volt"]],
"microvolt":[["noun.quantity"],["microvolt","potential unit","volt"]],
"nanovolt":[["noun.quantity"],["nanovolt","potential unit","volt"]],
"picovolt":[["noun.quantity"],["picovolt","potential unit","volt"]],
"femtovolt":[["noun.quantity"],["femtovolt","potential unit","volt"]],
"volt":[["noun.quantity","adj.pert:voltaic"],["volt","V","potential unit","kilovolt"]],
"kilovolt":[["noun.quantity"],["kilovolt","kV","potential unit"]],
"rydberg":[["noun.quantity"],["rydberg","rydberg constant","rydberg unit","wave number"]],
"wave number":[["noun.quantity","noun.time:frequency"],["wave number"]],
"abwatt":[["noun.quantity"],["abwatt","power unit","milliwatt"]],
"milliwatt":[["noun.quantity"],["milliwatt","power unit","watt"]],
"kilowatt":[["noun.quantity"],["kilowatt","kW","power unit","megawatt"]],
"megawatt":[["noun.quantity"],["megawatt","power unit"]],
"horsepower":[["noun.quantity","H.P."],["horsepower","HP","power unit"]],
"volt-ampere":[["noun.quantity"],["volt-ampere","var","power unit","kilovolt-ampere"]],
"kilovolt-ampere":[["noun.quantity"],["kilovolt-ampere","power unit"]],
"millicurie":[["noun.quantity"],["millicurie","radioactivity unit","curie"]],
"rem":[["noun.quantity"],["rem","radioactivity unit"]],
"mrem":[["noun.quantity"],["mrem","millirem","radioactivity unit"]],
"rad":[["noun.quantity"],["rad","radioactivity unit"]],
"abohm":[["noun.quantity"],["abohm","resistance unit","ohm"]],
"megohm":[["noun.quantity"],["megohm","resistance unit"]],
"kiloton":[["noun.quantity"],["kiloton","avoirdupois unit","megaton"]],
"megaton":[["noun.quantity"],["megaton","avoirdupois unit"]],
"dyne":[["noun.quantity"],["dyne","force unit","newton"]],
"sthene":[["noun.quantity"],["sthene","force unit"]],
"poundal":[["noun.quantity"],["poundal","pdl","force unit"]],
"pounder":[["noun.quantity","noun.communication:combining form"],["pounder","force unit"]],
"astronomy unit":[["noun.quantity"],["astronomy unit","linear unit"]],
"metric linear unit":[["noun.quantity"],["metric linear unit","linear unit","metric unit"]],
"nautical linear unit":[["noun.quantity"],["nautical linear unit","linear unit"]],
"inch":[["noun.quantity","verb.motion:inch","noun.location:US","noun.location:Britain"],["inch","in","linear unit","foot"]],
"footer":[["noun.quantity","noun.communication:combining form"],["footer","linear unit"]],
"furlong":[["noun.quantity"],["furlong","linear unit","mile1"]],
"half mile":[["noun.quantity"],["half mile","880 yards","linear unit","mile1"]],
"quarter mile":[["noun.quantity"],["quarter mile","440 yards","linear unit","mile1"]],
"ligne":[["noun.quantity"],["ligne","linear unit","inch"]],
"archine":[["noun.quantity"],["archine","linear unit"]],
"kos":[["noun.quantity"],["kos","coss","linear unit"]],
"vara":[["noun.quantity"],["vara","linear unit"]],
"verst":[["noun.quantity"],["verst","linear unit"]],
"gunter's chain":[["noun.quantity"],["Gunter's chain","chain","furlong"]],
"engineer's chain":[["noun.quantity"],["engineer's chain","chain"]],
"cubit":[["noun.quantity"],["cubit","linear unit"]],
"fistmele":[["noun.quantity"],["fistmele","linear unit"]],
"body length":[["noun.quantity"],["body length","linear unit"]],
"extremum":[["noun.quantity","adj.all:high3^peaky","verb.motion:peak"],["extremum","peak","limit"]],
"handbreadth":[["noun.quantity"],["handbreadth","handsbreadth","linear unit"]],
"lea":[["noun.quantity"],["lea","linear unit"]],
"li":[["noun.quantity"],["li","linear unit"]],
"roman pace":[["noun.quantity"],["Roman pace","linear unit"]],
"geometric pace":[["noun.quantity"],["geometric pace","linear unit"]],
"military pace":[["noun.quantity"],["military pace","linear unit"]],
"survey mile":[["noun.quantity"],["survey mile","linear unit"]],
"light year":[["noun.quantity"],["light year","light-year","astronomy unit"]],
"light hour":[["noun.quantity"],["light hour","astronomy unit","light year"]],
"light minute":[["noun.quantity"],["light minute","astronomy unit","light year"]],
"light second":[["noun.quantity"],["light second","astronomy unit","light year"]],
"astronomical unit":[["noun.quantity"],["Astronomical Unit","AU","astronomy unit"]],
"parsec":[["noun.quantity"],["parsec","secpar","astronomy unit"]],
"femtometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["femtometer","femtometre","fermi","metric linear unit","picometer"]],
"picometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["picometer","picometre","micromicron","metric linear unit","angstrom"]],
"angstrom":[["noun.quantity"],["angstrom","angstrom unit","A1","metric linear unit","nanometer"]],
"nanometer":[["noun.quantity","noun.location:Canada","noun.location:Britain","noun.location:Canada","noun.location:Britain"],["nanometer","nanometre","nm","millimicron","micromillimeter","micromillimetre","metric linear unit","micron"]],
"micron":[["noun.quantity"],["micron","micrometer","metric linear unit","millimeter"]],
"millimeter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["millimeter","millimetre","mm","metric linear unit","centimeter"]],
"centimeter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["centimeter","centimetre","cm","metric linear unit","decimeter"]],
"decimeter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["decimeter","decimetre","dm","metric linear unit","meter"]],
"decameter":[["noun.quantity","noun.location:Canada","noun.location:Britain","noun.location:Canada","noun.location:Britain"],["decameter","dekameter","decametre","dekametre","dam","dkm","metric linear unit","hectometer"]],
"hectometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["hectometer","hectometre","hm","metric linear unit","kilometer"]],
"kilometer":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["kilometer","kilometre","km","klick","metric linear unit","myriameter"]],
"myriameter":[["noun.quantity","noun.location:Canada","noun.location:Britain"],["myriameter","myriametre","mym","metric linear unit"]],
"nautical chain":[["noun.quantity"],["nautical chain","chain"]],
"nautical mile":[["noun.quantity","noun.quantity:miler","noun.quantity","noun.quantity:miler"],["nautical mile1","mile4","mi4","naut mi","international nautical mile","air mile","nautical linear unit","nautical mile2","naut mi1","mile6","mi5","geographical mile","Admiralty mile","nautical linear unit"]],
"sea mile":[["noun.quantity","noun.quantity:miler"],["sea mile","mile5","nautical linear unit"]],
"halfpennyworth":[["noun.quantity"],["halfpennyworth","ha'p'orth","worth"]],
"pennyworth":[["noun.quantity"],["pennyworth","penn'orth","worth"]],
"euro":[["noun.quantity"],["euro","monetary unit"]],
"franc":[["noun.quantity"],["franc","monetary unit"]],
"fractional monetary unit":[["noun.quantity"],["fractional monetary unit","subunit","monetary unit"]],
"afghan monetary unit":[["noun.quantity"],["Afghan monetary unit","monetary unit"]],
"afghani":[["noun.quantity"],["afghani","Afghan monetary unit"]],
"pul":[["noun.quantity"],["pul","afghani","Afghan monetary unit"]],
"argentine monetary unit":[["noun.quantity"],["Argentine monetary unit","monetary unit"]],
"austral":[["noun.quantity"],["austral","Argentine monetary unit"]],
"thai monetary unit":[["noun.quantity"],["Thai monetary unit","monetary unit"]],
"baht":[["noun.quantity"],["baht","tical","Thai monetary unit"]],
"satang":[["noun.quantity"],["satang","baht","Thai monetary unit"]],
"panamanian monetary unit":[["noun.quantity"],["Panamanian monetary unit","monetary unit"]],
"ethiopian monetary unit":[["noun.quantity"],["Ethiopian monetary unit","monetary unit"]],
"birr":[["noun.quantity"],["birr","Ethiopian monetary unit"]],
"cent":[["noun.quantity"],["cent","fractional monetary unit","birr","dollar","gulden1","leone","lilangeni","rand","Mauritian rupee","Seychelles rupee","Sri Lanka rupee","shilling1"]],
"centesimo":[["noun.quantity"],["centesimo","fractional monetary unit","balboa","Italian lira","Uruguayan peso","Chilean peso"]],
"centimo":[["noun.quantity"],["centimo","fractional monetary unit","bolivar","Costa Rican colon","guarani","peseta"]],
"centavo":[["noun.quantity"],["centavo","fractional monetary unit","austral","El Salvadoran colon","dobra","escudo1","escudo2","cordoba","lempira","metical","boliviano","peso3","peso4","peso5","peso6","peso7","peso8","peso10","quetzal","real1","sucre"]],
"centime":[["noun.quantity"],["centime","fractional monetary unit","franc","Algerian dinar","Belgian franc","Burkina Faso franc","Burundi franc","Cameroon franc","Chadian franc","Congo franc","Gabon franc","Ivory Coast franc","Luxembourg franc","Mali franc","Moroccan dirham","Niger franc","Rwanda franc","Senegalese franc","Swiss franc","Togo franc"]],
"venezuelan monetary unit":[["noun.quantity"],["Venezuelan monetary unit","monetary unit"]],
"ghanian monetary unit":[["noun.quantity"],["Ghanian monetary unit","monetary unit"]],
"cedi":[["noun.quantity"],["cedi","Ghanian monetary unit"]],
"pesewa":[["noun.quantity"],["pesewa","cedi","Ghanian monetary unit"]],
"costa rican monetary unit":[["noun.quantity"],["Costa Rican monetary unit","monetary unit"]],
"el salvadoran monetary unit":[["noun.quantity"],["El Salvadoran monetary unit","monetary unit"]],
"brazilian monetary unit":[["noun.quantity"],["Brazilian monetary unit","monetary unit"]],
"gambian monetary unit":[["noun.quantity"],["Gambian monetary unit","monetary unit"]],
"dalasi":[["noun.quantity"],["dalasi","Gambian monetary unit"]],
"butut":[["noun.quantity"],["butut","butat","dalasi","Gambian monetary unit"]],
"algerian monetary unit":[["noun.quantity"],["Algerian monetary unit","monetary unit"]],
"algerian dinar":[["noun.quantity"],["Algerian dinar","dinar","Algerian monetary unit"]],
"algerian centime":[["noun.quantity"],["Algerian centime","centime","Algerian dinar"]],
"bahrainian monetary unit":[["noun.quantity"],["Bahrainian monetary unit","monetary unit"]],
"bahrain dinar":[["noun.quantity"],["Bahrain dinar","dinar1","Bahrainian monetary unit"]],
"fils":[["noun.quantity"],["fils","fractional monetary unit","Bahrain dinar","Iraqi dinar","Jordanian dinar","Kuwaiti dirham"]],
"iraqi monetary unit":[["noun.quantity"],["Iraqi monetary unit","monetary unit"]],
"iraqi dinar":[["noun.quantity"],["Iraqi dinar","dinar2","Iraqi monetary unit"]],
"jordanian monetary unit":[["noun.quantity"],["Jordanian monetary unit","monetary unit"]],
"jordanian dinar":[["noun.quantity"],["Jordanian dinar","dinar3","Jordanian monetary unit"]],
"kuwaiti monetary unit":[["noun.quantity"],["Kuwaiti monetary unit","monetary unit"]],
"kuwaiti dinar":[["noun.quantity"],["Kuwaiti dinar","dinar4","Kuwaiti monetary unit"]],
"kuwaiti dirham":[["noun.quantity"],["Kuwaiti dirham","dirham1","Kuwaiti monetary unit","Kuwaiti dinar"]],
"libyan monetary unit":[["noun.quantity"],["Libyan monetary unit","monetary unit"]],
"libyan dinar":[["noun.quantity"],["Libyan dinar","dinar5","Libyan monetary unit"]],
"libyan dirham":[["noun.quantity"],["Libyan dirham","dirham2","Libyan monetary unit","Libyan dinar"]],
"tunisian monetary unit":[["noun.quantity"],["Tunisian monetary unit","monetary unit"]],
"tunisian dinar":[["noun.quantity"],["Tunisian dinar","dinar7","Tunisian monetary unit"]],
"tunisian dirham":[["noun.quantity"],["Tunisian dirham","dirham3","Tunisian monetary unit","Tunisian dinar"]],
"millime":[["noun.quantity"],["millime","Tunisian monetary unit","Tunisian dirham"]],
"yugoslavian monetary unit":[["noun.quantity"],["Yugoslavian monetary unit","monetary unit"]],
"yugoslavian dinar":[["noun.quantity"],["Yugoslavian dinar","dinar8","Yugoslavian monetary unit"]],
"moroccan monetary unit":[["noun.quantity"],["Moroccan monetary unit","monetary unit"]],
"moroccan dirham":[["noun.quantity"],["Moroccan dirham","dirham4","Moroccan monetary unit"]],
"united arab emirate monetary unit":[["noun.quantity"],["United Arab Emirate monetary unit","monetary unit"]],
"united arab emirate dirham":[["noun.quantity"],["United Arab Emirate dirham","dirham5","United Arab Emirate monetary unit"]],
"australian dollar":[["noun.quantity"],["Australian dollar","dollar"]],
"bahamian dollar":[["noun.quantity"],["Bahamian dollar","dollar"]],
"barbados dollar":[["noun.quantity"],["Barbados dollar","dollar"]],
"belize dollar":[["noun.quantity"],["Belize dollar","dollar"]],
"bermuda dollar":[["noun.quantity"],["Bermuda dollar","dollar"]],
"brunei dollar":[["noun.quantity"],["Brunei dollar","dollar"]],
"sen":[["noun.quantity"],["sen","fractional monetary unit","rupiah","riel","ringgit","yen"]],
"canadian dollar":[["noun.quantity"],["Canadian dollar","loonie","dollar"]],
"cayman islands dollar":[["noun.quantity"],["Cayman Islands dollar","dollar"]],
"dominican dollar":[["noun.quantity"],["Dominican dollar","dollar"]],
"fiji dollar":[["noun.quantity"],["Fiji dollar","dollar"]],
"grenada dollar":[["noun.quantity"],["Grenada dollar","dollar"]],
"guyana dollar":[["noun.quantity"],["Guyana dollar","dollar"]],
"hong kong dollar":[["noun.quantity"],["Hong Kong dollar","dollar"]],
"jamaican dollar":[["noun.quantity"],["Jamaican dollar","dollar"]],
"kiribati dollar":[["noun.quantity"],["Kiribati dollar","dollar"]],
"liberian dollar":[["noun.quantity"],["Liberian dollar","dollar"]],
"new zealand dollar":[["noun.quantity"],["New Zealand dollar","dollar"]],
"singapore dollar":[["noun.quantity"],["Singapore dollar","dollar"]],
"taiwan dollar":[["noun.quantity"],["Taiwan dollar","dollar"]],
"trinidad and tobago dollar":[["noun.quantity"],["Trinidad and Tobago dollar","dollar"]],
"tuvalu dollar":[["noun.quantity"],["Tuvalu dollar","dollar"]],
"united states dollar":[["noun.quantity"],["United States dollar","dollar"]],
"eurodollar":[["noun.quantity","noun.possession:Eurocurrency"],["Eurodollar","United States dollar"]],
"zimbabwean dollar":[["noun.quantity"],["Zimbabwean dollar","dollar"]],
"vietnamese monetary unit":[["noun.quantity"],["Vietnamese monetary unit","monetary unit"]],
"dong":[["noun.quantity"],["dong","Vietnamese monetary unit"]],
"hao":[["noun.quantity"],["hao","dong","Vietnamese monetary unit"]],
"greek monetary unit":[["noun.quantity"],["Greek monetary unit","monetary unit"]],
"drachma":[["noun.quantity"],["drachma","Greek drachma","Greek monetary unit"]],
"sao thome e principe monetary unit":[["noun.quantity"],["Sao Thome e Principe monetary unit","monetary unit"]],
"dobra":[["noun.quantity"],["dobra","Sao Thome e Principe monetary unit"]],
"cape verde monetary unit":[["noun.quantity"],["Cape Verde monetary unit","monetary unit"]],
"cape verde escudo":[["noun.quantity"],["Cape Verde escudo","escudo1","Cape Verde monetary unit"]],
"portuguese monetary unit":[["noun.quantity"],["Portuguese monetary unit","monetary unit"]],
"portuguese escudo":[["noun.quantity"],["Portuguese escudo","escudo2","Portuguese monetary unit","conto"]],
"conto":[["noun.quantity"],["conto","Portuguese monetary unit"]],
"hungarian monetary unit":[["noun.quantity"],["Hungarian monetary unit","monetary unit"]],
"forint":[["noun.quantity"],["forint","Hungarian monetary unit"]],
"belgian franc":[["noun.quantity"],["Belgian franc","franc"]],
"benin franc":[["noun.quantity"],["Benin franc","franc"]],
"burundi franc":[["noun.quantity"],["Burundi franc","franc"]],
"cameroon franc":[["noun.quantity"],["Cameroon franc","franc"]],
"central african republic franc":[["noun.quantity"],["Central African Republic franc","franc"]],
"chadian franc":[["noun.quantity"],["Chadian franc","franc"]],
"congo franc":[["noun.quantity"],["Congo franc","franc"]],
"djibouti franc":[["noun.quantity"],["Djibouti franc","franc"]],
"french franc":[["noun.quantity"],["French franc","franc"]],
"gabon franc":[["noun.quantity"],["Gabon franc","franc"]],
"ivory coast franc":[["noun.quantity"],["Ivory Coast franc","Cote d'Ivoire franc","franc"]],
"luxembourg franc":[["noun.quantity"],["Luxembourg franc","franc"]],
"madagascar franc":[["noun.quantity"],["Madagascar franc","franc"]],
"mali franc":[["noun.quantity"],["Mali franc","franc"]],
"niger franc":[["noun.quantity"],["Niger franc","franc"]],
"rwanda franc":[["noun.quantity"],["Rwanda franc","franc"]],
"senegalese franc":[["noun.quantity"],["Senegalese franc","franc"]],
"swiss franc":[["noun.quantity"],["Swiss franc","franc"]],
"togo franc":[["noun.quantity"],["Togo franc","franc"]],
"burkina faso franc":[["noun.quantity"],["Burkina Faso franc","franc"]],
"haitian monetary unit":[["noun.quantity"],["Haitian monetary unit","monetary unit"]],
"gourde":[["noun.quantity"],["gourde","Haitian monetary unit"]],
"haitian centime":[["noun.quantity"],["Haitian centime","centime","gourde"]],
"paraguayan monetary unit":[["noun.quantity"],["Paraguayan monetary unit","monetary unit"]],
"dutch monetary unit":[["noun.quantity"],["Dutch monetary unit","monetary unit"]],
"guilder":[["noun.quantity","noun.quantity"],["guilder1","gulden1","florin1","Dutch florin","Dutch monetary unit","guilder2","gulden2","florin2","Surinamese monetary unit"]],
"surinamese monetary unit":[["noun.quantity"],["Surinamese monetary unit","monetary unit"]],
"peruvian monetary unit":[["noun.quantity"],["Peruvian monetary unit","monetary unit"]],
"inti":[["noun.quantity"],["inti","Peruvian monetary unit"]],
"papuan monetary unit":[["noun.quantity"],["Papuan monetary unit","monetary unit"]],
"kina":[["noun.quantity"],["kina","Papuan monetary unit"]],
"toea":[["noun.quantity"],["toea","kina","Papuan monetary unit"]],
"laotian monetary unit":[["noun.quantity"],["Laotian monetary unit","monetary unit"]],
"at":[["noun.quantity"],["at","kip","Laotian monetary unit"]],
"czech monetary unit":[["noun.quantity"],["Czech monetary unit","monetary unit"]],
"koruna":[["noun.quantity","noun.quantity"],["koruna","Czech monetary unit","koruna1","Slovakian monetary unit"]],
"haler":[["noun.quantity","noun.quantity"],["haler","heller","koruna","Czech monetary unit","haler1","heller1","Slovakian monetary unit","koruna"]],
"slovakian monetary unit":[["noun.quantity"],["Slovakian monetary unit","monetary unit"]],
"icelandic monetary unit":[["noun.quantity"],["Icelandic monetary unit","monetary unit"]],
"icelandic krona":[["noun.quantity"],["Icelandic krona","krona1","Icelandic monetary unit"]],
"eyrir":[["noun.quantity"],["eyrir","Icelandic krona","Icelandic monetary unit"]],
"swedish monetary unit":[["noun.quantity"],["Swedish monetary unit","monetary unit"]],
"swedish krona":[["noun.quantity"],["Swedish krona","krona2","Swedish monetary unit"]],
"danish monetary unit":[["noun.quantity"],["Danish monetary unit","monetary unit"]],
"danish krone":[["noun.quantity"],["Danish krone","krone1","Danish monetary unit"]],
"norwegian monetary unit":[["noun.quantity"],["Norwegian monetary unit","monetary unit"]],
"norwegian krone":[["noun.quantity"],["Norwegian krone","krone2","Norwegian monetary unit"]],
"malawian monetary unit":[["noun.quantity"],["Malawian monetary unit","monetary unit"]],
"malawi kwacha":[["noun.quantity"],["Malawi kwacha","kwacha1","Malawian monetary unit"]],
"tambala":[["noun.quantity"],["tambala","Malawi kwacha","Malawian monetary unit"]],
"zambian monetary unit":[["noun.quantity"],["Zambian monetary unit","monetary unit"]],
"zambian kwacha":[["noun.quantity"],["Zambian kwacha","kwacha2","Zambian monetary unit"]],
"ngwee":[["noun.quantity"],["ngwee","Zambian kwacha","Zambian monetary unit"]],
"angolan monetary unit":[["noun.quantity"],["Angolan monetary unit","monetary unit"]],
"kwanza":[["noun.quantity"],["kwanza","Angolan monetary unit"]],
"lwei":[["noun.quantity"],["lwei","kwanza","Angolan monetary unit"]],
"myanmar monetary unit":[["noun.quantity","noun.location:Burma"],["Myanmar monetary unit","monetary unit"]],
"kyat":[["noun.quantity"],["kyat","Myanmar monetary unit"]],
"pya":[["noun.quantity"],["pya","kyat","Myanmar monetary unit"]],
"albanian monetary unit":[["noun.quantity"],["Albanian monetary unit","monetary unit"]],
"lek":[["noun.quantity"],["lek","Albanian monetary unit"]],
"qindarka":[["noun.quantity"],["qindarka","qintar","lek","Albanian monetary unit"]],
"honduran monetary unit":[["noun.quantity"],["Honduran monetary unit","monetary unit"]],
"lempira":[["noun.quantity"],["lempira","Honduran monetary unit"]],
"sierra leone monetary unit":[["noun.quantity"],["Sierra Leone monetary unit","monetary unit"]],
"leone":[["noun.quantity"],["leone","Sierra Leone monetary unit"]],
"romanian monetary unit":[["noun.quantity"],["Romanian monetary unit","monetary unit"]],
"leu":[["noun.quantity","noun.quantity"],["leu","Romanian monetary unit","leu1","Moldovan monetary unit"]],
"bulgarian monetary unit":[["noun.quantity"],["Bulgarian monetary unit","monetary unit"]],
"lev":[["noun.quantity"],["lev","Bulgarian monetary unit"]],
"stotinka":[["noun.quantity"],["stotinka","lev","Bulgarian monetary unit"]],
"swaziland monetary unit":[["noun.quantity"],["Swaziland monetary unit","monetary unit"]],
"lilangeni":[["noun.quantity"],["lilangeni","Swaziland monetary unit"]],
"italian monetary unit":[["noun.quantity"],["Italian monetary unit","monetary unit"]],
"lira":[["noun.quantity","noun.quantity","noun.quantity"],["lira1","Italian lira","Italian monetary unit","lira2","Turkish lira","Turkish monetary unit","lira3","Maltese lira","Maltese monetary unit"]],
"british monetary unit":[["noun.quantity"],["British monetary unit","monetary unit"]],
"british pound":[["noun.quantity"],["British pound","pound1","British pound sterling","pound sterling","quid","British monetary unit"]],
"british shilling":[["noun.quantity"],["British shilling","shilling1","bob","British monetary unit"]],
"turkish monetary unit":[["noun.quantity"],["Turkish monetary unit","monetary unit"]],
"kurus":[["noun.quantity"],["kurus","piaster1","piastre1","lira2","Turkish monetary unit"]],
"asper":[["noun.quantity"],["asper","kurus","Turkish monetary unit"]],
"lesotho monetary unit":[["noun.quantity"],["Lesotho monetary unit","monetary unit"]],
"loti":[["noun.quantity"],["loti","Lesotho monetary unit"]],
"sente":[["noun.quantity"],["sente","loti","Lesotho monetary unit"]],
"german monetary unit":[["noun.quantity"],["German monetary unit","monetary unit"]],
"pfennig":[["noun.quantity"],["pfennig","German monetary unit","mark"]],
"finnish monetary unit":[["noun.quantity"],["Finnish monetary unit","monetary unit"]],
"markka":[["noun.quantity"],["markka","Finnish mark","Finnish monetary unit"]],
"penni":[["noun.quantity"],["penni","markka","Finnish monetary unit"]],
"mozambique monetary unit":[["noun.quantity"],["Mozambique monetary unit","monetary unit"]],
"metical":[["noun.quantity"],["metical","Mozambique monetary unit"]],
"nigerian monetary unit":[["noun.quantity"],["Nigerian monetary unit","monetary unit"]],
"naira":[["noun.quantity"],["naira","Nigerian monetary unit"]],
"kobo":[["noun.quantity"],["kobo","naira","Nigerian monetary unit"]],
"bhutanese monetary unit":[["noun.quantity"],["Bhutanese monetary unit","monetary unit"]],
"ngultrum":[["noun.quantity"],["ngultrum","Bhutanese monetary unit"]],
"chetrum":[["noun.quantity"],["chetrum","ngultrum","Bhutanese monetary unit"]],
"mauritanian monetary unit":[["noun.quantity"],["Mauritanian monetary unit","monetary unit"]],
"ouguiya":[["noun.quantity"],["ouguiya","Mauritanian monetary unit"]],
"khoum":[["noun.quantity"],["khoum","ouguiya","Mauritanian monetary unit"]],
"tongan monetary unit":[["noun.quantity"],["Tongan monetary unit","monetary unit"]],
"pa'anga":[["noun.quantity"],["pa'anga","Tongan monetary unit"]],
"seniti":[["noun.quantity"],["seniti","pa'anga","Tongan monetary unit"]],
"macao monetary unit":[["noun.quantity"],["Macao monetary unit","monetary unit"]],
"pataca":[["noun.quantity"],["pataca","Macao monetary unit"]],
"avo":[["noun.quantity"],["avo","pataca","Macao monetary unit"]],
"spanish monetary unit":[["noun.quantity"],["Spanish monetary unit","monetary unit"]],
"peseta":[["noun.quantity"],["peseta","Spanish peseta","Spanish monetary unit"]],
"bolivian monetary unit":[["noun.quantity"],["Bolivian monetary unit","monetary unit"]],
"boliviano":[["noun.quantity"],["boliviano","Bolivian monetary unit"]],
"nicaraguan monetary unit":[["noun.quantity"],["Nicaraguan monetary unit","monetary unit"]],
"chilean monetary unit":[["noun.quantity"],["Chilean monetary unit","monetary unit"]],
"chilean peso":[["noun.quantity"],["Chilean peso","peso9","Chilean monetary unit"]],
"colombian monetary unit":[["noun.quantity"],["Colombian monetary unit","monetary unit"]],
"colombian peso":[["noun.quantity"],["Colombian peso","peso3","Colombian monetary unit"]],
"cuban monetary unit":[["noun.quantity"],["Cuban monetary unit","monetary unit"]],
"cuban peso":[["noun.quantity"],["Cuban peso","peso4","Cuban monetary unit"]],
"dominican monetary unit":[["noun.quantity"],["Dominican monetary unit","monetary unit"]],
"dominican peso":[["noun.quantity"],["Dominican peso","peso5","Dominican monetary unit"]],
"guinea-bissau monetary unit":[["noun.quantity"],["Guinea-Bissau monetary unit","monetary unit"]],
"guinea-bissau peso":[["noun.quantity"],["Guinea-Bissau peso","peso10","Guinea-Bissau monetary unit"]],
"mexican monetary unit":[["noun.quantity"],["Mexican monetary unit","monetary unit"]],
"mexican peso":[["noun.quantity"],["Mexican peso","peso6","Mexican monetary unit"]],
"philippine monetary unit":[["noun.quantity"],["Philippine monetary unit","monetary unit"]],
"philippine peso":[["noun.quantity"],["Philippine peso","peso7","Philippine monetary unit"]],
"uruguayan monetary unit":[["noun.quantity"],["Uruguayan monetary unit","monetary unit"]],
"uruguayan peso":[["noun.quantity"],["Uruguayan peso","peso8","Uruguayan monetary unit"]],
"cypriot monetary unit":[["noun.quantity"],["Cypriot monetary unit","monetary unit"]],
"cypriot pound":[["noun.quantity"],["Cypriot pound","pound2","Cypriot monetary unit"]],
"egyptian monetary unit":[["noun.quantity"],["Egyptian monetary unit","monetary unit"]],
"egyptian pound":[["noun.quantity"],["Egyptian pound","pound3","Egyptian monetary unit"]],
"piaster":[["noun.quantity"],["piaster","piastre","fractional monetary unit","Egyptian pound","Lebanese pound","Sudanese pound","Syrian pound"]],
"irish monetary unit":[["noun.quantity"],["Irish monetary unit","monetary unit"]],
"irish pound":[["noun.quantity"],["Irish pound","Irish punt","punt","pound4","Irish monetary unit"]],
"lebanese monetary unit":[["noun.quantity"],["Lebanese monetary unit","monetary unit"]],
"lebanese pound":[["noun.quantity"],["Lebanese pound","pound5","Lebanese monetary unit"]],
"maltese monetary unit":[["noun.quantity"],["Maltese monetary unit","monetary unit"]],
"sudanese monetary unit":[["noun.quantity"],["Sudanese monetary unit","monetary unit"]],
"sudanese pound":[["noun.quantity"],["Sudanese pound","pound7","Sudanese monetary unit"]],
"syrian monetary unit":[["noun.quantity"],["Syrian monetary unit","monetary unit"]],
"syrian pound":[["noun.quantity"],["Syrian pound","pound8","Syrian monetary unit"]],
"botswana monetary unit":[["noun.quantity"],["Botswana monetary unit","monetary unit"]],
"pula":[["noun.quantity"],["pula","Botswana monetary unit"]],
"thebe":[["noun.quantity"],["thebe","pula","Botswana monetary unit"]],
"guatemalan monetary unit":[["noun.quantity"],["Guatemalan monetary unit","monetary unit"]],
"south african monetary unit":[["noun.quantity"],["South African monetary unit","monetary unit"]],
"iranian monetary unit":[["noun.quantity"],["Iranian monetary unit","monetary unit"]],
"iranian rial":[["noun.quantity"],["Iranian rial","rial1","Iranian monetary unit"]],
"iranian dinar":[["noun.quantity"],["Iranian dinar","dinar9","Iranian monetary unit","Iranian rial"]],
"omani monetary unit":[["noun.quantity"],["Omani monetary unit","monetary unit"]],
"riyal-omani":[["noun.quantity"],["riyal-omani","Omani rial","rial2","Omani monetary unit"]],
"baiza":[["noun.quantity"],["baiza","baisa","Omani monetary unit","riyal-omani"]],
"yemeni monetary unit":[["noun.quantity"],["Yemeni monetary unit","monetary unit"]],
"yemeni rial":[["noun.quantity"],["Yemeni rial","rial","Yemeni monetary unit"]],
"yemeni fils":[["noun.quantity"],["Yemeni fils","fils1","Yemeni monetary unit"]],
"cambodian monetary unit":[["noun.quantity"],["Cambodian monetary unit","monetary unit"]],
"riel":[["noun.quantity"],["riel","Cambodian monetary unit"]],
"malaysian monetary unit":[["noun.quantity"],["Malaysian monetary unit","monetary unit"]],
"ringgit":[["noun.quantity"],["ringgit","Malaysian monetary unit"]],
"qatari monetary unit":[["noun.quantity"],["Qatari monetary unit","monetary unit"]],
"qatari riyal":[["noun.quantity"],["Qatari riyal","riyal2","Qatari monetary unit"]],
"qatari dirham":[["noun.quantity"],["Qatari dirham","dirham6","Qatari monetary unit","Qatari riyal"]],
"saudi arabian monetary unit":[["noun.quantity"],["Saudi Arabian monetary unit","monetary unit"]],
"saudi arabian riyal":[["noun.quantity"],["Saudi Arabian riyal","riyal3","Saudi Arabian monetary unit"]],
"qurush":[["noun.quantity"],["qurush","Saudi Arabian riyal","Saudi Arabian monetary unit"]],
"russian monetary unit":[["noun.quantity"],["Russian monetary unit","monetary unit"]],
"ruble":[["noun.quantity","noun.quantity"],["ruble","rouble","Russian monetary unit","ruble1","Tajikistani monetary unit"]],
"kopek":[["noun.quantity"],["kopek","kopeck","copeck","ruble","Russian monetary unit"]],
"armenian monetary unit":[["noun.quantity"],["Armenian monetary unit","monetary unit"]],
"dram":[["noun.quantity","noun.quantity","noun.quantity"],["dram","Armenian monetary unit","dram1","avoirdupois unit","ounce1","dram2","drachm","drachma2","apothecaries' unit","ounce2"]],
"lumma":[["noun.quantity"],["lumma","Armenian monetary unit"]],
"azerbaijani monetary unit":[["noun.quantity"],["Azerbaijani monetary unit","monetary unit"]],
"manat":[["noun.quantity","noun.quantity"],["manat","Azerbaijani monetary unit","manat1","Turkmen monetary unit"]],
"qepiq":[["noun.quantity"],["qepiq","Azerbaijani monetary unit"]],
"belarusian monetary unit":[["noun.quantity"],["Belarusian monetary unit","monetary unit"]],
"rubel":[["noun.quantity"],["rubel","Belarusian monetary unit"]],
"kapeika":[["noun.quantity"],["kapeika","Belarusian monetary unit"]],
"estonian monetary unit":[["noun.quantity"],["Estonian monetary unit","monetary unit"]],
"kroon":[["noun.quantity"],["kroon","Estonian monetary unit"]],
"sent":[["noun.quantity"],["sent","Estonian monetary unit"]],
"georgian monetary unit":[["noun.quantity"],["Georgian monetary unit","monetary unit"]],
"tetri":[["noun.quantity"],["tetri","Georgian monetary unit","lari"]],
"kazakhstani monetary unit":[["noun.quantity"],["Kazakhstani monetary unit","monetary unit"]],
"tenge":[["noun.quantity","noun.quantity"],["tenge","Kazakhstani monetary unit","tenge1","Turkmen monetary unit"]],
"tiyin":[["noun.quantity","noun.quantity"],["tiyin","Kazakhstani monetary unit","tiyin1","Uzbekistani monetary unit"]],
"latvian monetary unit":[["noun.quantity"],["Latvian monetary unit","monetary unit"]],
"lats":[["noun.quantity"],["lats","Latvian monetary unit"]],
"santims":[["noun.quantity"],["santims","Latvian monetary unit"]],
"lithuanian monetary unit":[["noun.quantity"],["Lithuanian monetary unit","monetary unit"]],
"litas":[["noun.quantity"],["litas","Lithuanian monetary unit"]],
"centas":[["noun.quantity"],["centas","Lithuanian monetary unit"]],
"kyrgyzstani monetary unit":[["noun.quantity"],["Kyrgyzstani monetary unit","monetary unit"]],
"som":[["noun.quantity","noun.quantity"],["som","Kyrgyzstani monetary unit","som1","Uzbekistani monetary unit"]],
"tyiyn":[["noun.quantity"],["tyiyn","Kyrgyzstani monetary unit"]],
"moldovan monetary unit":[["noun.quantity"],["Moldovan monetary unit","monetary unit"]],
"tajikistani monetary unit":[["noun.quantity"],["Tajikistani monetary unit","monetary unit"]],
"turkmen monetary unit":[["noun.quantity"],["Turkmen monetary unit","monetary unit"]],
"ukranian monetary unit":[["noun.quantity"],["Ukranian monetary unit","monetary unit"]],
"hryvnia":[["noun.quantity"],["hryvnia","Ukranian monetary unit"]],
"kopiyka":[["noun.quantity"],["kopiyka","Ukranian monetary unit","hryvnia"]],
"uzbekistani monetary unit":[["noun.quantity"],["Uzbekistani monetary unit","monetary unit"]],
"indian monetary unit":[["noun.quantity"],["Indian monetary unit","monetary unit"]],
"indian rupee":[["noun.quantity"],["Indian rupee","rupee1","Indian monetary unit"]],
"paisa":[["noun.quantity"],["paisa","fractional monetary unit","Indian rupee","Nepalese rupee","Pakistani rupee","taka"]],
"pakistani monetary unit":[["noun.quantity"],["Pakistani monetary unit","monetary unit"]],
"pakistani rupee":[["noun.quantity"],["Pakistani rupee","rupee2","Pakistani monetary unit"]],
"anna":[["noun.quantity"],["anna","Pakistani monetary unit","Indian monetary unit"]],
"mauritian monetary unit":[["noun.quantity"],["Mauritian monetary unit","monetary unit"]],
"mauritian rupee":[["noun.quantity"],["Mauritian rupee","rupee3","Mauritian monetary unit"]],
"nepalese monetary unit":[["noun.quantity"],["Nepalese monetary unit","monetary unit"]],
"nepalese rupee":[["noun.quantity"],["Nepalese rupee","rupee4","Nepalese monetary unit"]],
"seychelles monetary unit":[["noun.quantity"],["Seychelles monetary unit","monetary unit"]],
"seychelles rupee":[["noun.quantity"],["Seychelles rupee","rupee5","Seychelles monetary unit"]],
"sri lankan monetary unit":[["noun.quantity"],["Sri Lankan monetary unit","monetary unit"]],
"sri lanka rupee":[["noun.quantity"],["Sri Lanka rupee","rupee6","Sri Lankan monetary unit"]],
"indonesian monetary unit":[["noun.quantity"],["Indonesian monetary unit","monetary unit"]],
"rupiah":[["noun.quantity"],["rupiah","Indonesian monetary unit"]],
"austrian monetary unit":[["noun.quantity"],["Austrian monetary unit","monetary unit"]],
"schilling":[["noun.quantity"],["schilling","Austrian schilling","Austrian monetary unit"]],
"groschen":[["noun.quantity"],["groschen","schilling","Austrian monetary unit"]],
"israeli monetary unit":[["noun.quantity"],["Israeli monetary unit","monetary unit"]],
"shekel":[["noun.quantity"],["shekel","Israeli monetary unit"]],
"kenyan monetary unit":[["noun.quantity"],["Kenyan monetary unit","monetary unit"]],
"kenyan shilling":[["noun.quantity"],["Kenyan shilling","shilling2","kenyan monetary unit"]],
"somalian monetary unit":[["noun.quantity"],["Somalian monetary unit","monetary unit"]],
"somalian shilling":[["noun.quantity"],["Somalian shilling","shilling3","Somalian monetary unit"]],
"tanzanian monetary unit":[["noun.quantity"],["Tanzanian monetary unit","monetary unit"]],
"tanzanian shilling":[["noun.quantity"],["Tanzanian shilling","shilling4","Tanzanian monetary unit"]],
"ugandan monetary unit":[["noun.quantity"],["Ugandan monetary unit","monetary unit"]],
"ugandan shilling":[["noun.quantity"],["Ugandan shilling","shilling5","Ugandan monetary unit"]],
"ecuadoran monetary unit":[["noun.quantity"],["Ecuadoran monetary unit","monetary unit"]],
"guinean monetary unit":[["noun.quantity"],["Guinean monetary unit","monetary unit"]],
"guinean franc":[["noun.quantity"],["Guinean franc","franc"]],
"bangladeshi monetary unit":[["noun.quantity"],["Bangladeshi monetary unit","monetary unit"]],
"taka":[["noun.quantity"],["taka","Bangladeshi monetary unit"]],
"western samoan monetary unit":[["noun.quantity"],["Western Samoan monetary unit","monetary unit"]],
"tala":[["noun.quantity"],["tala","Western Samoan monetary unit"]],
"sene":[["noun.quantity"],["sene","tala","Western Samoan monetary unit"]],
"mongolian monetary unit":[["noun.quantity"],["Mongolian monetary unit","monetary unit"]],
"tugrik":[["noun.quantity"],["tugrik","tughrik","Mongolian monetary unit"]],
"mongo":[["noun.quantity"],["mongo","tugrik","Mongolian monetary unit"]],
"north korean monetary unit":[["noun.quantity"],["North Korean monetary unit","monetary unit"]],
"north korean won":[["noun.quantity"],["North Korean won","won1","North Korean monetary unit"]],
"chon":[["noun.quantity","noun.quantity"],["chon1","North Korean monetary unit","North Korean won","chon2","South Korean monetary unit","South Korean won"]],
"south korean monetary unit":[["noun.quantity"],["South Korean monetary unit","monetary unit"]],
"south korean won":[["noun.quantity"],["South Korean won","won2","South Korean monetary unit"]],
"japanese monetary unit":[["noun.quantity"],["Japanese monetary unit","monetary unit"]],
"yen":[["noun.quantity"],["yen","Japanese monetary unit"]],
"chinese monetary unit":[["noun.quantity"],["Chinese monetary unit","monetary unit"]],
"jiao":[["noun.quantity"],["jiao","yuan","Chinese monetary unit"]],
"fen":[["noun.quantity"],["fen","Chinese monetary unit","jiao"]],
"zairese monetary unit":[["noun.quantity"],["Zairese monetary unit","monetary unit"]],
"zaire":[["noun.quantity"],["zaire","Zairese monetary unit"]],
"likuta":[["noun.quantity"],["likuta","zaire","Zairese monetary unit"]],
"polish monetary unit":[["noun.quantity"],["Polish monetary unit","monetary unit"]],
"zloty":[["noun.quantity"],["zloty","Polish monetary unit"]],
"grosz":[["noun.quantity"],["grosz","zloty","Polish monetary unit"]],
"dol":[["noun.quantity"],["dol","pain unit"]],
"standard atmosphere":[["noun.quantity"],["standard atmosphere","atmosphere","atm","standard pressure","pressure unit"]],
"torr":[["noun.quantity"],["torr","millimeter of mercury","mm Hg","pressure unit"]],
"pounds per square inch":[["noun.quantity"],["pounds per square inch","psi","pressure unit"]],
"millibar":[["noun.quantity"],["millibar","pressure unit","bar"]],
"barye":[["noun.quantity"],["barye","bar absolute","microbar","pressure unit","bar"]],
"em":[["noun.quantity","noun.quantity"],["em2","pica em","pica","linear unit","inch","em1","em quad","mutton quad","area unit"]],
"en":[["noun.quantity"],["en","nut","linear unit","em2"]],
"agate line":[["noun.quantity"],["agate line","line","area unit"]],
"milline":[["noun.quantity"],["milline","printing unit"]],
"column inch":[["noun.quantity"],["column inch","inch2","area unit"]],
"decibel":[["noun.quantity"],["decibel","dB","sound unit"]],
"sone":[["noun.quantity"],["sone","sound unit","phon"]],
"phon":[["noun.quantity"],["phon","sound unit"]],
"erlang":[["noun.quantity"],["Erlang","telephone unit"]],
"millidegree":[["noun.quantity"],["millidegree","temperature unit"]],
"degree centigrade":[["noun.quantity"],["degree centigrade","degree Celsius","C2","degree3"]],
"degree fahrenheit":[["noun.quantity"],["degree Fahrenheit","F2","degree3"]],
"rankine":[["noun.quantity"],["Rankine","temperature unit"]],
"degree day":[["noun.quantity"],["degree day","temperature unit"]],
"standard temperature":[["noun.quantity"],["standard temperature","degree centigrade"]],
"atomic mass unit":[["noun.quantity"],["atomic mass unit","mass unit"]],
"mass number":[["noun.quantity"],["mass number","nucleon number","mass unit"]],
"system of weights":[["noun.quantity"],["system of weights","weight1","system of measurement"]],
"avoirdupois":[["noun.quantity"],["avoirdupois","avoirdupois weight","system of weights"]],
"avoirdupois unit":[["noun.quantity"],["avoirdupois unit","mass unit","avoirdupois weight","English system"]],
"troy unit":[["noun.quantity"],["troy unit","weight unit","troy weight"]],
"apothecaries' unit":[["noun.quantity"],["apothecaries' unit","apothecaries' weight","weight unit"]],
"metric weight unit":[["noun.quantity"],["metric weight unit","weight unit2","mass unit","metric unit","metric system"]],
"catty":[["noun.quantity","noun.location:China"],["catty","cattie","weight unit"]],
"crith":[["noun.quantity"],["crith","weight unit"]],
"maund":[["noun.quantity"],["maund","weight unit"]],
"obolus":[["noun.quantity"],["obolus","weight unit","gram"]],
"picul":[["noun.quantity"],["picul","weight unit"]],
"pood":[["noun.quantity"],["pood","weight unit"]],
"rotl":[["noun.quantity"],["rotl","weight unit"]],
"tael":[["noun.quantity"],["tael","weight unit"]],
"tod":[["noun.quantity","noun.location:Britain"],["tod","weight unit"]],
"ounce":[["noun.quantity","noun.quantity"],["ounce1","oz.","avoirdupois unit","pound9","ounce2","troy ounce","apothecaries' ounce","apothecaries' unit","troy unit","troy pound"]],
"half pound":[["noun.quantity"],["half pound","avoirdupois unit","pound9"]],
"quarter pound":[["noun.quantity"],["quarter pound","avoirdupois unit","pound"]],
"hundredweight":[["noun.quantity","noun.quantity","noun.quantity"],["hundredweight1","cwt1","long hundredweight","avoirdupois unit","long ton","hundredweight2","cwt2","short hundredweight","centner1","cental","quintal1","avoirdupois unit","short ton","hundredweight3","metric hundredweight","doppelzentner","centner3","metric weight unit","quintal2"]],
"long ton":[["noun.quantity"],["long ton","ton1","gross ton","avoirdupois unit"]],
"short ton":[["noun.quantity"],["short ton","ton2","net ton","avoirdupois unit","kiloton"]],
"pennyweight":[["noun.quantity"],["pennyweight","troy unit","ounce2"]],
"troy pound":[["noun.quantity"],["troy pound","apothecaries' pound","apothecaries' unit","troy unit"]],
"microgram":[["noun.quantity"],["microgram","mcg","metric weight unit","milligram"]],
"milligram":[["noun.quantity"],["milligram","mg","metric weight unit","grain3"]],
"nanogram":[["noun.quantity"],["nanogram","ng","metric weight unit","microgram"]],
"decigram":[["noun.quantity"],["decigram","dg","metric weight unit","carat"]],
"carat":[["noun.quantity"],["carat","metric weight unit","gram"]],
"gram atom":[["noun.quantity"],["gram atom","gram-atomic weight","metric weight unit"]],
"gram molecule":[["noun.quantity","adj.pert:molal","adj.pert:molar2","adj.pert:molar"],["gram molecule","mole","mol","metric weight unit"]],
"dekagram":[["noun.quantity"],["dekagram","decagram","dkg","dag","metric weight unit","hectogram"]],
"hectogram":[["noun.quantity"],["hectogram","hg","metric weight unit","kilogram"]],
"kilogram":[["noun.quantity"],["kilogram","kg","kilo","metric weight unit","myriagram"]],
"myriagram":[["noun.quantity"],["myriagram","myg","metric weight unit","centner2"]],
"centner":[["noun.quantity"],["centner2","metric weight unit","hundredweight3"]],
"quintal":[["noun.quantity"],["quintal2","metric weight unit","metric ton"]],
"metric ton":[["noun.quantity"],["metric ton","MT","tonne","t1","metric weight unit"]],
"erg":[["noun.quantity"],["erg","work unit","joule"]],
"electron volt":[["noun.quantity"],["electron volt","eV","work unit"]],
"calorie":[["noun.quantity","adj.pert:caloric","noun.quantity","adj.pert:caloric2"],["calorie1","gram calorie","small calorie","work unit","Calorie2","Calorie2","kilogram calorie","kilocalorie","large calorie","nutritionist's calorie","work unit"]],
"british thermal unit":[["noun.quantity","B.Th.U."],["British thermal unit","BTU","work unit","therm"]],
"therm":[["noun.quantity"],["therm","work unit"]],
"watt-hour":[["noun.quantity"],["watt-hour","work unit","kilowatt hour"]],
"kilowatt hour":[["noun.quantity","B.T.U."],["kilowatt hour","kW-hr","Board of Trade unit","work unit"]],
"foot-pound":[["noun.quantity"],["foot-pound","work unit","foot-ton"]],
"foot-ton":[["noun.quantity"],["foot-ton","work unit"]],
"foot-poundal":[["noun.quantity"],["foot-poundal","work unit"]],
"horsepower-hour":[["noun.quantity"],["horsepower-hour","work unit"]],
"kilogram-meter":[["noun.quantity"],["kilogram-meter","work unit"]],
"natural number":[["noun.quantity"],["natural number","number"]],
"integer":[["noun.quantity"],["integer","whole number","number"]],
"addend":[["noun.quantity"],["addend","number"]],
"augend":[["noun.quantity"],["augend","number"]],
"minuend":[["noun.quantity"],["minuend","number"]],
"subtrahend":[["noun.quantity"],["subtrahend","number"]],
"complex number":[["noun.quantity","noun.cognition:mathematics"],["complex number","complex quantity","imaginary number","imaginary","number"]],
"complex conjugate":[["noun.quantity"],["complex conjugate","complex number"]],
"real number":[["noun.quantity"],["real number","real","complex number"]],
"pure imaginary number":[["noun.quantity"],["pure imaginary number","complex number"]],
"imaginary part":[["noun.quantity"],["imaginary part","imaginary part of a complex number","pure imaginary number","complex number"]],
"rational number":[["noun.quantity"],["rational number","rational","real number"]],
"irrational number":[["noun.quantity"],["irrational number","irrational","real number"]],
"transcendental number":[["noun.quantity"],["transcendental number","irrational number"]],
"algebraic number":[["noun.quantity"],["algebraic number","irrational number"]],
"biquadrate":[["noun.quantity","adj.pert:biquadratic","adj.pert:biquadratic"],["biquadrate","biquadratic","quartic","fourth power","number"]],
"square root":[["noun.quantity"],["square root","root"]],
"cube root":[["noun.quantity"],["cube root","root"]],
"common fraction":[["noun.quantity"],["common fraction","simple fraction","fraction"]],
"numerator":[["noun.quantity"],["numerator","dividend"]],
"denominator":[["noun.quantity"],["denominator","divisor"]],
"divisor":[["noun.quantity","noun.quantity","verb.cognition:factor","verb.cognition:factorize"],["divisor","number","divisor1","factor","integer"]],
"multiplier":[["noun.quantity","verb.cognition:multiply"],["multiplier","multiplier factor","number"]],
"multiplicand":[["noun.quantity"],["multiplicand","number"]],
"scale factor":[["noun.quantity"],["scale factor","multiplier"]],
"time-scale factor":[["noun.quantity","noun.cognition:simulation"],["time-scale factor","scale factor"]],
"equivalent-binary-digit factor":[["noun.quantity"],["equivalent-binary-digit factor","divisor1"]],
"aliquot":[["noun.quantity","adj.all:fractional^aliquot"],["aliquot","aliquant","aliquot part","divisor"]],
"aliquant":[["noun.quantity"],["aliquant","aliquot","aliquant part","divisor"]],
"common divisor":[["noun.quantity"],["common divisor","common factor","common measure","divisor1"]],
"greatest common divisor":[["noun.quantity"],["greatest common divisor","greatest common factor","highest common factor","common divisor"]],
"common multiple":[["noun.quantity"],["common multiple","integer"]],
"improper fraction":[["noun.quantity"],["improper fraction","fraction"]],
"proper fraction":[["noun.quantity"],["proper fraction","fraction"]],
"complex fraction":[["noun.quantity"],["complex fraction","compound fraction","fraction"]],
"decimal fraction":[["noun.quantity","verb.change:decimalize1","verb.change:decimalise1"],["decimal fraction","decimal","proper fraction"]],
"circulating decimal":[["noun.quantity"],["circulating decimal","recurring decimal","repeating decimal","decimal fraction"]],
"continued fraction":[["noun.quantity"],["continued fraction","fraction"]],
"one-half":[["noun.quantity"],["one-half","half","common fraction"]],
"fifty percent":[["noun.quantity"],["fifty percent","one-half"]],
"one-third":[["noun.quantity"],["one-third","third","tierce","common fraction"]],
"two-thirds":[["noun.quantity"],["two-thirds","common fraction"]],
"one-fourth":[["noun.quantity","verb.contact:quarter1","verb.social:quarter"],["one-fourth","fourth","one-quarter","quarter1","fourth part","twenty-five percent","quartern","common fraction"]],
"three-fourths":[["noun.quantity"],["three-fourths","three-quarters","common fraction"]],
"one-fifth":[["noun.quantity"],["one-fifth","fifth","fifth part","twenty percent","common fraction"]],
"one-sixth":[["noun.quantity"],["one-sixth","sixth","common fraction"]],
"one-seventh":[["noun.quantity"],["one-seventh","seventh","common fraction"]],
"one-eighth":[["noun.quantity"],["one-eighth","eighth","common fraction"]],
"one-ninth":[["noun.quantity"],["one-ninth","ninth","common fraction"]],
"one-tenth":[["noun.quantity"],["one-tenth","tenth","tenth part","ten percent","common fraction"]],
"one-twelfth":[["noun.quantity"],["one-twelfth","twelfth","twelfth part","duodecimal","common fraction"]],
"one-sixteenth":[["noun.quantity"],["one-sixteenth","sixteenth","sixteenth part","common fraction"]],
"one-thirty-second":[["noun.quantity"],["one-thirty-second","thirty-second","thirty-second part","common fraction"]],
"one-sixtieth":[["noun.quantity"],["one-sixtieth","sixtieth","common fraction"]],
"one-sixty-fourth":[["noun.quantity"],["one-sixty-fourth","sixty-fourth","common fraction"]],
"one-hundredth":[["noun.quantity"],["one-hundredth","hundredth","one percent","common fraction"]],
"one-thousandth":[["noun.quantity"],["one-thousandth","thousandth","common fraction"]],
"one-ten-thousandth":[["noun.quantity"],["one-ten-thousandth","ten-thousandth","common fraction"]],
"one-hundred-thousandth":[["noun.quantity"],["one-hundred-thousandth","common fraction"]],
"one-millionth":[["noun.quantity"],["one-millionth","millionth","common fraction"]],
"one-hundred-millionth":[["noun.quantity"],["one-hundred-millionth","common fraction"]],
"one-billionth":[["noun.quantity"],["one-billionth","billionth","common fraction"]],
"one-trillionth":[["noun.quantity"],["one-trillionth","trillionth","common fraction"]],
"one-quadrillionth":[["noun.quantity"],["one-quadrillionth","quadrillionth","common fraction"]],
"one-quintillionth":[["noun.quantity"],["one-quintillionth","quintillionth","common fraction"]],
"nothing":[["noun.quantity","verb.change:zero1"],["nothing","nil","nix","nada","null","aught","cipher","cypher","goose egg","naught","zero2","zilch","zip","zippo","relative quantity"]],
"nihil":[["noun.quantity","noun.communication:Latin"],["nihil","nothing"]],
"bugger all":[["noun.quantity","noun.location:Britain","noun.communication:obscenity"],["bugger all","fuck all","Fanny Adams","sweet Fanny Adams","nothing"]],
"binary digit":[["noun.quantity"],["binary digit","digit"]],
"octal digit":[["noun.quantity"],["octal digit","digit"]],
"decimal digit":[["noun.quantity"],["decimal digit","digit"]],
"duodecimal digit":[["noun.quantity"],["duodecimal digit","digit"]],
"hexadecimal digit":[["noun.quantity"],["hexadecimal digit","digit"]],
"significant digit":[["noun.quantity"],["significant digit","significant figure","digit"]],
"two":[["noun.quantity"],["two","2\"","II","deuce","digit"]],
"doubleton":[["noun.quantity","noun.act:bridge"],["doubleton","couple"]],
"three":[["noun.quantity"],["three","3\"","III","trio","threesome","tierce1","leash","troika","triad","trine","trinity","ternary","ternion","triplet","tercet","terzetto","trey","deuce-ace","digit"]],
"four":[["noun.quantity"],["four","4\"","IV","tetrad","quatern","quaternion","quaternary","quaternity","quartet","quadruplet","foursome","Little Joe","digit"]],
"five":[["noun.quantity"],["five","5\"","V2","cinque","quint","quintet","fivesome","quintuplet","pentad","fin","Phoebe","Little Phoebe","digit"]],
"six":[["noun.quantity"],["six","6\"","VI","sixer","sise","Captain Hicks","half a dozen","sextet","sestet","sextuplet","hexad","digit"]],
"seven":[["noun.quantity","adj.all:cardinal^seven"],["seven","7\"","VII","sevener","heptad","septet","septenary","digit"]],
"eight":[["noun.quantity"],["eight","8\"","VIII","eighter","eighter from Decatur","octad","ogdoad","octonary","octet","digit"]],
"nine":[["noun.quantity"],["nine","9\"","IX","niner","Nina from Carolina","ennead","digit"]],
"large integer":[["noun.quantity"],["large integer","integer"]],
"double digit":[["noun.quantity"],["double digit","integer"]],
"ten":[["noun.quantity"],["ten","10\"","X","tenner","decade","large integer"]],
"eleven":[["noun.quantity"],["eleven","11\"","XI","large integer"]],
"twelve":[["noun.quantity","adj.all:cardinal^dozen"],["twelve","12\"","XII","dozen","large integer"]],
"boxcars":[["noun.quantity","noun.communication:plural"],["boxcars","twelve"]],
"thirteen":[["noun.quantity"],["thirteen","13\"","XIII","baker's dozen","long dozen","large integer"]],
"fourteen":[["noun.quantity"],["fourteen","14\"","XIV","large integer"]],
"fifteen":[["noun.quantity","adj.all:cardinal^fifteen"],["fifteen","15\"","XV","large integer"]],
"sixteen":[["noun.quantity"],["sixteen","16\"","XVI","large integer"]],
"seventeen":[["noun.quantity","adj.all:cardinal^seventeen"],["seventeen","17\"","XVII","large integer"]],
"eighteen":[["noun.quantity"],["eighteen","18\"","XVIII","large integer"]],
"nineteen":[["noun.quantity","adj.all:cardinal^nineteen"],["nineteen","19\"","XIX","large integer"]],
"twenty":[["noun.quantity"],["twenty","20\"","XX","large integer"]],
"twenty-one":[["noun.quantity"],["twenty-one","21\"","XXI","large integer"]],
"twenty-three":[["noun.quantity"],["twenty-three","23\"","XXIII","large integer"]],
"twenty-four":[["noun.quantity"],["twenty-four","24\"","XXIV","two dozen","large integer"]],
"twenty-five":[["noun.quantity"],["twenty-five","25\"","XXV","large integer"]],
"twenty-six":[["noun.quantity"],["twenty-six","26\"","XXVI","large integer"]],
"twenty-seven":[["noun.quantity"],["twenty-seven","27\"","XXVII","large integer"]],
"twenty-eight":[["noun.quantity"],["twenty-eight","28\"","XXVIII","large integer"]],
"twenty-nine":[["noun.quantity"],["twenty-nine","29\"","XXIX","large integer"]],
"thirty":[["noun.quantity"],["thirty","30\"","XXX","large integer"]],
"forty":[["noun.quantity"],["forty","40\"","XL","large integer"]],
"fifty":[["noun.quantity","adj.all:cardinal^fifty"],["fifty","50\"","L6","large integer"]],
"sixty":[["noun.quantity"],["sixty","60\"","LX","large integer"]],
"seventy":[["noun.quantity","adj.all:cardinal^seventy"],["seventy","70\"","LXX","large integer"]],
"eighty":[["noun.quantity"],["eighty","80\"","LXXX","fourscore","large integer"]],
"ninety":[["noun.quantity"],["ninety","90\"","XC","large integer"]],
"hundred":[["noun.quantity"],["hundred","100\"","C1","century","one C","large integer"]],
"long hundred":[["noun.quantity"],["long hundred","great hundred","120\"","large integer"]],
"five hundred":[["noun.quantity"],["five hundred","500\"","D","large integer"]],
"thousand":[["noun.quantity"],["thousand","one thousand","1000\"","M1","K6","chiliad","G1","grand","thou","yard2","large integer"]],
"millenary":[["noun.quantity"],["millenary","thousand"]],
"great gross":[["noun.quantity"],["great gross","1728\"","large integer"]],
"ten thousand":[["noun.quantity"],["ten thousand","10000\"","myriad","large integer"]],
"hundred thousand":[["noun.quantity"],["hundred thousand","100000\"","lakh","large integer"]],
"million":[["noun.quantity","noun.quantity"],["million","1000000\"","one thousand thousand","meg","large integer","million1","billion2","trillion2","zillion","jillion","gazillion","bazillion","large indefinite quantity"]],
"crore":[["noun.quantity","noun.location:India"],["crore","large integer"]],
"billion":[["noun.quantity","adj.all:cardinal^billion","noun.location:US","noun.quantity","adj.all:cardinal^billion1","noun.location:Britain"],["billion","one thousand million","1000000000\"","large integer","billion1","one million million","1000000000000\"","large integer"]],
"milliard":[["noun.quantity","noun.location:Britain"],["milliard","billion"]],
"trillion":[["noun.quantity","noun.location:US","noun.location:France","noun.quantity","noun.location:Britain","noun.location:Germany"],["trillion","one million million1","1000000000000\"1","large integer","trillion1","one million million million","large integer"]],
"quadrillion":[["noun.quantity","noun.location:US","noun.location:France","noun.quantity","noun.location:Britain","noun.location:Germany"],["quadrillion","large integer","quadrillion1","large integer"]],
"quintillion":[["noun.quantity","noun.location:US","noun.location:France"],["quintillion","large integer"]],
"sextillion":[["noun.quantity","noun.location:US","noun.location:France"],["sextillion","large integer"]],
"septillion":[["noun.quantity","noun.location:US","noun.location:France"],["septillion","large integer"]],
"octillion":[["noun.quantity","noun.location:US","noun.location:France"],["octillion","large integer"]],
"aleph-null":[["noun.quantity"],["aleph-null","aleph-nought","aleph-zero","large integer"]],
"formatted capacity":[["noun.quantity","noun.cognition:computer science"],["formatted capacity","capacity1"]],
"unformatted capacity":[["noun.quantity","noun.cognition:computer science"],["unformatted capacity","capacity1"]],
"containerful":[["noun.quantity"],["containerful","indefinite quantity"]],
"headspace":[["noun.quantity"],["headspace","indefinite quantity"]],
"large indefinite quantity":[["noun.quantity"],["large indefinite quantity","large indefinite amount","indefinite quantity"]],
"chunk":[["noun.quantity"],["chunk","large indefinite quantity"]],
"pulmonary reserve":[["noun.quantity"],["pulmonary reserve","reserve"]],
"small indefinite quantity":[["noun.quantity"],["small indefinite quantity","small indefinite amount","indefinite quantity"]],
"hair's-breadth":[["noun.quantity"],["hair's-breadth","hairsbreadth","hair","whisker","small indefinite quantity"]],
"modicum":[["noun.quantity"],["modicum","small indefinite quantity"]],
"shoestring":[["noun.quantity"],["shoestring","shoe string","small indefinite quantity"]],
"little":[["noun.quantity"],["little","small indefinite quantity"]],
"shtikl":[["noun.quantity"],["shtikl","shtickl","schtikl","schtickl","shtik"]],
"tad":[["noun.quantity"],["tad","shade","small indefinite quantity"]],
"spillage":[["noun.quantity"],["spillage","indefinite quantity"]],
"ullage":[["noun.quantity"],["ullage","indefinite quantity"]],
"top-up":[["noun.quantity","noun.location:Britain"],["top-up","indefinite quantity"]],
"armful":[["noun.quantity"],["armful","containerful"]],
"barnful":[["noun.quantity"],["barnful","containerful"]],
"busload":[["noun.quantity"],["busload","large indefinite quantity"]],
"capful":[["noun.quantity"],["capful","containerful"]],
"carful":[["noun.quantity"],["carful","containerful"]],
"cartload":[["noun.quantity"],["cartload","containerful"]],
"cask":[["noun.quantity"],["cask","caskful","containerful"]],
"handful":[["noun.quantity","noun.quantity"],["handful","fistful","containerful","handful1","smattering","small indefinite quantity"]],
"hatful":[["noun.quantity"],["hatful","containerful"]],
"houseful":[["noun.quantity"],["houseful","containerful"]],
"lapful":[["noun.quantity"],["lapful","containerful"]],
"mouthful":[["noun.quantity"],["mouthful","containerful"]],
"pail":[["noun.quantity"],["pail","pailful","containerful"]],
"pipeful":[["noun.quantity"],["pipeful","containerful"]],
"pocketful":[["noun.quantity"],["pocketful","containerful"]],
"roomful":[["noun.quantity"],["roomful","containerful"]],
"shelfful":[["noun.quantity"],["shelfful","containerful"]],
"shoeful":[["noun.quantity"],["shoeful","containerful"]],
"skinful":[["noun.quantity","noun.communication:slang"],["skinful","indefinite quantity"]],
"skepful":[["noun.quantity"],["skepful","containerful"]],
"dessertspoon":[["noun.quantity"],["dessertspoon","dessertspoonful","containerful"]],
"droplet":[["noun.quantity","noun.shape:drop","noun.quantity:drop"],["droplet","drop"]],
"dollop":[["noun.quantity"],["dollop","small indefinite quantity"]],
"trainload":[["noun.quantity"],["trainload","load"]],
"dreg":[["noun.quantity"],["dreg","small indefinite quantity"]],
"tot":[["noun.quantity"],["tot","small indefinite quantity"]],
"barrels":[["noun.quantity"],["barrels","large indefinite quantity"]],
"billyo":[["noun.quantity"],["billyo","billyoh","billy-ho","all get out","large indefinite quantity"]],
"boatload":[["noun.quantity"],["boatload","shipload","carload","large indefinite quantity"]],
"haymow":[["noun.quantity"],["haymow","batch"]],
"infinitude":[["noun.quantity"],["infinitude","large indefinite quantity"]],
"much":[["noun.quantity"],["much","large indefinite quantity"]],
"myriad":[["noun.quantity","adj.all:incalculable^myriad"],["myriad1","large indefinite quantity"]],
"small fortune":[["noun.quantity"],["small fortune","large indefinite quantity"]],
"tons":[["noun.quantity"],["tons","dozens","heaps","lots","piles","scores","stacks","loads","rafts","slews","wads","oodles","gobs","scads","lashings","large indefinite quantity"]],
"breathing room":[["noun.quantity"],["breathing room","breathing space","room"]],
"houseroom":[["noun.quantity"],["houseroom","room"]],
"living space":[["noun.quantity"],["living space","lebensraum","room"]],
"sea room":[["noun.quantity"],["sea room","room"]],
"vital capacity":[["noun.quantity","noun.cognition:diagnostic test"],["vital capacity","capacity"]],
"stp":[["noun.quantity","s.t.p."],["STP","standard temperature","standard pressure"]]
} | Seagat2011/NLP-Story-Engine | wn/DICT/mysql-wn-data.noun.quantity.js | JavaScript | gpl-2.0 | 96,743 |
<?php
/*
homepage: http://arc.semsol.org/
license: http://arc.semsol.org/license
class: ARC2 RDF/XML Serializer
author: Benjamin Nowack
version: 2009-02-12 (Fix: scheme-detection: scheme must have at least 2 chars, thanks to Eric Schoonover)
*/
ARC2::inc('RDFSerializer');
class ARC2_RDFXMLSerializer extends ARC2_RDFSerializer {
function __construct($a = '', &$caller) {
parent::__construct($a, $caller);
}
function ARC2_RDFXMLSerializer($a = '', &$caller) {
$this->__construct($a, $caller);
}
function __init() {
parent::__init();
$this->content_header = 'application/rdf+xml';
$this->pp_containers = $this->v('serializer_prettyprint_containers', 0, $this->a);
}
/* */
function getTerm($v, $type) {
if (!is_array($v)) {/* uri or bnode */
if (preg_match('/^\_\:(.*)$/', $v, $m)) {
return ' rdf:nodeID="' . $m[1] . '"';
}
if ($type == 's') {
return ' rdf:about="' . htmlspecialchars($v) . '"';
}
if ($type == 'p') {
if ($pn = $this->getPName($v)) {
return $pn;
}
return 0;
}
if ($type == 'o') {
$v = $this->expandPName($v);
if (!preg_match('/^[a-z0-9]{2,}\:[^\s]+$/is', $v)) return $this->getTerm(array('value' => $v, 'type' => 'literal'), $type);
return ' rdf:resource="' . htmlspecialchars($v) . '"';
}
if ($type == 'datatype') {
$v = $this->expandPName($v);
return ' rdf:datatype="' . htmlspecialchars($v) . '"';
}
if ($type == 'lang') {
return ' xml:lang="' . htmlspecialchars($v) . '"';
}
}
if ($v['type'] != 'literal') {
return $this->getTerm($v['value'], 'o');
}
/* literal */
$dt = isset($v['datatype']) ? $v['datatype'] : '';
$lang = isset($v['lang']) ? $v['lang'] : '';
if ($dt == 'http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral') {
return ' rdf:parseType="Literal">' . $v['value'];
}
elseif ($dt) {
return $this->getTerm($dt, 'datatype') . '>' . htmlspecialchars($v['value']);
}
elseif ($lang) {
return $this->getTerm($lang, 'lang') . '>' . htmlspecialchars($v['value']);
}
return '>' . htmlspecialchars($v['value']);
}
function getHead() {
$r = '';
$nl = "\n";
$r .= '<?xml version="1.0" encoding="UTF-8"?>';
$r .= $nl . '<rdf:RDF';
$first_ns = 1;
foreach ($this->used_ns as $v) {
$r .= $first_ns ? ' ' : $nl . ' ';
$r .= 'xmlns:' . $this->nsp[$v] . '="' .$v. '"';
$first_ns = 0;
}
$r .= '>';
return $r;
}
function getFooter() {
$r = '';
$nl = "\n";
$r .= $nl . $nl . '</rdf:RDF>';
return $r;
}
function getSerializedIndex($index, $raw = 0) {
$r = '';
$nl = "\n";
foreach ($index as $raw_s => $ps) {
$r .= $r ? $nl . $nl : '';
$s = $this->getTerm($raw_s, 's');
$tag = 'rdf:Description';
$sub_ps = 0;
/* pretty containers */
if ($this->pp_containers && ($ctag = $this->getContainerTag($ps))) {
$tag = 'rdf:' . $ctag;
list($ps, $sub_ps) = $this->splitContainerEntries($ps);
}
$r .= ' <' . $tag . '' .$s . '>';
$first_p = 1;
foreach ($ps as $p => $os) {
if (!$os) continue;
if ($p = $this->getTerm($p, 'p')) {
$r .= $nl . str_pad('', 4);
$first_o = 1;
if (!is_array($os)) {/* single literal o */
$os = array(array('value' => $os, 'type' => 'literal'));
}
foreach ($os as $o) {
$o = $this->getTerm($o, 'o');
$r .= $first_o ? '' : $nl . ' ';
$r .= '<' . $p;
$r .= $o;
$r .= preg_match('/\>/', $o) ? '</' . $p . '>' : '/>';
$first_o = 0;
}
$first_p = 0;
}
}
$r .= $r ? $nl . ' </' . $tag . '>' : '';
if ($sub_ps) $r .= $nl . $nl . $this->getSerializedIndex(array($raw_s => $sub_ps), 1);
}
if ($raw) {
return $r;
}
return $this->getHead() . $nl . $nl . $r . $this->getFooter();
}
/* */
function getContainerTag($ps) {
$rdf = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
if (!isset($ps[$rdf . 'type'])) return '';
$types = $ps[$rdf . 'type'];
foreach ($types as $type) {
if (!in_array($type['value'], array($rdf . 'Bag', $rdf . 'Seq', $rdf . 'Alt'))) return '';
return str_replace($rdf, '', $type['value']);
}
}
function splitContainerEntries($ps) {
$rdf = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
$items = array();
$rest = array();
foreach ($ps as $p => $os) {
$p_short = str_replace($rdf, '', $p);
if ($p_short === 'type') continue;
if (preg_match('/^\_([0-9]+)$/', $p_short, $m)) {
$items = array_merge($items, $os);
}
else {
$rest[$p] = $os;
}
}
if ($items) return array(array($rdf . 'li' => $items), $rest);
return array($rest, 0);
}
/* */
}
| baxtree/OKBook | sites/all/modules/rdf/vendor/arc/serializers/ARC2_RDFXMLSerializer.php | PHP | gpl-2.0 | 5,008 |
package dataset;
public class UndefinedSampleLengthException extends Exception {
private static final long serialVersionUID = 1L;
}
| ric2b/POO | java/src/dataset/UndefinedSampleLengthException.java | Java | gpl-2.0 | 135 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Evgeniya G. Maenkova
*/
package org.apache.harmony.awt.text;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.swing.text.Element;
import javax.swing.text.View;
public abstract class TextFactory {
private static final String FACTORY_IMPL_CLS_NAME =
"javax.swing.text.TextFactoryImpl"; //$NON-NLS-1$
private static final TextFactory viewFactory = createTextFactory();
public static TextFactory getTextFactory() {
return viewFactory;
}
private static TextFactory createTextFactory() {
PrivilegedAction<TextFactory> createAction = new PrivilegedAction<TextFactory>() {
public TextFactory run() {
try {
Class<?> factoryImplClass = Class
.forName(FACTORY_IMPL_CLS_NAME);
Constructor<?> defConstr =
factoryImplClass.getDeclaredConstructor(new Class[0]);
defConstr.setAccessible(true);
return (TextFactory)defConstr.newInstance(new Object[0]);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
};
return AccessController.doPrivileged(createAction);
}
public abstract RootViewContext createRootView(final Element element);
public abstract View createPlainView(final Element e);
public abstract View createWrappedPlainView(final Element e);
public abstract View createFieldView(final Element e);
public abstract View createPasswordView(Element e);
public abstract TextCaret createCaret();
}
| skyHALud/codenameone | Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/awt/src/main/java/common/org/apache/harmony/awt/text/TextFactory.java | Java | gpl-2.0 | 3,164 |
<?php
/**
* @package sauto
* @subpackage Base
* @author Dacian Strain {@link http://shop.elbase.eu}
* @author Created on 17-Nov-2013
* @license GNU/GPL
*/
//-- No direct access
defined('_JEXEC') || die('=;)');
$id =& JRequest::getVar( 'id', '', 'post', 'string' );
$db = JFactory::getDbo();
$query = "DELETE FROM #__sa_stare_auto WHERE `id` = '".$id."'";
$db->setQuery($query);
$db->query();
$app =& JFactory::getApplication();
$redirect = 'index.php?option=com_sauto&task=setari&action=stare';
$app->redirect($redirect, 'Stare auto eliminata cu succes');
| grchis/android | administrator/components/com_sauto/assets/includes/p_delete_stare.php | PHP | gpl-2.0 | 581 |
var hilbert = (function() {
// From Mike Bostock: http://bl.ocks.org/597287
// Adapted from Nick Johnson: http://bit.ly/biWkkq
var pairs = [
[[0, 3], [1, 0], [3, 1], [2, 0]],
[[2, 1], [1, 1], [3, 0], [0, 2]],
[[2, 2], [3, 3], [1, 2], [0, 1]],
[[0, 0], [3, 2], [1, 3], [2, 3]]
];
// d2xy and rot are from:
// http://en.wikipedia.org/wiki/Hilbert_curve#Applications_and_mapping_algorithms
var rot = function(n, x, y, rx, ry) {
if (ry === 0) {
if (rx === 1) {
x = n - 1 - x;
y = n - 1 - y;
}
return [y, x];
}
return [x, y];
};
return {
xy2d: function(x, y, z) {
var quad = 0,
pair,
i = 0;
while (--z >= 0) {
pair = pairs[quad][(x & (1 << z) ? 2 : 0) | (y & (1 << z) ? 1 : 0)];
i = (i << 2) | pair[0];
quad = pair[1];
}
return i;
},
d2xy: function(z, t) {
var n = 1 << z,
x = 0,
y = 0;
for (var s = 1; s < n; s *= 2) {
var rx = 1 & (t / 2),
ry = 1 & (t ^ rx);
var xy = rot(s, x, y, rx, ry);
x = xy[0] + s * rx;
y = xy[1] + s * ry;
t /= 4;
}
return [x, y];
}
};
})();
| eggla/LA-glazed | sites/all/modules/openlayers/modules/openlayers_library/src/Plugin/Component/Hilbert/js/hilbert_algo.js | JavaScript | gpl-2.0 | 1,468 |
<?php include("./lib/template/mini_calendrier.php"); ?>
<div id="lecorps">
<?php include("./lib/template/menu_edt.php"); ?>
<div id="art-main">
<div class="art-sheet">
<div class="art-sheet-tl"></div>
<div class="art-sheet-tr"></div>
<div class="art-sheet-bl"></div>
<div class="art-sheet-br"></div>
<div class="art-sheet-tc"></div>
<div class="art-sheet-bc"></div>
<div class="art-sheet-cl"></div>
<div class="art-sheet-cr"></div>
<div class="art-sheet-cc"></div>
<div class="art-sheet-body">
<div class="art-nav">
<div class="l"></div>
<div class="r"></div>
<?php include("menu_top.php"); ?>
</div>
<div class="art-content-layout">
<div class="art-content-layout-row">
<div class="art-layout-cell art-content">
<div class="art-post">
<div class="art-post-tl"></div>
<div class="art-post-tr"></div>
<div class="art-post-bl"></div>
<div class="art-post-br"></div>
<div class="art-post-tc"></div>
<div class="art-post-bc"></div>
<div class="art-post-cl"></div>
<div class="art-post-cr"></div>
<div class="art-post-cc"></div>
<div class="art-post-body">
<div class="art-post-inner art-article">
<div class="art-postmetadataheader">
<h2 class="art-postheader">
Future interface of module EDT
</h2>
</div>
<div class="art-postcontent">
<!-- article-content -->
<p> This part of the software is under development. It is the new interface of module EDT, resulting of a complete refactorisation of the module. The objective is to pass all the module into object MVC.</p>
<div class="cleared"></div>
<!-- /article-content -->
</div>
<div class="cleared"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php include("footer.php"); ?>
</div>
</div> | pollux1er/SajoscolApp | edt_organisation/lib/template/indexSuccess.php | PHP | gpl-2.0 | 2,906 |
<?php
/**
*
* @category modules
* @package news
* @author WebsiteBaker Project
* @copyright 2004-2009, Ryan Djurovich
* @copyright 2009-2011, Website Baker Org. e.V.
* @link http://www.websitebaker2.org/
* @license http://www.gnu.org/licenses/gpl.html
* @platform WebsiteBaker 2.8.x
* @requirements PHP 5.2.2 and higher
* @version $Id$
* @filesource $HeadURL$
* @lastmodified $Date$
*
*/
//Modul Description
$module_description = 'Den här sidtypen är designad för att skapa en nyhetssida.';
//Variables for the backend
$MOD_NEWS['SETTINGS'] = 'Inställningar';
//Variables for the frontend
$MOD_NEWS['TEXT_READ_MORE'] = 'Läs mer';
$MOD_NEWS['TEXT_POSTED_BY'] = 'Postat av';
$MOD_NEWS['TEXT_ON'] = 'den';
$MOD_NEWS['TEXT_LAST_CHANGED'] = 'Senaste ändring';
$MOD_NEWS['TEXT_AT'] = 'kl.';
$MOD_NEWS['TEXT_BACK'] = 'Tillbaka';
$MOD_NEWS['TEXT_COMMENTS'] = 'Kommentarer';
$MOD_NEWS['TEXT_COMMENT'] = 'kommentar';
$MOD_NEWS['TEXT_ADD_COMMENT'] = 'Kommentera';
$MOD_NEWS['TEXT_BY'] = 'Av';
$MOD_NEWS['PAGE_NOT_FOUND'] = 'Sidan kunde inte hittas';
$MOD_NEWS['NO_COMMENT_FOUND'] = 'No comment found';
$TEXT['UNKNOWN'] = 'Guest';
?> | marmotwb/2.8.x | wb/modules/news/languages/SE.php | PHP | gpl-2.0 | 1,238 |
/**
* @file
* Provides Ajax page updating via jQuery $.ajax.
*
* Ajax is a method of making a request via JavaScript while viewing an HTML
* page. The request returns an array of commands encoded in JSON, which is
* then executed to make any changes that are necessary to the page.
*
* Drupal uses this file to enhance form elements with `#ajax['url']` and
* `#ajax['wrapper']` properties. If set, this file will automatically be
* included to provide Ajax capabilities.
*/
(function ($, window, Drupal, drupalSettings) {
'use strict';
/**
* Attaches the Ajax behavior to each Ajax form element.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Initialize all {@link Drupal.Ajax} objects declared in
* `drupalSettings.ajax` or initialize {@link Drupal.Ajax} objects from
* DOM elements having the `use-ajax-submit` or `use-ajax` css class.
* @prop {Drupal~behaviorDetach} detach
* During `unload` remove all {@link Drupal.Ajax} objects related to
* the removed content.
*/
Drupal.behaviors.AJAX = {
attach: function (context, settings) {
function loadAjaxBehavior(base) {
var element_settings = settings.ajax[base];
if (typeof element_settings.selector === 'undefined') {
element_settings.selector = '#' + base;
}
$(element_settings.selector).once('drupal-ajax').each(function () {
element_settings.element = this;
element_settings.base = base;
Drupal.ajax(element_settings);
});
}
// Load all Ajax behaviors specified in the settings.
for (var base in settings.ajax) {
if (settings.ajax.hasOwnProperty(base)) {
loadAjaxBehavior(base);
}
}
// Bind Ajax behaviors to all items showing the class.
$('.use-ajax').once('ajax').each(function () {
var element_settings = {};
// Clicked links look better with the throbber than the progress bar.
element_settings.progress = {type: 'throbber'};
// For anchor tags, these will go to the target of the anchor rather
// than the usual location.
var href = $(this).attr('href');
if (href) {
element_settings.url = href;
element_settings.event = 'click';
}
element_settings.dialogType = $(this).data('dialog-type');
element_settings.dialog = $(this).data('dialog-options');
element_settings.base = $(this).attr('id');
element_settings.element = this;
Drupal.ajax(element_settings);
});
// This class means to submit the form to the action using Ajax.
$('.use-ajax-submit').once('ajax').each(function () {
var element_settings = {};
// Ajax submits specified in this manner automatically submit to the
// normal form action.
element_settings.url = $(this.form).attr('action');
// Form submit button clicks need to tell the form what was clicked so
// it gets passed in the POST request.
element_settings.setClick = true;
// Form buttons use the 'click' event rather than mousedown.
element_settings.event = 'click';
// Clicked form buttons look better with the throbber than the progress
// bar.
element_settings.progress = {type: 'throbber'};
element_settings.base = $(this).attr('id');
element_settings.element = this;
Drupal.ajax(element_settings);
});
},
detach: function (context, settings, trigger) {
if (trigger === 'unload') {
Drupal.ajax.expired().forEach(function (instance) {
// Set this to null and allow garbage collection to reclaim
// the memory.
Drupal.ajax.instances[instance.instanceIndex] = null;
});
}
}
};
/**
* Extends Error to provide handling for Errors in Ajax.
*
* @constructor
*
* @augments Error
*
* @param {XMLHttpRequest} xmlhttp
* XMLHttpRequest object used for the failed request.
* @param {string} uri
* The URI where the error occurred.
* @param {string} customMessage
* The custom message.
*/
Drupal.AjaxError = function (xmlhttp, uri, customMessage) {
var statusCode;
var statusText;
var pathText;
var responseText;
var readyStateText;
if (xmlhttp.status) {
statusCode = '\n' + Drupal.t('An AJAX HTTP error occurred.') + '\n' + Drupal.t('HTTP Result Code: !status', {'!status': xmlhttp.status});
}
else {
statusCode = '\n' + Drupal.t('An AJAX HTTP request terminated abnormally.');
}
statusCode += '\n' + Drupal.t('Debugging information follows.');
pathText = '\n' + Drupal.t('Path: !uri', {'!uri': uri});
statusText = '';
// In some cases, when statusCode === 0, xmlhttp.statusText may not be
// defined. Unfortunately, testing for it with typeof, etc, doesn't seem to
// catch that and the test causes an exception. So we need to catch the
// exception here.
try {
statusText = '\n' + Drupal.t('StatusText: !statusText', {'!statusText': $.trim(xmlhttp.statusText)});
}
catch (e) {
// Empty.
}
responseText = '';
// Again, we don't have a way to know for sure whether accessing
// xmlhttp.responseText is going to throw an exception. So we'll catch it.
try {
responseText = '\n' + Drupal.t('ResponseText: !responseText', {'!responseText': $.trim(xmlhttp.responseText)});
}
catch (e) {
// Empty.
}
// Make the responseText more readable by stripping HTML tags and newlines.
responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, '');
responseText = responseText.replace(/[\n]+\s+/g, '\n');
// We don't need readyState except for status == 0.
readyStateText = xmlhttp.status === 0 ? ('\n' + Drupal.t('ReadyState: !readyState', {'!readyState': xmlhttp.readyState})) : '';
customMessage = customMessage ? ('\n' + Drupal.t('CustomMessage: !customMessage', {'!customMessage': customMessage})) : '';
/**
* Formatted and translated error message.
*
* @type {string}
*/
this.message = statusCode + pathText + statusText + customMessage + responseText + readyStateText;
/**
* Used by some browsers to display a more accurate stack trace.
*
* @type {string}
*/
this.name = 'AjaxError';
};
Drupal.AjaxError.prototype = new Error();
Drupal.AjaxError.prototype.constructor = Drupal.AjaxError;
/**
* Provides Ajax page updating via jQuery $.ajax.
*
* This function is designed to improve developer experience by wrapping the
* initialization of {@link Drupal.Ajax} objects and storing all created
* objects in the {@link Drupal.ajax.instances} array.
*
* @example
* Drupal.behaviors.myCustomAJAXStuff = {
* attach: function (context, settings) {
*
* var ajaxSettings = {
* url: 'my/url/path',
* // If the old version of Drupal.ajax() needs to be used those
* // properties can be added
* base: 'myBase',
* element: $(context).find('.someElement')
* };
*
* var myAjaxObject = Drupal.ajax(ajaxSettings);
*
* // Declare a new Ajax command specifically for this Ajax object.
* myAjaxObject.commands.insert = function (ajax, response, status) {
* $('#my-wrapper').append(response.data);
* alert('New content was appended to #my-wrapper');
* };
*
* // This command will remove this Ajax object from the page.
* myAjaxObject.commands.destroyObject = function (ajax, response, status) {
* Drupal.ajax.instances[this.instanceIndex] = null;
* };
*
* // Programmatically trigger the Ajax request.
* myAjaxObject.execute();
* }
* };
*
* @param {object} settings
* The settings object passed to {@link Drupal.Ajax} constructor.
* @param {string} [settings.base]
* Base is passed to {@link Drupal.Ajax} constructor as the 'base'
* parameter.
* @param {HTMLElement} [settings.element]
* Element parameter of {@link Drupal.Ajax} constructor, element on which
* event listeners will be bound.
*
* @return {Drupal.Ajax}
* The created Ajax object.
*
* @see Drupal.AjaxCommands
*/
Drupal.ajax = function (settings) {
if (arguments.length !== 1) {
throw new Error('Drupal.ajax() function must be called with one configuration object only');
}
// Map those config keys to variables for the old Drupal.ajax function.
var base = settings.base || false;
var element = settings.element || false;
delete settings.base;
delete settings.element;
// By default do not display progress for ajax calls without an element.
if (!settings.progress && !element) {
settings.progress = false;
}
var ajax = new Drupal.Ajax(base, element, settings);
ajax.instanceIndex = Drupal.ajax.instances.length;
Drupal.ajax.instances.push(ajax);
return ajax;
};
/**
* Contains all created Ajax objects.
*
* @type {Array.<Drupal.Ajax|null>}
*/
Drupal.ajax.instances = [];
/**
* List all objects where the associated element is not in the DOM
*
* This method ignores {@link Drupal.Ajax} objects not bound to DOM elements
* when created with {@link Drupal.ajax}.
*
* @return {Array.<Drupal.Ajax>}
* The list of expired {@link Drupal.Ajax} objects.
*/
Drupal.ajax.expired = function () {
return Drupal.ajax.instances.filter(function (instance) {
return instance && instance.element !== false && !document.body.contains(instance.element);
});
};
/**
* Settings for an Ajax object.
*
* @typedef {object} Drupal.Ajax~element_settings
*
* @prop {string} url
* Target of the Ajax request.
* @prop {?string} [event]
* Event bound to settings.element which will trigger the Ajax request.
* @prop {bool} [keypress=true]
* Triggers a request on keypress events.
* @prop {?string} selector
* jQuery selector targeting the element to bind events to or used with
* {@link Drupal.AjaxCommands}.
* @prop {string} [effect='none']
* Name of the jQuery method to use for displaying new Ajax content.
* @prop {string|number} [speed='none']
* Speed with which to apply the effect.
* @prop {string} [method]
* Name of the jQuery method used to insert new content in the targeted
* element.
* @prop {object} [progress]
* Settings for the display of a user-friendly loader.
* @prop {string} [progress.type='throbber']
* Type of progress element, core provides `'bar'`, `'throbber'` and
* `'fullscreen'`.
* @prop {string} [progress.message=Drupal.t('Please wait...')]
* Custom message to be used with the bar indicator.
* @prop {object} [submit]
* Extra data to be sent with the Ajax request.
* @prop {bool} [submit.js=true]
* Allows the PHP side to know this comes from an Ajax request.
* @prop {object} [dialog]
* Options for {@link Drupal.dialog}.
* @prop {string} [dialogType]
* One of `'modal'` or `'dialog'`.
* @prop {string} [prevent]
* List of events on which to stop default action and stop propagation.
*/
/**
* Ajax constructor.
*
* The Ajax request returns an array of commands encoded in JSON, which is
* then executed to make any changes that are necessary to the page.
*
* Drupal uses this file to enhance form elements with `#ajax['url']` and
* `#ajax['wrapper']` properties. If set, this file will automatically be
* included to provide Ajax capabilities.
*
* @constructor
*
* @param {string} [base]
* Base parameter of {@link Drupal.Ajax} constructor
* @param {HTMLElement} [element]
* Element parameter of {@link Drupal.Ajax} constructor, element on which
* event listeners will be bound.
* @param {Drupal.Ajax~element_settings} element_settings
* Settings for this Ajax object.
*/
Drupal.Ajax = function (base, element, element_settings) {
var defaults = {
event: element ? 'mousedown' : null,
keypress: true,
selector: base ? '#' + base : null,
effect: 'none',
speed: 'none',
method: 'replaceWith',
progress: {
type: 'throbber',
message: Drupal.t('Please wait...')
},
submit: {
js: true
}
};
$.extend(this, defaults, element_settings);
/**
* @type {Drupal.AjaxCommands}
*/
this.commands = new Drupal.AjaxCommands();
/**
* @type {bool|number}
*/
this.instanceIndex = false;
// @todo Remove this after refactoring the PHP code to:
// - Call this 'selector'.
// - Include the '#' for ID-based selectors.
// - Support non-ID-based selectors.
if (this.wrapper) {
/**
* @type {string}
*/
this.wrapper = '#' + this.wrapper;
}
/**
* @type {HTMLElement}
*/
this.element = element;
/**
* @type {Drupal.Ajax~element_settings}
*/
this.element_settings = element_settings;
// If there isn't a form, jQuery.ajax() will be used instead, allowing us to
// bind Ajax to links as well.
if (this.element && this.element.form) {
/**
* @type {jQuery}
*/
this.$form = $(this.element.form);
}
// If no Ajax callback URL was given, use the link href or form action.
if (!this.url) {
var $element = $(this.element);
if ($element.is('a')) {
this.url = $element.attr('href');
}
else if (this.element && element.form) {
this.url = this.$form.attr('action');
}
}
// Replacing 'nojs' with 'ajax' in the URL allows for an easy method to let
// the server detect when it needs to degrade gracefully.
// There are four scenarios to check for:
// 1. /nojs/
// 2. /nojs$ - The end of a URL string.
// 3. /nojs? - Followed by a query (e.g. path/nojs?destination=foobar).
// 4. /nojs# - Followed by a fragment (e.g.: path/nojs#myfragment).
var originalUrl = this.url;
/**
* Processed Ajax URL.
*
* @type {string}
*/
this.url = this.url.replace(/\/nojs(\/|$|\?|#)/g, '/ajax$1');
// If the 'nojs' version of the URL is trusted, also trust the 'ajax'
// version.
if (drupalSettings.ajaxTrustedUrl[originalUrl]) {
drupalSettings.ajaxTrustedUrl[this.url] = true;
}
// Set the options for the ajaxSubmit function.
// The 'this' variable will not persist inside of the options object.
var ajax = this;
/**
* Options for the jQuery.ajax function.
*
* @name Drupal.Ajax#options
*
* @type {object}
*
* @prop {string} url
* Ajax URL to be called.
* @prop {object} data
* Ajax payload.
* @prop {function} beforeSerialize
* Implement jQuery beforeSerialize function to call
* {@link Drupal.Ajax#beforeSerialize}.
* @prop {function} beforeSubmit
* Implement jQuery beforeSubmit function to call
* {@link Drupal.Ajax#beforeSubmit}.
* @prop {function} beforeSend
* Implement jQuery beforeSend function to call
* {@link Drupal.Ajax#beforeSend}.
* @prop {function} success
* Implement jQuery success function to call
* {@link Drupal.Ajax#success}.
* @prop {function} complete
* Implement jQuery success function to clean up ajax state and trigger an
* error if needed.
* @prop {string} dataType='json'
* Type of the response expected.
* @prop {string} type='POST'
* HTTP method to use for the Ajax request.
*/
ajax.options = {
url: ajax.url,
data: ajax.submit,
beforeSerialize: function (element_settings, options) {
return ajax.beforeSerialize(element_settings, options);
},
beforeSubmit: function (form_values, element_settings, options) {
ajax.ajaxing = true;
return ajax.beforeSubmit(form_values, element_settings, options);
},
beforeSend: function (xmlhttprequest, options) {
ajax.ajaxing = true;
return ajax.beforeSend(xmlhttprequest, options);
},
success: function (response, status, xmlhttprequest) {
// Sanity check for browser support (object expected).
// When using iFrame uploads, responses must be returned as a string.
if (typeof response === 'string') {
response = $.parseJSON(response);
}
// Prior to invoking the response's commands, verify that they can be
// trusted by checking for a response header. See
// \Drupal\Core\EventSubscriber\AjaxResponseSubscriber for details.
// - Empty responses are harmless so can bypass verification. This
// avoids an alert message for server-generated no-op responses that
// skip Ajax rendering.
// - Ajax objects with trusted URLs (e.g., ones defined server-side via
// #ajax) can bypass header verification. This is especially useful
// for Ajax with multipart forms. Because IFRAME transport is used,
// the response headers cannot be accessed for verification.
if (response !== null && !drupalSettings.ajaxTrustedUrl[ajax.url]) {
if (xmlhttprequest.getResponseHeader('X-Drupal-Ajax-Token') !== '1') {
var customMessage = Drupal.t('The response failed verification so will not be processed.');
return ajax.error(xmlhttprequest, ajax.url, customMessage);
}
}
return ajax.success(response, status);
},
complete: function (xmlhttprequest, status) {
ajax.ajaxing = false;
if (status === 'error' || status === 'parsererror') {
return ajax.error(xmlhttprequest, ajax.url);
}
},
dataType: 'json',
type: 'POST'
};
if (element_settings.dialog) {
ajax.options.data.dialogOptions = element_settings.dialog;
}
// Ensure that we have a valid URL by adding ? when no query parameter is
// yet available, otherwise append using &.
if (ajax.options.url.indexOf('?') === -1) {
ajax.options.url += '?';
}
else {
ajax.options.url += '&';
}
ajax.options.url += Drupal.ajax.WRAPPER_FORMAT + '=drupal_' + (element_settings.dialogType || 'ajax');
// Bind the ajaxSubmit function to the element event.
$(ajax.element).on(element_settings.event, function (event) {
if (!drupalSettings.ajaxTrustedUrl[ajax.url] && !Drupal.url.isLocal(ajax.url)) {
throw new Error(Drupal.t('The callback URL is not local and not trusted: !url', {'!url': ajax.url}));
}
return ajax.eventResponse(this, event);
});
// If necessary, enable keyboard submission so that Ajax behaviors
// can be triggered through keyboard input as well as e.g. a mousedown
// action.
if (element_settings.keypress) {
$(ajax.element).on('keypress', function (event) {
return ajax.keypressResponse(this, event);
});
}
// If necessary, prevent the browser default action of an additional event.
// For example, prevent the browser default action of a click, even if the
// Ajax behavior binds to mousedown.
if (element_settings.prevent) {
$(ajax.element).on(element_settings.prevent, false);
}
};
/**
* URL query attribute to indicate the wrapper used to render a request.
*
* The wrapper format determines how the HTML is wrapped, for example in a
* modal dialog.
*
* @const {string}
*
* @default
*/
Drupal.ajax.WRAPPER_FORMAT = '_wrapper_format';
/**
* Request parameter to indicate that a request is a Drupal Ajax request.
*
* @const {string}
*
* @default
*/
Drupal.Ajax.AJAX_REQUEST_PARAMETER = '_drupal_ajax';
/**
* Execute the ajax request.
*
* Allows developers to execute an Ajax request manually without specifying
* an event to respond to.
*
* @return {object}
* Returns the jQuery.Deferred object underlying the Ajax request. If
* pre-serialization fails, the Deferred will be returned in the rejected
* state.
*/
Drupal.Ajax.prototype.execute = function () {
// Do not perform another ajax command if one is already in progress.
if (this.ajaxing) {
return;
}
try {
this.beforeSerialize(this.element, this.options);
// Return the jqXHR so that external code can hook into the Deferred API.
return $.ajax(this.options);
}
catch (e) {
// Unset the ajax.ajaxing flag here because it won't be unset during
// the complete response.
this.ajaxing = false;
window.alert('An error occurred while attempting to process ' + this.options.url + ': ' + e.message);
// For consistency, return a rejected Deferred (i.e., jqXHR's superclass)
// so that calling code can take appropriate action.
return $.Deferred().reject();
}
};
/**
* Handle a key press.
*
* The Ajax object will, if instructed, bind to a key press response. This
* will test to see if the key press is valid to trigger this event and
* if it is, trigger it for us and prevent other keypresses from triggering.
* In this case we're handling RETURN and SPACEBAR keypresses (event codes 13
* and 32. RETURN is often used to submit a form when in a textfield, and
* SPACE is often used to activate an element without submitting.
*
* @param {HTMLElement} element
* Element the event was triggered on.
* @param {jQuery.Event} event
* Triggered event.
*/
Drupal.Ajax.prototype.keypressResponse = function (element, event) {
// Create a synonym for this to reduce code confusion.
var ajax = this;
// Detect enter key and space bar and allow the standard response for them,
// except for form elements of type 'text', 'tel', 'number' and 'textarea',
// where the spacebar activation causes inappropriate activation if
// #ajax['keypress'] is TRUE. On a text-type widget a space should always
// be a space.
if (event.which === 13 || (event.which === 32 && element.type !== 'text' &&
element.type !== 'textarea' && element.type !== 'tel' && element.type !== 'number')) {
event.preventDefault();
event.stopPropagation();
$(ajax.element_settings.element).trigger(ajax.element_settings.event);
}
};
/**
* Handle an event that triggers an Ajax response.
*
* When an event that triggers an Ajax response happens, this method will
* perform the actual Ajax call. It is bound to the event using
* bind() in the constructor, and it uses the options specified on the
* Ajax object.
*
* @param {HTMLElement} element
* Element the event was triggered on.
* @param {jQuery.Event} event
* Triggered event.
*/
Drupal.Ajax.prototype.eventResponse = function (element, event) {
event.preventDefault();
event.stopPropagation();
// Create a synonym for this to reduce code confusion.
var ajax = this;
// Do not perform another Ajax command if one is already in progress.
if (ajax.ajaxing) {
return;
}
try {
if (ajax.$form) {
// If setClick is set, we must set this to ensure that the button's
// value is passed.
if (ajax.setClick) {
// Mark the clicked button. 'form.clk' is a special variable for
// ajaxSubmit that tells the system which element got clicked to
// trigger the submit. Without it there would be no 'op' or
// equivalent.
element.form.clk = element;
}
ajax.$form.ajaxSubmit(ajax.options);
}
else {
ajax.beforeSerialize(ajax.element, ajax.options);
$.ajax(ajax.options);
}
}
catch (e) {
// Unset the ajax.ajaxing flag here because it won't be unset during
// the complete response.
ajax.ajaxing = false;
window.alert('An error occurred while attempting to process ' + ajax.options.url + ': ' + e.message);
}
};
/**
* Handler for the form serialization.
*
* Runs before the beforeSend() handler (see below), and unlike that one, runs
* before field data is collected.
*
* @param {object} [element]
* Ajax object's `element_settings`.
* @param {object} options
* jQuery.ajax options.
*/
Drupal.Ajax.prototype.beforeSerialize = function (element, options) {
// Allow detaching behaviors to update field values before collecting them.
// This is only needed when field values are added to the POST data, so only
// when there is a form such that this.$form.ajaxSubmit() is used instead of
// $.ajax(). When there is no form and $.ajax() is used, beforeSerialize()
// isn't called, but don't rely on that: explicitly check this.$form.
if (this.$form) {
var settings = this.settings || drupalSettings;
Drupal.detachBehaviors(this.$form.get(0), settings, 'serialize');
}
// Inform Drupal that this is an AJAX request.
options.data[Drupal.Ajax.AJAX_REQUEST_PARAMETER] = 1;
// Allow Drupal to return new JavaScript and CSS files to load without
// returning the ones already loaded.
// @see \Drupal\Core\Theme\AjaxBasePageNegotiator
// @see \Drupal\Core\Asset\LibraryDependencyResolverInterface::getMinimalRepresentativeSubset()
// @see system_js_settings_alter()
var pageState = drupalSettings.ajaxPageState;
options.data['ajax_page_state[theme]'] = pageState.theme;
options.data['ajax_page_state[theme_token]'] = pageState.theme_token;
options.data['ajax_page_state[libraries]'] = pageState.libraries;
};
/**
* Modify form values prior to form submission.
*
* @param {Array.<object>} form_values
* Processed form values.
* @param {jQuery} element
* The form node as a jQuery object.
* @param {object} options
* jQuery.ajax options.
*/
Drupal.Ajax.prototype.beforeSubmit = function (form_values, element, options) {
// This function is left empty to make it simple to override for modules
// that wish to add functionality here.
};
/**
* Prepare the Ajax request before it is sent.
*
* @param {XMLHttpRequest} xmlhttprequest
* Native Ajax object.
* @param {object} options
* jQuery.ajax options.
*/
Drupal.Ajax.prototype.beforeSend = function (xmlhttprequest, options) {
// For forms without file inputs, the jQuery Form plugin serializes the
// form values, and then calls jQuery's $.ajax() function, which invokes
// this handler. In this circumstance, options.extraData is never used. For
// forms with file inputs, the jQuery Form plugin uses the browser's normal
// form submission mechanism, but captures the response in a hidden IFRAME.
// In this circumstance, it calls this handler first, and then appends
// hidden fields to the form to submit the values in options.extraData.
// There is no simple way to know which submission mechanism will be used,
// so we add to extraData regardless, and allow it to be ignored in the
// former case.
if (this.$form) {
options.extraData = options.extraData || {};
// Let the server know when the IFRAME submission mechanism is used. The
// server can use this information to wrap the JSON response in a
// TEXTAREA, as per http://jquery.malsup.com/form/#file-upload.
options.extraData.ajax_iframe_upload = '1';
// The triggering element is about to be disabled (see below), but if it
// contains a value (e.g., a checkbox, textfield, select, etc.), ensure
// that value is included in the submission. As per above, submissions
// that use $.ajax() are already serialized prior to the element being
// disabled, so this is only needed for IFRAME submissions.
var v = $.fieldValue(this.element);
if (v !== null) {
options.extraData[this.element.name] = v;
}
}
// Disable the element that received the change to prevent user interface
// interaction while the Ajax request is in progress. ajax.ajaxing prevents
// the element from triggering a new request, but does not prevent the user
// from changing its value.
$(this.element).prop('disabled', true);
if (!this.progress || !this.progress.type) {
return;
}
// Insert progress indicator.
var progressIndicatorMethod = 'setProgressIndicator' + this.progress.type.slice(0, 1).toUpperCase() + this.progress.type.slice(1).toLowerCase();
if (progressIndicatorMethod in this && typeof this[progressIndicatorMethod] === 'function') {
this[progressIndicatorMethod].call(this);
}
};
/**
* Sets the progress bar progress indicator.
*/
Drupal.Ajax.prototype.setProgressIndicatorBar = function () {
var progressBar = new Drupal.ProgressBar('ajax-progress-' + this.element.id, $.noop, this.progress.method, $.noop);
if (this.progress.message) {
progressBar.setProgress(-1, this.progress.message);
}
if (this.progress.url) {
progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500);
}
this.progress.element = $(progressBar.element).addClass('ajax-progress ajax-progress-bar');
this.progress.object = progressBar;
$(this.element).after(this.progress.element);
};
/**
* Sets the throbber progress indicator.
*/
Drupal.Ajax.prototype.setProgressIndicatorThrobber = function () {
this.progress.element = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber"> </div></div>');
if (this.progress.message) {
this.progress.element.find('.throbber').after('<div class="message">' + this.progress.message + '</div>');
}
$(this.element).after(this.progress.element);
};
/**
* Sets the fullscreen progress indicator.
*/
Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function () {
this.progress.element = $('<div class="ajax-progress ajax-progress-fullscreen"> </div>');
$('body').after(this.progress.element);
};
/**
* Handler for the form redirection completion.
*
* @param {Array.<Drupal.AjaxCommands~commandDefinition>} response
* Drupal Ajax response.
* @param {number} status
* XMLHttpRequest status.
*/
Drupal.Ajax.prototype.success = function (response, status) {
// Remove the progress element.
if (this.progress.element) {
$(this.progress.element).remove();
}
if (this.progress.object) {
this.progress.object.stopMonitoring();
}
$(this.element).prop('disabled', false);
// Save element's ancestors tree so if the element is removed from the dom
// we can try to refocus one of its parents. Using addBack reverse the
// result array, meaning that index 0 is the highest parent in the hierarchy
// in this situation it is usually a <form> element.
var elementParents = $(this.element).parents('[data-drupal-selector]').addBack().toArray();
// Track if any command is altering the focus so we can avoid changing the
// focus set by the Ajax command.
var focusChanged = false;
for (var i in response) {
if (response.hasOwnProperty(i) && response[i].command && this.commands[response[i].command]) {
this.commands[response[i].command](this, response[i], status);
if (response[i].command === 'invoke' && response[i].method === 'focus') {
focusChanged = true;
}
}
}
// If the focus hasn't be changed by the ajax commands, try to refocus the
// triggering element or one of its parents if that element does not exist
// anymore.
if (!focusChanged && this.element && !$(this.element).data('disable-refocus')) {
var target = false;
for (var n = elementParents.length - 1; !target && n > 0; n--) {
target = document.querySelector('[data-drupal-selector="' + elementParents[n].getAttribute('data-drupal-selector') + '"]');
}
if (target) {
$(target).trigger('focus');
}
}
// Reattach behaviors, if they were detached in beforeSerialize(). The
// attachBehaviors() called on the new content from processing the response
// commands is not sufficient, because behaviors from the entire form need
// to be reattached.
if (this.$form) {
var settings = this.settings || drupalSettings;
Drupal.attachBehaviors(this.$form.get(0), settings);
}
// Remove any response-specific settings so they don't get used on the next
// call by mistake.
this.settings = null;
};
/**
* Build an effect object to apply an effect when adding new HTML.
*
* @param {object} response
* Drupal Ajax response.
* @param {string} [response.effect]
* Override the default value of {@link Drupal.Ajax#element_settings}.
* @param {string|number} [response.speed]
* Override the default value of {@link Drupal.Ajax#element_settings}.
*
* @return {object}
* Returns an object with `showEffect`, `hideEffect` and `showSpeed`
* properties.
*/
Drupal.Ajax.prototype.getEffect = function (response) {
var type = response.effect || this.effect;
var speed = response.speed || this.speed;
var effect = {};
if (type === 'none') {
effect.showEffect = 'show';
effect.hideEffect = 'hide';
effect.showSpeed = '';
}
else if (type === 'fade') {
effect.showEffect = 'fadeIn';
effect.hideEffect = 'fadeOut';
effect.showSpeed = speed;
}
else {
effect.showEffect = type + 'Toggle';
effect.hideEffect = type + 'Toggle';
effect.showSpeed = speed;
}
return effect;
};
/**
* Handler for the form redirection error.
*
* @param {object} xmlhttprequest
* Native XMLHttpRequest object.
* @param {string} uri
* Ajax Request URI.
* @param {string} [customMessage]
* Extra message to print with the Ajax error.
*/
Drupal.Ajax.prototype.error = function (xmlhttprequest, uri, customMessage) {
// Remove the progress element.
if (this.progress.element) {
$(this.progress.element).remove();
}
if (this.progress.object) {
this.progress.object.stopMonitoring();
}
// Undo hide.
$(this.wrapper).show();
// Re-enable the element.
$(this.element).prop('disabled', false);
// Reattach behaviors, if they were detached in beforeSerialize().
if (this.$form) {
var settings = this.settings || drupalSettings;
Drupal.attachBehaviors(this.$form.get(0), settings);
}
throw new Drupal.AjaxError(xmlhttprequest, uri, customMessage);
};
/**
* @typedef {object} Drupal.AjaxCommands~commandDefinition
*
* @prop {string} command
* @prop {string} [method]
* @prop {string} [selector]
* @prop {string} [data]
* @prop {object} [settings]
* @prop {bool} [asterisk]
* @prop {string} [text]
* @prop {string} [title]
* @prop {string} [url]
* @prop {object} [argument]
* @prop {string} [name]
* @prop {string} [value]
* @prop {string} [old]
* @prop {string} [new]
* @prop {bool} [merge]
* @prop {Array} [args]
*
* @see Drupal.AjaxCommands
*/
/**
* Provide a series of commands that the client will perform.
*
* @constructor
*/
Drupal.AjaxCommands = function () {};
Drupal.AjaxCommands.prototype = {
/**
* Command to insert new content into the DOM.
*
* @param {Drupal.Ajax} ajax
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.data
* The data to use with the jQuery method.
* @param {string} [response.method]
* The jQuery DOM manipulation method to be used.
* @param {string} [response.selector]
* A optional jQuery selector string.
* @param {object} [response.settings]
* An optional array of settings that will be used.
* @param {number} [status]
* The XMLHttpRequest status.
*/
insert: function (ajax, response, status) {
// Get information from the response. If it is not there, default to
// our presets.
var $wrapper = response.selector ? $(response.selector) : $(ajax.wrapper);
var method = response.method || ajax.method;
var effect = ajax.getEffect(response);
var settings;
// We don't know what response.data contains: it might be a string of text
// without HTML, so don't rely on jQuery correctly interpreting
// $(response.data) as new HTML rather than a CSS selector. Also, if
// response.data contains top-level text nodes, they get lost with either
// $(response.data) or $('<div></div>').replaceWith(response.data).
var $new_content_wrapped = $('<div></div>').html(response.data);
var $new_content = $new_content_wrapped.contents();
// For legacy reasons, the effects processing code assumes that
// $new_content consists of a single top-level element. Also, it has not
// been sufficiently tested whether attachBehaviors() can be successfully
// called with a context object that includes top-level text nodes.
// However, to give developers full control of the HTML appearing in the
// page, and to enable Ajax content to be inserted in places where <div>
// elements are not allowed (e.g., within <table>, <tr>, and <span>
// parents), we check if the new content satisfies the requirement
// of a single top-level element, and only use the container <div> created
// above when it doesn't. For more information, please see
// https://www.drupal.org/node/736066.
if ($new_content.length !== 1 || $new_content.get(0).nodeType !== 1) {
$new_content = $new_content_wrapped;
}
// If removing content from the wrapper, detach behaviors first.
switch (method) {
case 'html':
case 'replaceWith':
case 'replaceAll':
case 'empty':
case 'remove':
settings = response.settings || ajax.settings || drupalSettings;
Drupal.detachBehaviors($wrapper.get(0), settings);
}
// Add the new content to the page.
$wrapper[method]($new_content);
// Immediately hide the new content if we're using any effects.
if (effect.showEffect !== 'show') {
$new_content.hide();
}
// Determine which effect to use and what content will receive the
// effect, then show the new content.
if ($new_content.find('.ajax-new-content').length > 0) {
$new_content.find('.ajax-new-content').hide();
$new_content.show();
$new_content.find('.ajax-new-content')[effect.showEffect](effect.showSpeed);
}
else if (effect.showEffect !== 'show') {
$new_content[effect.showEffect](effect.showSpeed);
}
// Attach all JavaScript behaviors to the new content, if it was
// successfully added to the page, this if statement allows
// `#ajax['wrapper']` to be optional.
if ($new_content.parents('html').length > 0) {
// Apply any settings from the returned JSON if available.
settings = response.settings || ajax.settings || drupalSettings;
Drupal.attachBehaviors($new_content.get(0), settings);
}
},
/**
* Command to remove a chunk from the page.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.selector
* A jQuery selector string.
* @param {object} [response.settings]
* An optional array of settings that will be used.
* @param {number} [status]
* The XMLHttpRequest status.
*/
remove: function (ajax, response, status) {
var settings = response.settings || ajax.settings || drupalSettings;
$(response.selector).each(function () {
Drupal.detachBehaviors(this, settings);
})
.remove();
},
/**
* Command to mark a chunk changed.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The JSON response object from the Ajax request.
* @param {string} response.selector
* A jQuery selector string.
* @param {bool} [response.asterisk]
* An optional CSS selector. If specified, an asterisk will be
* appended to the HTML inside the provided selector.
* @param {number} [status]
* The request status.
*/
changed: function (ajax, response, status) {
var $element = $(response.selector);
if (!$element.hasClass('ajax-changed')) {
$element.addClass('ajax-changed');
if (response.asterisk) {
$element.find(response.asterisk).append(' <abbr class="ajax-changed" title="' + Drupal.t('Changed') + '">*</abbr> ');
}
}
},
/**
* Command to provide an alert.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The JSON response from the Ajax request.
* @param {string} response.text
* The text that will be displayed in an alert dialog.
* @param {number} [status]
* The XMLHttpRequest status.
*/
alert: function (ajax, response, status) {
window.alert(response.text, response.title);
},
/**
* Command to set the window.location, redirecting the browser.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.url
* The URL to redirect to.
* @param {number} [status]
* The XMLHttpRequest status.
*/
redirect: function (ajax, response, status) {
window.location = response.url;
},
/**
* Command to provide the jQuery css() function.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.selector
* A jQuery selector string.
* @param {object} response.argument
* An array of key/value pairs to set in the CSS for the selector.
* @param {number} [status]
* The XMLHttpRequest status.
*/
css: function (ajax, response, status) {
$(response.selector).css(response.argument);
},
/**
* Command to set the settings used for other commands in this response.
*
* This method will also remove expired `drupalSettings.ajax` settings.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {bool} response.merge
* Determines whether the additional settings should be merged to the
* global settings.
* @param {object} response.settings
* Contains additional settings to add to the global settings.
* @param {number} [status]
* The XMLHttpRequest status.
*/
settings: function (ajax, response, status) {
var ajaxSettings = drupalSettings.ajax;
// Clean up drupalSettings.ajax.
if (ajaxSettings) {
Drupal.ajax.expired().forEach(function (instance) {
// If the Ajax object has been created through drupalSettings.ajax
// it will have a selector. When there is no selector the object
// has been initialized with a special class name picked up by the
// Ajax behavior.
if (instance.selector) {
var selector = instance.selector.replace('#', '');
if (selector in ajaxSettings) {
delete ajaxSettings[selector];
}
}
});
}
if (response.merge) {
$.extend(true, drupalSettings, response.settings);
}
else {
ajax.settings = response.settings;
}
},
/**
* Command to attach data using jQuery's data API.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.name
* The name or key (in the key value pair) of the data attached to this
* selector.
* @param {string} response.selector
* A jQuery selector string.
* @param {string|object} response.value
* The value of to be attached.
* @param {number} [status]
* The XMLHttpRequest status.
*/
data: function (ajax, response, status) {
$(response.selector).data(response.name, response.value);
},
/**
* Command to apply a jQuery method.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {Array} response.args
* An array of arguments to the jQuery method, if any.
* @param {string} response.method
* The jQuery method to invoke.
* @param {string} response.selector
* A jQuery selector string.
* @param {number} [status]
* The XMLHttpRequest status.
*/
invoke: function (ajax, response, status) {
var $element = $(response.selector);
$element[response.method].apply($element, response.args);
},
/**
* Command to restripe a table.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.selector
* A jQuery selector string.
* @param {number} [status]
* The XMLHttpRequest status.
*/
restripe: function (ajax, response, status) {
// :even and :odd are reversed because jQuery counts from 0 and
// we count from 1, so we're out of sync.
// Match immediate children of the parent element to allow nesting.
$(response.selector).find('> tbody > tr:visible, > tr:visible')
.removeClass('odd even')
.filter(':even').addClass('odd').end()
.filter(':odd').addClass('even');
},
/**
* Command to update a form's build ID.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.old
* The old form build ID.
* @param {string} response.new
* The new form build ID.
* @param {number} [status]
* The XMLHttpRequest status.
*/
update_build_id: function (ajax, response, status) {
$('input[name="form_build_id"][value="' + response.old + '"]').val(response.new);
},
/**
* Command to add css.
*
* Uses the proprietary addImport method if available as browsers which
* support that method ignore @import statements in dynamically added
* stylesheets.
*
* @param {Drupal.Ajax} [ajax]
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* The response from the Ajax request.
* @param {string} response.data
* A string that contains the styles to be added.
* @param {number} [status]
* The XMLHttpRequest status.
*/
add_css: function (ajax, response, status) {
// Add the styles in the normal way.
$('head').prepend(response.data);
// Add imports in the styles using the addImport method if available.
var match;
var importMatch = /^@import url\("(.*)"\);$/igm;
if (document.styleSheets[0].addImport && importMatch.test(response.data)) {
importMatch.lastIndex = 0;
do {
match = importMatch.exec(response.data);
document.styleSheets[0].addImport(match[1]);
} while (match);
}
}
};
})(jQuery, window, Drupal, drupalSettings);
;
/**
* @file
* Adds an HTML element and method to trigger audio UAs to read system messages.
*
* Use {@link Drupal.announce} to indicate to screen reader users that an
* element on the page has changed state. For instance, if clicking a link
* loads 10 more items into a list, one might announce the change like this.
*
* @example
* $('#search-list')
* .on('itemInsert', function (event, data) {
* // Insert the new items.
* $(data.container.el).append(data.items.el);
* // Announce the change to the page contents.
* Drupal.announce(Drupal.t('@count items added to @container',
* {'@count': data.items.length, '@container': data.container.title}
* ));
* });
*/
(function (Drupal, debounce) {
'use strict';
var liveElement;
var announcements = [];
/**
* Builds a div element with the aria-live attribute and add it to the DOM.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the behavior for drupalAnnouce.
*/
Drupal.behaviors.drupalAnnounce = {
attach: function (context) {
// Create only one aria-live element.
if (!liveElement) {
liveElement = document.createElement('div');
liveElement.id = 'drupal-live-announce';
liveElement.className = 'visually-hidden';
liveElement.setAttribute('aria-live', 'polite');
liveElement.setAttribute('aria-busy', 'false');
document.body.appendChild(liveElement);
}
}
};
/**
* Concatenates announcements to a single string; appends to the live region.
*/
function announce() {
var text = [];
var priority = 'polite';
var announcement;
// Create an array of announcement strings to be joined and appended to the
// aria live region.
var il = announcements.length;
for (var i = 0; i < il; i++) {
announcement = announcements.pop();
text.unshift(announcement.text);
// If any of the announcements has a priority of assertive then the group
// of joined announcements will have this priority.
if (announcement.priority === 'assertive') {
priority = 'assertive';
}
}
if (text.length) {
// Clear the liveElement so that repeated strings will be read.
liveElement.innerHTML = '';
// Set the busy state to true until the node changes are complete.
liveElement.setAttribute('aria-busy', 'true');
// Set the priority to assertive, or default to polite.
liveElement.setAttribute('aria-live', priority);
// Print the text to the live region. Text should be run through
// Drupal.t() before being passed to Drupal.announce().
liveElement.innerHTML = text.join('\n');
// The live text area is updated. Allow the AT to announce the text.
liveElement.setAttribute('aria-busy', 'false');
}
}
/**
* Triggers audio UAs to read the supplied text.
*
* The aria-live region will only read the text that currently populates its
* text node. Replacing text quickly in rapid calls to announce results in
* only the text from the most recent call to {@link Drupal.announce} being
* read. By wrapping the call to announce in a debounce function, we allow for
* time for multiple calls to {@link Drupal.announce} to queue up their
* messages. These messages are then joined and append to the aria-live region
* as one text node.
*
* @param {string} text
* A string to be read by the UA.
* @param {string} [priority='polite']
* A string to indicate the priority of the message. Can be either
* 'polite' or 'assertive'.
*
* @return {function}
* The return of the call to debounce.
*
* @see http://www.w3.org/WAI/PF/aria-practices/#liveprops
*/
Drupal.announce = function (text, priority) {
// Save the text and priority into a closure variable. Multiple simultaneous
// announcements will be concatenated and read in sequence.
announcements.push({
text: text,
priority: priority
});
// Immediately invoke the function that debounce returns. 200 ms is right at
// the cusp where humans notice a pause, so we will wait
// at most this much time before the set of queued announcements is read.
return (debounce(announce, 200)());
};
}(Drupal, Drupal.debounce));
;
(function(){if(window.matchMedia&&window.matchMedia("all").addListener){return false}var e=window.matchMedia,i=e("only all").matches,n=false,t=0,a=[],r=function(i){clearTimeout(t);t=setTimeout(function(){for(var i=0,n=a.length;i<n;i++){var t=a[i].mql,r=a[i].listeners||[],o=e(t.media).matches;if(o!==t.matches){t.matches=o;for(var s=0,l=r.length;s<l;s++){r[s].call(window,t)}}}},30)};window.matchMedia=function(t){var o=e(t),s=[],l=0;o.addListener=function(e){if(!i){return}if(!n){n=true;window.addEventListener("resize",r,true)}if(l===0){l=a.push({mql:o,listeners:s})}s.push(e)};o.removeListener=function(e){for(var i=0,n=s.length;i<n;i++){if(s[i]===e){s.splice(i,1)}}};return o}})();
;
/**
* @file
* Manages elements that can offset the size of the viewport.
*
* Measures and reports viewport offset dimensions from elements like the
* toolbar that can potentially displace the positioning of other elements.
*/
/**
* @typedef {object} Drupal~displaceOffset
*
* @prop {number} top
* @prop {number} left
* @prop {number} right
* @prop {number} bottom
*/
/**
* Triggers when layout of the page changes.
*
* This is used to position fixed element on the page during page resize and
* Toolbar toggling.
*
* @event drupalViewportOffsetChange
*/
(function ($, Drupal, debounce) {
'use strict';
/**
* @name Drupal.displace.offsets
*
* @type {Drupal~displaceOffset}
*/
var offsets = {
top: 0,
right: 0,
bottom: 0,
left: 0
};
/**
* Registers a resize handler on the window.
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.drupalDisplace = {
attach: function () {
// Mark this behavior as processed on the first pass.
if (this.displaceProcessed) {
return;
}
this.displaceProcessed = true;
$(window).on('resize.drupalDisplace', debounce(displace, 200));
}
};
/**
* Informs listeners of the current offset dimensions.
*
* @function Drupal.displace
*
* @prop {Drupal~displaceOffset} offsets
*
* @param {bool} [broadcast]
* When true or undefined, causes the recalculated offsets values to be
* broadcast to listeners.
*
* @return {Drupal~displaceOffset}
* An object whose keys are the for sides an element -- top, right, bottom
* and left. The value of each key is the viewport displacement distance for
* that edge.
*
* @fires event:drupalViewportOffsetChange
*/
function displace(broadcast) {
offsets = Drupal.displace.offsets = calculateOffsets();
if (typeof broadcast === 'undefined' || broadcast) {
$(document).trigger('drupalViewportOffsetChange', offsets);
}
return offsets;
}
/**
* Determines the viewport offsets.
*
* @return {Drupal~displaceOffset}
* An object whose keys are the for sides an element -- top, right, bottom
* and left. The value of each key is the viewport displacement distance for
* that edge.
*/
function calculateOffsets() {
return {
top: calculateOffset('top'),
right: calculateOffset('right'),
bottom: calculateOffset('bottom'),
left: calculateOffset('left')
};
}
/**
* Gets a specific edge's offset.
*
* Any element with the attribute data-offset-{edge} e.g. data-offset-top will
* be considered in the viewport offset calculations. If the attribute has a
* numeric value, that value will be used. If no value is provided, one will
* be calculated using the element's dimensions and placement.
*
* @function Drupal.displace.calculateOffset
*
* @param {string} edge
* The name of the edge to calculate. Can be 'top', 'right',
* 'bottom' or 'left'.
*
* @return {number}
* The viewport displacement distance for the requested edge.
*/
function calculateOffset(edge) {
var edgeOffset = 0;
var displacingElements = document.querySelectorAll('[data-offset-' + edge + ']');
var n = displacingElements.length;
for (var i = 0; i < n; i++) {
var el = displacingElements[i];
// If the element is not visible, do consider its dimensions.
if (el.style.display === 'none') {
continue;
}
// If the offset data attribute contains a displacing value, use it.
var displacement = parseInt(el.getAttribute('data-offset-' + edge), 10);
// If the element's offset data attribute exits
// but is not a valid number then get the displacement
// dimensions directly from the element.
if (isNaN(displacement)) {
displacement = getRawOffset(el, edge);
}
// If the displacement value is larger than the current value for this
// edge, use the displacement value.
edgeOffset = Math.max(edgeOffset, displacement);
}
return edgeOffset;
}
/**
* Calculates displacement for element based on its dimensions and placement.
*
* @param {HTMLElement} el
* The jQuery element whose dimensions and placement will be measured.
*
* @param {string} edge
* The name of the edge of the viewport that the element is associated
* with.
*
* @return {number}
* The viewport displacement distance for the requested edge.
*/
function getRawOffset(el, edge) {
var $el = $(el);
var documentElement = document.documentElement;
var displacement = 0;
var horizontal = (edge === 'left' || edge === 'right');
// Get the offset of the element itself.
var placement = $el.offset()[horizontal ? 'left' : 'top'];
// Subtract scroll distance from placement to get the distance
// to the edge of the viewport.
placement -= window['scroll' + (horizontal ? 'X' : 'Y')] || document.documentElement['scroll' + (horizontal ? 'Left' : 'Top')] || 0;
// Find the displacement value according to the edge.
switch (edge) {
// Left and top elements displace as a sum of their own offset value
// plus their size.
case 'top':
// Total displacement is the sum of the elements placement and size.
displacement = placement + $el.outerHeight();
break;
case 'left':
// Total displacement is the sum of the elements placement and size.
displacement = placement + $el.outerWidth();
break;
// Right and bottom elements displace according to their left and
// top offset. Their size isn't important.
case 'bottom':
displacement = documentElement.clientHeight - placement;
break;
case 'right':
displacement = documentElement.clientWidth - placement;
break;
default:
displacement = 0;
}
return displacement;
}
/**
* Assign the displace function to a property of the Drupal global object.
*
* @ignore
*/
Drupal.displace = displace;
$.extend(Drupal.displace, {
/**
* Expose offsets to other scripts to avoid having to recalculate offsets.
*
* @ignore
*/
offsets: offsets,
/**
* Expose method to compute a single edge offsets.
*
* @ignore
*/
calculateOffset: calculateOffset
});
})(jQuery, Drupal, Drupal.debounce);
;
/**
* @file
* Builds a nested accordion widget.
*
* Invoke on an HTML list element with the jQuery plugin pattern.
*
* @example
* $('.toolbar-menu').drupalToolbarMenu();
*/
(function ($, Drupal, drupalSettings) {
'use strict';
/**
* Store the open menu tray.
*/
var activeItem = Drupal.url(drupalSettings.path.currentPath);
$.fn.drupalToolbarMenu = function () {
var ui = {
handleOpen: Drupal.t('Extend'),
handleClose: Drupal.t('Collapse')
};
/**
* Handle clicks from the disclosure button on an item with sub-items.
*
* @param {Object} event
* A jQuery Event object.
*/
function toggleClickHandler(event) {
var $toggle = $(event.target);
var $item = $toggle.closest('li');
// Toggle the list item.
toggleList($item);
// Close open sibling menus.
var $openItems = $item.siblings().filter('.open');
toggleList($openItems, false);
}
/**
* Handle clicks from a menu item link.
*
* @param {Object} event
* A jQuery Event object.
*/
function linkClickHandler(event) {
// If the toolbar is positioned fixed (and therefore hiding content
// underneath), then users expect clicks in the administration menu tray
// to take them to that destination but for the menu tray to be closed
// after clicking: otherwise the toolbar itself is obstructing the view
// of the destination they chose.
if (!Drupal.toolbar.models.toolbarModel.get('isFixed')) {
Drupal.toolbar.models.toolbarModel.set('activeTab', null);
}
// Stopping propagation to make sure that once a toolbar-box is clicked
// (the whitespace part), the page is not redirected anymore.
event.stopPropagation();
}
/**
* Toggle the open/close state of a list is a menu.
*
* @param {jQuery} $item
* The li item to be toggled.
*
* @param {Boolean} switcher
* A flag that forces toggleClass to add or a remove a class, rather than
* simply toggling its presence.
*/
function toggleList($item, switcher) {
var $toggle = $item.children('.toolbar-box').children('.toolbar-handle');
switcher = (typeof switcher !== 'undefined') ? switcher : !$item.hasClass('open');
// Toggle the item open state.
$item.toggleClass('open', switcher);
// Twist the toggle.
$toggle.toggleClass('open', switcher);
// Adjust the toggle text.
$toggle
.find('.action')
// Expand Structure, Collapse Structure.
.text((switcher) ? ui.handleClose : ui.handleOpen);
}
/**
* Add markup to the menu elements.
*
* Items with sub-elements have a list toggle attached to them. Menu item
* links and the corresponding list toggle are wrapped with in a div
* classed with .toolbar-box. The .toolbar-box div provides a positioning
* context for the item list toggle.
*
* @param {jQuery} $menu
* The root of the menu to be initialized.
*/
function initItems($menu) {
var options = {
class: 'toolbar-icon toolbar-handle',
action: ui.handleOpen,
text: ''
};
// Initialize items and their links.
$menu.find('li > a').wrap('<div class="toolbar-box">');
// Add a handle to each list item if it has a menu.
$menu.find('li').each(function (index, element) {
var $item = $(element);
if ($item.children('ul.toolbar-menu').length) {
var $box = $item.children('.toolbar-box');
options.text = Drupal.t('@label', {'@label': $box.find('a').text()});
$item.children('.toolbar-box')
.append(Drupal.theme('toolbarMenuItemToggle', options));
}
});
}
/**
* Adds a level class to each list based on its depth in the menu.
*
* This function is called recursively on each sub level of lists elements
* until the depth of the menu is exhausted.
*
* @param {jQuery} $lists
* A jQuery object of ul elements.
*
* @param {number} level
* The current level number to be assigned to the list elements.
*/
function markListLevels($lists, level) {
level = (!level) ? 1 : level;
var $lis = $lists.children('li').addClass('level-' + level);
$lists = $lis.children('ul');
if ($lists.length) {
markListLevels($lists, level + 1);
}
}
/**
* On page load, open the active menu item.
*
* Marks the trail of the active link in the menu back to the root of the
* menu with .menu-item--active-trail.
*
* @param {jQuery} $menu
* The root of the menu.
*/
function openActiveItem($menu) {
var pathItem = $menu.find('a[href="' + location.pathname + '"]');
if (pathItem.length && !activeItem) {
activeItem = location.pathname;
}
if (activeItem) {
var $activeItem = $menu.find('a[href="' + activeItem + '"]').addClass('menu-item--active');
var $activeTrail = $activeItem.parentsUntil('.root', 'li').addClass('menu-item--active-trail');
toggleList($activeTrail, true);
}
}
// Return the jQuery object.
return this.each(function (selector) {
var $menu = $(this).once('toolbar-menu');
if ($menu.length) {
// Bind event handlers.
$menu
.on('click.toolbar', '.toolbar-box', toggleClickHandler)
.on('click.toolbar', '.toolbar-box a', linkClickHandler);
$menu.addClass('root');
initItems($menu);
markListLevels($menu);
// Restore previous and active states.
openActiveItem($menu);
}
});
};
/**
* A toggle is an interactive element often bound to a click handler.
*
* @param {object} options
* Options for the button.
* @param {string} options.class
* Class to set on the button.
* @param {string} options.action
* Action for the button.
* @param {string} options.text
* Used as label for the button.
*
* @return {string}
* A string representing a DOM fragment.
*/
Drupal.theme.toolbarMenuItemToggle = function (options) {
return '<button class="' + options['class'] + '"><span class="action">' + options.action + '</span><span class="label">' + options.text + '</span></button>';
};
}(jQuery, Drupal, drupalSettings));
;
/**
* @file
* Defines the behavior of the Drupal administration toolbar.
*/
(function ($, Drupal, drupalSettings) {
'use strict';
// Merge run-time settings with the defaults.
var options = $.extend(
{
breakpoints: {
'toolbar.narrow': '',
'toolbar.standard': '',
'toolbar.wide': ''
}
},
drupalSettings.toolbar,
// Merge strings on top of drupalSettings so that they are not mutable.
{
strings: {
horizontal: Drupal.t('Horizontal orientation'),
vertical: Drupal.t('Vertical orientation')
}
}
);
/**
* Registers tabs with the toolbar.
*
* The Drupal toolbar allows modules to register top-level tabs. These may
* point directly to a resource or toggle the visibility of a tray.
*
* Modules register tabs with hook_toolbar().
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the toolbar rendering functionality to the toolbar element.
*/
Drupal.behaviors.toolbar = {
attach: function (context) {
// Verify that the user agent understands media queries. Complex admin
// toolbar layouts require media query support.
if (!window.matchMedia('only screen').matches) {
return;
}
// Process the administrative toolbar.
$(context).find('#toolbar-administration').once('toolbar').each(function () {
// Establish the toolbar models and views.
var model = Drupal.toolbar.models.toolbarModel = new Drupal.toolbar.ToolbarModel({
locked: JSON.parse(localStorage.getItem('Drupal.toolbar.trayVerticalLocked')) || false,
activeTab: document.getElementById(JSON.parse(localStorage.getItem('Drupal.toolbar.activeTabID')))
});
Drupal.toolbar.views.toolbarVisualView = new Drupal.toolbar.ToolbarVisualView({
el: this,
model: model,
strings: options.strings
});
Drupal.toolbar.views.toolbarAuralView = new Drupal.toolbar.ToolbarAuralView({
el: this,
model: model,
strings: options.strings
});
Drupal.toolbar.views.bodyVisualView = new Drupal.toolbar.BodyVisualView({
el: this,
model: model
});
// Render collapsible menus.
var menuModel = Drupal.toolbar.models.menuModel = new Drupal.toolbar.MenuModel();
Drupal.toolbar.views.menuVisualView = new Drupal.toolbar.MenuVisualView({
el: $(this).find('.toolbar-menu-administration').get(0),
model: menuModel,
strings: options.strings
});
// Handle the resolution of Drupal.toolbar.setSubtrees.
// This is handled with a deferred so that the function may be invoked
// asynchronously.
Drupal.toolbar.setSubtrees.done(function (subtrees) {
menuModel.set('subtrees', subtrees);
var theme = drupalSettings.ajaxPageState.theme;
localStorage.setItem('Drupal.toolbar.subtrees.' + theme, JSON.stringify(subtrees));
// Indicate on the toolbarModel that subtrees are now loaded.
model.set('areSubtreesLoaded', true);
});
// Attach a listener to the configured media query breakpoints.
for (var label in options.breakpoints) {
if (options.breakpoints.hasOwnProperty(label)) {
var mq = options.breakpoints[label];
var mql = Drupal.toolbar.mql[label] = window.matchMedia(mq);
// Curry the model and the label of the media query breakpoint to
// the mediaQueryChangeHandler function.
mql.addListener(Drupal.toolbar.mediaQueryChangeHandler.bind(null, model, label));
// Fire the mediaQueryChangeHandler for each configured breakpoint
// so that they process once.
Drupal.toolbar.mediaQueryChangeHandler.call(null, model, label, mql);
}
}
// Trigger an initial attempt to load menu subitems. This first attempt
// is made after the media query handlers have had an opportunity to
// process. The toolbar starts in the vertical orientation by default,
// unless the viewport is wide enough to accommodate a horizontal
// orientation. Thus we give the Toolbar a chance to determine if it
// should be set to horizontal orientation before attempting to load
// menu subtrees.
Drupal.toolbar.views.toolbarVisualView.loadSubtrees();
$(document)
// Update the model when the viewport offset changes.
.on('drupalViewportOffsetChange.toolbar', function (event, offsets) {
model.set('offsets', offsets);
});
// Broadcast model changes to other modules.
model
.on('change:orientation', function (model, orientation) {
$(document).trigger('drupalToolbarOrientationChange', orientation);
})
.on('change:activeTab', function (model, tab) {
$(document).trigger('drupalToolbarTabChange', tab);
})
.on('change:activeTray', function (model, tray) {
$(document).trigger('drupalToolbarTrayChange', tray);
});
// If the toolbar's orientation is horizontal and no active tab is
// defined then show the tray of the first toolbar tab by default (but
// not the first 'Home' toolbar tab).
if (Drupal.toolbar.models.toolbarModel.get('orientation') === 'horizontal' && Drupal.toolbar.models.toolbarModel.get('activeTab') === null) {
Drupal.toolbar.models.toolbarModel.set({
activeTab: $('.toolbar-bar .toolbar-tab:not(.home-toolbar-tab) a').get(0)
});
}
});
}
};
/**
* Toolbar methods of Backbone objects.
*
* @namespace
*/
Drupal.toolbar = {
/**
* A hash of View instances.
*
* @type {object.<string, Backbone.View>}
*/
views: {},
/**
* A hash of Model instances.
*
* @type {object.<string, Backbone.Model>}
*/
models: {},
/**
* A hash of MediaQueryList objects tracked by the toolbar.
*
* @type {object.<string, object>}
*/
mql: {},
/**
* Accepts a list of subtree menu elements.
*
* A deferred object that is resolved by an inlined JavaScript callback.
*
* @type {jQuery.Deferred}
*
* @see toolbar_subtrees_jsonp().
*/
setSubtrees: new $.Deferred(),
/**
* Respond to configured narrow media query changes.
*
* @param {Drupal.toolbar.ToolbarModel} model
* A toolbar model
* @param {string} label
* Media query label.
* @param {object} mql
* A MediaQueryList object.
*/
mediaQueryChangeHandler: function (model, label, mql) {
switch (label) {
case 'toolbar.narrow':
model.set({
isOriented: mql.matches,
isTrayToggleVisible: false
});
// If the toolbar doesn't have an explicit orientation yet, or if the
// narrow media query doesn't match then set the orientation to
// vertical.
if (!mql.matches || !model.get('orientation')) {
model.set({orientation: 'vertical'}, {validate: true});
}
break;
case 'toolbar.standard':
model.set({
isFixed: mql.matches
});
break;
case 'toolbar.wide':
model.set({
orientation: ((mql.matches) ? 'horizontal' : 'vertical')
}, {validate: true});
// The tray orientation toggle visibility does not need to be
// validated.
model.set({
isTrayToggleVisible: mql.matches
});
break;
default:
break;
}
}
};
/**
* A toggle is an interactive element often bound to a click handler.
*
* @return {string}
* A string representing a DOM fragment.
*/
Drupal.theme.toolbarOrientationToggle = function () {
return '<div class="toolbar-toggle-orientation"><div class="toolbar-lining">' +
'<button class="toolbar-icon" type="button"></button>' +
'</div></div>';
};
/**
* Ajax command to set the toolbar subtrees.
*
* @param {Drupal.Ajax} ajax
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* JSON response from the Ajax request.
* @param {number} [status]
* XMLHttpRequest status.
*/
Drupal.AjaxCommands.prototype.setToolbarSubtrees = function (ajax, response, status) {
Drupal.toolbar.setSubtrees.resolve(response.subtrees);
};
}(jQuery, Drupal, drupalSettings));
;
/**
* @file
* A Backbone Model for collapsible menus.
*/
(function (Backbone, Drupal) {
'use strict';
/**
* Backbone Model for collapsible menus.
*
* @constructor
*
* @augments Backbone.Model
*/
Drupal.toolbar.MenuModel = Backbone.Model.extend(/** @lends Drupal.toolbar.MenuModel# */{
/**
* @type {object}
*
* @prop {object} subtrees
*/
defaults: /** @lends Drupal.toolbar.MenuModel# */{
/**
* @type {object}
*/
subtrees: {}
}
});
}(Backbone, Drupal));
;
/**
* @file
* A Backbone Model for the toolbar.
*/
(function (Backbone, Drupal) {
'use strict';
/**
* Backbone model for the toolbar.
*
* @constructor
*
* @augments Backbone.Model
*/
Drupal.toolbar.ToolbarModel = Backbone.Model.extend(/** @lends Drupal.toolbar.ToolbarModel# */{
/**
* @type {object}
*
* @prop activeTab
* @prop activeTray
* @prop isOriented
* @prop isFixed
* @prop areSubtreesLoaded
* @prop isViewportOverflowConstrained
* @prop orientation
* @prop locked
* @prop isTrayToggleVisible
* @prop height
* @prop offsets
*/
defaults: /** @lends Drupal.toolbar.ToolbarModel# */{
/**
* The active toolbar tab. All other tabs should be inactive under
* normal circumstances. It will remain active across page loads. The
* active item is stored as an ID selector e.g. '#toolbar-item--1'.
*
* @type {string}
*/
activeTab: null,
/**
* Represents whether a tray is open or not. Stored as an ID selector e.g.
* '#toolbar-item--1-tray'.
*
* @type {string}
*/
activeTray: null,
/**
* Indicates whether the toolbar is displayed in an oriented fashion,
* either horizontal or vertical.
*
* @type {bool}
*/
isOriented: false,
/**
* Indicates whether the toolbar is positioned absolute (false) or fixed
* (true).
*
* @type {bool}
*/
isFixed: false,
/**
* Menu subtrees are loaded through an AJAX request only when the Toolbar
* is set to a vertical orientation.
*
* @type {bool}
*/
areSubtreesLoaded: false,
/**
* If the viewport overflow becomes constrained, isFixed must be true so
* that elements in the trays aren't lost off-screen and impossible to
* get to.
*
* @type {bool}
*/
isViewportOverflowConstrained: false,
/**
* The orientation of the active tray.
*
* @type {string}
*/
orientation: 'vertical',
/**
* A tray is locked if a user toggled it to vertical. Otherwise a tray
* will switch between vertical and horizontal orientation based on the
* configured breakpoints. The locked state will be maintained across page
* loads.
*
* @type {bool}
*/
locked: false,
/**
* Indicates whether the tray orientation toggle is visible.
*
* @type {bool}
*/
isTrayToggleVisible: false,
/**
* The height of the toolbar.
*
* @type {number}
*/
height: null,
/**
* The current viewport offsets determined by {@link Drupal.displace}. The
* offsets suggest how a module might position is components relative to
* the viewport.
*
* @type {object}
*
* @prop {number} top
* @prop {number} right
* @prop {number} bottom
* @prop {number} left
*/
offsets: {
top: 0,
right: 0,
bottom: 0,
left: 0
}
},
/**
* @inheritdoc
*
* @param {object} attributes
* Attributes for the toolbar.
* @param {object} options
* Options for the toolbar.
*
* @return {string|undefined}
* Returns an error message if validation failed.
*/
validate: function (attributes, options) {
// Prevent the orientation being set to horizontal if it is locked, unless
// override has not been passed as an option.
if (attributes.orientation === 'horizontal' && this.get('locked') && !options.override) {
return Drupal.t('The toolbar cannot be set to a horizontal orientation when it is locked.');
}
}
});
}(Backbone, Drupal));
;
/**
* @file
* A Backbone view for the body element.
*/
(function ($, Drupal, Backbone) {
'use strict';
Drupal.toolbar.BodyVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.BodyVisualView# */{
/**
* Adjusts the body element with the toolbar position and dimension changes.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change:orientation change:offsets change:activeTray change:isOriented change:isFixed change:isViewportOverflowConstrained', this.render);
},
/**
* @inheritdoc
*/
render: function () {
var $body = $('body');
var orientation = this.model.get('orientation');
var isOriented = this.model.get('isOriented');
var isViewportOverflowConstrained = this.model.get('isViewportOverflowConstrained');
$body
// We are using JavaScript to control media-query handling for two
// reasons: (1) Using JavaScript let's us leverage the breakpoint
// configurations and (2) the CSS is really complex if we try to hide
// some styling from browsers that don't understand CSS media queries.
// If we drive the CSS from classes added through JavaScript,
// then the CSS becomes simpler and more robust.
.toggleClass('toolbar-vertical', (orientation === 'vertical'))
.toggleClass('toolbar-horizontal', (isOriented && orientation === 'horizontal'))
// When the toolbar is fixed, it will not scroll with page scrolling.
.toggleClass('toolbar-fixed', (isViewportOverflowConstrained || this.model.get('isFixed')))
// Toggle the toolbar-tray-open class on the body element. The class is
// applied when a toolbar tray is active. Padding might be applied to
// the body element to prevent the tray from overlapping content.
.toggleClass('toolbar-tray-open', !!this.model.get('activeTray'))
// Apply padding to the top of the body to offset the placement of the
// toolbar bar element.
.css('padding-top', this.model.get('offsets').top);
}
});
}(jQuery, Drupal, Backbone));
;
/**
* @file
* A Backbone view for the collapsible menus.
*/
(function ($, Backbone, Drupal) {
'use strict';
Drupal.toolbar.MenuVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.MenuVisualView# */{
/**
* Backbone View for collapsible menus.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change:subtrees', this.render);
},
/**
* @inheritdoc
*/
render: function () {
var subtrees = this.model.get('subtrees');
// Add subtrees.
for (var id in subtrees) {
if (subtrees.hasOwnProperty(id)) {
this.$el
.find('#toolbar-link-' + id)
.once('toolbar-subtrees')
.after(subtrees[id]);
}
}
// Render the main menu as a nested, collapsible accordion.
if ('drupalToolbarMenu' in $.fn) {
this.$el
.children('.toolbar-menu')
.drupalToolbarMenu();
}
}
});
}(jQuery, Backbone, Drupal));
;
/**
* @file
* A Backbone view for the aural feedback of the toolbar.
*/
(function (Backbone, Drupal) {
'use strict';
Drupal.toolbar.ToolbarAuralView = Backbone.View.extend(/** @lends Drupal.toolbar.ToolbarAuralView# */{
/**
* Backbone view for the aural feedback of the toolbar.
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options for the view.
* @param {object} options.strings
* Various strings to use in the view.
*/
initialize: function (options) {
this.strings = options.strings;
this.listenTo(this.model, 'change:orientation', this.onOrientationChange);
this.listenTo(this.model, 'change:activeTray', this.onActiveTrayChange);
},
/**
* Announces an orientation change.
*
* @param {Drupal.toolbar.ToolbarModel} model
* The toolbar model in question.
* @param {string} orientation
* The new value of the orientation attribute in the model.
*/
onOrientationChange: function (model, orientation) {
Drupal.announce(Drupal.t('Tray orientation changed to @orientation.', {
'@orientation': orientation
}));
},
/**
* Announces a changed active tray.
*
* @param {Drupal.toolbar.ToolbarModel} model
* The toolbar model in question.
* @param {HTMLElement} tray
* The new value of the tray attribute in the model.
*/
onActiveTrayChange: function (model, tray) {
var relevantTray = (tray === null) ? model.previous('activeTray') : tray;
var action = (tray === null) ? Drupal.t('closed') : Drupal.t('opened');
var trayNameElement = relevantTray.querySelector('.toolbar-tray-name');
var text;
if (trayNameElement !== null) {
text = Drupal.t('Tray "@tray" @action.', {
'@tray': trayNameElement.textContent, '@action': action
});
}
else {
text = Drupal.t('Tray @action.', {'@action': action});
}
Drupal.announce(text);
}
});
}(Backbone, Drupal));
;
/**
* @file
* A Backbone view for the toolbar element. Listens to mouse & touch.
*/
(function ($, Drupal, drupalSettings, Backbone) {
'use strict';
Drupal.toolbar.ToolbarVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.ToolbarVisualView# */{
/**
* Event map for the `ToolbarVisualView`.
*
* @return {object}
* A map of events.
*/
events: function () {
// Prevents delay and simulated mouse events.
var touchEndToClick = function (event) {
event.preventDefault();
event.target.click();
};
return {
'click .toolbar-bar .toolbar-tab .trigger': 'onTabClick',
'click .toolbar-toggle-orientation button': 'onOrientationToggleClick',
'touchend .toolbar-bar .toolbar-tab .trigger': touchEndToClick,
'touchend .toolbar-toggle-orientation button': touchEndToClick
};
},
/**
* Backbone view for the toolbar element. Listens to mouse & touch.
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options for the view object.
* @param {object} options.strings
* Various strings to use in the view.
*/
initialize: function (options) {
this.strings = options.strings;
this.listenTo(this.model, 'change:activeTab change:orientation change:isOriented change:isTrayToggleVisible', this.render);
this.listenTo(this.model, 'change:mqMatches', this.onMediaQueryChange);
this.listenTo(this.model, 'change:offsets', this.adjustPlacement);
// Add the tray orientation toggles.
this.$el
.find('.toolbar-tray .toolbar-lining')
.append(Drupal.theme('toolbarOrientationToggle'));
// Trigger an activeTab change so that listening scripts can respond on
// page load. This will call render.
this.model.trigger('change:activeTab');
},
/**
* @inheritdoc
*
* @return {Drupal.toolbar.ToolbarVisualView}
* The `ToolbarVisualView` instance.
*/
render: function () {
this.updateTabs();
this.updateTrayOrientation();
this.updateBarAttributes();
// Load the subtrees if the orientation of the toolbar is changed to
// vertical. This condition responds to the case that the toolbar switches
// from horizontal to vertical orientation. The toolbar starts in a
// vertical orientation by default and then switches to horizontal during
// initialization if the media query conditions are met. Simply checking
// that the orientation is vertical here would result in the subtrees
// always being loaded, even when the toolbar initialization ultimately
// results in a horizontal orientation.
//
// @see Drupal.behaviors.toolbar.attach() where admin menu subtrees
// loading is invoked during initialization after media query conditions
// have been processed.
if (this.model.changed.orientation === 'vertical' || this.model.changed.activeTab) {
this.loadSubtrees();
}
// Trigger a recalculation of viewport displacing elements. Use setTimeout
// to ensure this recalculation happens after changes to visual elements
// have processed.
window.setTimeout(function () {
Drupal.displace(true);
}, 0);
return this;
},
/**
* Responds to a toolbar tab click.
*
* @param {jQuery.Event} event
* The event triggered.
*/
onTabClick: function (event) {
// If this tab has a tray associated with it, it is considered an
// activatable tab.
if (event.target.hasAttribute('data-toolbar-tray')) {
var activeTab = this.model.get('activeTab');
var clickedTab = event.target;
// Set the event target as the active item if it is not already.
this.model.set('activeTab', (!activeTab || clickedTab !== activeTab) ? clickedTab : null);
event.preventDefault();
event.stopPropagation();
}
},
/**
* Toggles the orientation of a toolbar tray.
*
* @param {jQuery.Event} event
* The event triggered.
*/
onOrientationToggleClick: function (event) {
var orientation = this.model.get('orientation');
// Determine the toggle-to orientation.
var antiOrientation = (orientation === 'vertical') ? 'horizontal' : 'vertical';
var locked = antiOrientation === 'vertical';
// Remember the locked state.
if (locked) {
localStorage.setItem('Drupal.toolbar.trayVerticalLocked', 'true');
}
else {
localStorage.removeItem('Drupal.toolbar.trayVerticalLocked');
}
// Update the model.
this.model.set({
locked: locked,
orientation: antiOrientation
}, {
validate: true,
override: true
});
event.preventDefault();
event.stopPropagation();
},
/**
* Updates the display of the tabs: toggles a tab and the associated tray.
*/
updateTabs: function () {
var $tab = $(this.model.get('activeTab'));
// Deactivate the previous tab.
$(this.model.previous('activeTab'))
.removeClass('is-active')
.prop('aria-pressed', false);
// Deactivate the previous tray.
$(this.model.previous('activeTray'))
.removeClass('is-active');
// Activate the selected tab.
if ($tab.length > 0) {
$tab
.addClass('is-active')
// Mark the tab as pressed.
.prop('aria-pressed', true);
var name = $tab.attr('data-toolbar-tray');
// Store the active tab name or remove the setting.
var id = $tab.get(0).id;
if (id) {
localStorage.setItem('Drupal.toolbar.activeTabID', JSON.stringify(id));
}
// Activate the associated tray.
var $tray = this.$el.find('[data-toolbar-tray="' + name + '"].toolbar-tray');
if ($tray.length) {
$tray.addClass('is-active');
this.model.set('activeTray', $tray.get(0));
}
else {
// There is no active tray.
this.model.set('activeTray', null);
}
}
else {
// There is no active tray.
this.model.set('activeTray', null);
localStorage.removeItem('Drupal.toolbar.activeTabID');
}
},
/**
* Update the attributes of the toolbar bar element.
*/
updateBarAttributes: function () {
var isOriented = this.model.get('isOriented');
if (isOriented) {
this.$el.find('.toolbar-bar').attr('data-offset-top', '');
}
else {
this.$el.find('.toolbar-bar').removeAttr('data-offset-top');
}
// Toggle between a basic vertical view and a more sophisticated
// horizontal and vertical display of the toolbar bar and trays.
this.$el.toggleClass('toolbar-oriented', isOriented);
},
/**
* Updates the orientation of the active tray if necessary.
*/
updateTrayOrientation: function () {
var orientation = this.model.get('orientation');
// The antiOrientation is used to render the view of action buttons like
// the tray orientation toggle.
var antiOrientation = (orientation === 'vertical') ? 'horizontal' : 'vertical';
// Update the orientation of the trays.
var $trays = this.$el.find('.toolbar-tray')
.removeClass('toolbar-tray-horizontal toolbar-tray-vertical')
.addClass('toolbar-tray-' + orientation);
// Update the tray orientation toggle button.
var iconClass = 'toolbar-icon-toggle-' + orientation;
var iconAntiClass = 'toolbar-icon-toggle-' + antiOrientation;
var $orientationToggle = this.$el.find('.toolbar-toggle-orientation')
.toggle(this.model.get('isTrayToggleVisible'));
$orientationToggle.find('button')
.val(antiOrientation)
.attr('title', this.strings[antiOrientation])
.text(this.strings[antiOrientation])
.removeClass(iconClass)
.addClass(iconAntiClass);
// Update data offset attributes for the trays.
var dir = document.documentElement.dir;
var edge = (dir === 'rtl') ? 'right' : 'left';
// Remove data-offset attributes from the trays so they can be refreshed.
$trays.removeAttr('data-offset-left data-offset-right data-offset-top');
// If an active vertical tray exists, mark it as an offset element.
$trays.filter('.toolbar-tray-vertical.is-active').attr('data-offset-' + edge, '');
// If an active horizontal tray exists, mark it as an offset element.
$trays.filter('.toolbar-tray-horizontal.is-active').attr('data-offset-top', '');
},
/**
* Sets the tops of the trays so that they align with the bottom of the bar.
*/
adjustPlacement: function () {
var $trays = this.$el.find('.toolbar-tray');
if (!this.model.get('isOriented')) {
$trays.css('margin-top', 0);
$trays.removeClass('toolbar-tray-horizontal').addClass('toolbar-tray-vertical');
}
else {
// The toolbar container is invisible. Its placement is used to
// determine the container for the trays.
$trays.css('margin-top', this.$el.find('.toolbar-bar').outerHeight());
}
},
/**
* Calls the endpoint URI that builds an AJAX command with the rendered
* subtrees.
*
* The rendered admin menu subtrees HTML is cached on the client in
* localStorage until the cache of the admin menu subtrees on the server-
* side is invalidated. The subtreesHash is stored in localStorage as well
* and compared to the subtreesHash in drupalSettings to determine when the
* admin menu subtrees cache has been invalidated.
*/
loadSubtrees: function () {
var $activeTab = $(this.model.get('activeTab'));
var orientation = this.model.get('orientation');
// Only load and render the admin menu subtrees if:
// (1) They have not been loaded yet.
// (2) The active tab is the administration menu tab, indicated by the
// presence of the data-drupal-subtrees attribute.
// (3) The orientation of the tray is vertical.
if (!this.model.get('areSubtreesLoaded') && typeof $activeTab.data('drupal-subtrees') !== 'undefined' && orientation === 'vertical') {
var subtreesHash = drupalSettings.toolbar.subtreesHash;
var theme = drupalSettings.ajaxPageState.theme;
var endpoint = Drupal.url('toolbar/subtrees/' + subtreesHash);
var cachedSubtreesHash = localStorage.getItem('Drupal.toolbar.subtreesHash.' + theme);
var cachedSubtrees = JSON.parse(localStorage.getItem('Drupal.toolbar.subtrees.' + theme));
var isVertical = this.model.get('orientation') === 'vertical';
// If we have the subtrees in localStorage and the subtree hash has not
// changed, then use the cached data.
if (isVertical && subtreesHash === cachedSubtreesHash && cachedSubtrees) {
Drupal.toolbar.setSubtrees.resolve(cachedSubtrees);
}
// Only make the call to get the subtrees if the orientation of the
// toolbar is vertical.
else if (isVertical) {
// Remove the cached menu information.
localStorage.removeItem('Drupal.toolbar.subtreesHash.' + theme);
localStorage.removeItem('Drupal.toolbar.subtrees.' + theme);
// The AJAX response's command will trigger the resolve method of the
// Drupal.toolbar.setSubtrees Promise.
Drupal.ajax({url: endpoint}).execute();
// Cache the hash for the subtrees locally.
localStorage.setItem('Drupal.toolbar.subtreesHash.' + theme, subtreesHash);
}
}
}
});
}(jQuery, Drupal, drupalSettings, Backbone));
;
| schnitzel25/conta | sites/default/files/js/js_3YI8rlQtCphHC8k7Vs22nkB6_u47OqwXcD7P8Jm9QQg_BHuNkXbS1MEkV6lGkimSfQE6366BcKxzYtd8U65iUpM.js | JavaScript | gpl-2.0 | 96,793 |
/* OtherwiseNode.java --
Copyright (C) 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.xml.transform;
import javax.xml.namespace.QName;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Node;
/**
* A template node representing an XSL <code>otherwise</code> instruction.
*
* @author <a href='mailto:dog@gnu.org'>Chris Burdess</a>
*/
final class OtherwiseNode
extends TemplateNode
{
OtherwiseNode(TemplateNode children, TemplateNode next)
{
super(children, next);
}
TemplateNode clone(Stylesheet stylesheet)
{
return new OtherwiseNode((children == null) ? null :
children.clone(stylesheet),
(next == null) ? null :
next.clone(stylesheet));
}
void doApply(Stylesheet stylesheet, QName mode,
Node context, int pos, int len,
Node parent, Node nextSibling)
throws TransformerException
{
if (children != null)
{
children.apply(stylesheet, mode,
context, pos, len,
parent, nextSibling);
}
if (next != null)
{
next.apply(stylesheet, mode,
context, pos, len,
parent, nextSibling);
}
}
public String toString()
{
StringBuffer buf = new StringBuffer(getClass().getName());
buf.append('[');
buf.append(']');
return buf.toString();
}
}
| unofficial-opensource-apple/gcc_40 | libjava/gnu/xml/transform/OtherwiseNode.java | Java | gpl-2.0 | 3,110 |
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
/*
COPYING CONDITIONS NOTICE:
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation, and provided that the
following conditions are met:
* Redistributions of source code must retain this COPYING
CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
PATENT MARKING NOTICE (below), and the PATENT RIGHTS
GRANT (below).
* Redistributions in binary form must reproduce this COPYING
CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the
DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the
PATENT MARKING NOTICE (below), and the PATENT RIGHTS
GRANT (below) in the documentation and/or other materials
provided with the distribution.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
COPYRIGHT NOTICE:
TokuDB, Tokutek Fractal Tree Indexing Library.
Copyright (C) 2007-2013 Tokutek, Inc.
DISCLAIMER:
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.
UNIVERSITY PATENT NOTICE:
The technology is licensed by the Massachusetts Institute of
Technology, Rutgers State University of New Jersey, and the Research
Foundation of State University of New York at Stony Brook under
United States of America Serial No. 11/760379 and to the patents
and/or patent applications resulting from it.
PATENT MARKING NOTICE:
This software is covered by US Patent No. 8,185,551.
This software is covered by US Patent No. 8,489,638.
PATENT RIGHTS GRANT:
"THIS IMPLEMENTATION" means the copyrightable works distributed by
Tokutek as part of the Fractal Tree project.
"PATENT CLAIMS" means the claims of patents that are owned or
licensable by Tokutek, both currently or in the future; and that in
the absence of this license would be infringed by THIS
IMPLEMENTATION or by using or running THIS IMPLEMENTATION.
"PATENT CHALLENGE" shall mean a challenge to the validity,
patentability, enforceability and/or non-infringement of any of the
PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS.
Tokutek hereby grants to you, for the term and geographical scope of
the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to
make, have made, use, offer to sell, sell, import, transfer, and
otherwise run, modify, and propagate the contents of THIS
IMPLEMENTATION, where such license applies only to the PATENT
CLAIMS. This grant does not include claims that would be infringed
only as a consequence of further modifications of THIS
IMPLEMENTATION. If you or your agent or licensee institute or order
or agree to the institution of patent litigation against any entity
(including a cross-claim or counterclaim in a lawsuit) alleging that
THIS IMPLEMENTATION constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any rights
granted to you under this License shall terminate as of the date
such litigation is filed. If you or your agent or exclusive
licensee institute or order or agree to the institution of a PATENT
CHALLENGE, then Tokutek may terminate any rights granted to you
under this License.
*/
#ident "Copyright (c) 2007-2013 Tokutek Inc. All rights reserved."
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."
/* -*- mode: C; c-basic-offset: 4 -*- */
#define MYSQL_SERVER 1
#include "hatoku_defines.h"
#include <db.h>
#include "stdint.h"
#if defined(_WIN32)
#include "misc.h"
#endif
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include "toku_os.h"
#include "toku_time.h"
#include "partitioned_counter.h"
/* We define DTRACE after mysql_priv.h in case it disabled dtrace in the main server */
#ifdef HAVE_DTRACE
#define _DTRACE_VERSION 1
#else
#endif
#include <mysql/plugin.h>
#include "hatoku_hton.h"
#include "ha_tokudb.h"
#undef PACKAGE
#undef VERSION
#undef HAVE_DTRACE
#undef _DTRACE_VERSION
#define TOKU_METADB_NAME "tokudb_meta"
typedef struct savepoint_info {
DB_TXN* txn;
tokudb_trx_data* trx;
bool in_sub_stmt;
} *SP_INFO, SP_INFO_T;
#if defined(MARIADB_BASE_VERSION)
ha_create_table_option tokudb_index_options[] = {
HA_IOPTION_BOOL("clustering", clustering, 0),
HA_IOPTION_END
};
#endif
static uchar *tokudb_get_key(TOKUDB_SHARE * share, size_t * length, my_bool not_used __attribute__ ((unused))) {
*length = share->table_name_length;
return (uchar *) share->table_name;
}
static handler *tokudb_create_handler(handlerton * hton, TABLE_SHARE * table, MEM_ROOT * mem_root);
static void tokudb_print_error(const DB_ENV * db_env, const char *db_errpfx, const char *buffer);
static void tokudb_cleanup_log_files(void);
static int tokudb_end(handlerton * hton, ha_panic_function type);
static bool tokudb_flush_logs(handlerton * hton);
static bool tokudb_show_status(handlerton * hton, THD * thd, stat_print_fn * print, enum ha_stat_type);
#if TOKU_INCLUDE_HANDLERTON_HANDLE_FATAL_SIGNAL
static void tokudb_handle_fatal_signal(handlerton *hton, THD *thd, int sig);
#endif
static int tokudb_close_connection(handlerton * hton, THD * thd);
static int tokudb_commit(handlerton * hton, THD * thd, bool all);
static int tokudb_rollback(handlerton * hton, THD * thd, bool all);
#if TOKU_INCLUDE_XA
static int tokudb_xa_prepare(handlerton* hton, THD* thd, bool all);
static int tokudb_xa_recover(handlerton* hton, XID* xid_list, uint len);
static int tokudb_commit_by_xid(handlerton* hton, XID* xid);
static int tokudb_rollback_by_xid(handlerton* hton, XID* xid);
#endif
static int tokudb_rollback_to_savepoint(handlerton * hton, THD * thd, void *savepoint);
static int tokudb_savepoint(handlerton * hton, THD * thd, void *savepoint);
static int tokudb_release_savepoint(handlerton * hton, THD * thd, void *savepoint);
static int tokudb_discover_table(handlerton *hton, THD* thd, TABLE_SHARE *ts);
static int tokudb_discover_table_existence(handlerton *hton, const char *db, const char *name);
static int tokudb_discover(handlerton *hton, THD* thd, const char *db, const char *name, uchar **frmblob, size_t *frmlen);
static int tokudb_discover2(handlerton *hton, THD* thd, const char *db, const char *name, bool translate_name,uchar **frmblob, size_t *frmlen);
static int tokudb_discover3(handlerton *hton, THD* thd, const char *db, const char *name, char *path, uchar **frmblob, size_t *frmlen);
handlerton *tokudb_hton;
const char *ha_tokudb_ext = ".tokudb";
char *tokudb_data_dir;
ulong tokudb_debug;
DB_ENV *db_env;
HASH tokudb_open_tables;
pthread_mutex_t tokudb_mutex;
#if TOKU_THDVAR_MEMALLOC_BUG
static pthread_mutex_t tokudb_map_mutex;
static TREE tokudb_map;
struct tokudb_map_pair {
THD *thd;
char *last_lock_timeout;
};
#if 50500 <= MYSQL_VERSION_ID && MYSQL_VERSION_ID <= 50599
static int tokudb_map_pair_cmp(void *custom_arg, const void *a, const void *b) {
#else
static int tokudb_map_pair_cmp(const void *custom_arg, const void *a, const void *b) {
#endif
const struct tokudb_map_pair *a_key = (const struct tokudb_map_pair *) a;
const struct tokudb_map_pair *b_key = (const struct tokudb_map_pair *) b;
if (a_key->thd < b_key->thd)
return -1;
else if (a_key->thd > b_key->thd)
return +1;
else
return 0;
};
#endif
#if TOKU_INCLUDE_HANDLERTON_HANDLE_FATAL_SIGNAL
static my_bool tokudb_gdb_on_fatal;
static char *tokudb_gdb_path;
#endif
static PARTITIONED_COUNTER tokudb_primary_key_bytes_inserted;
void toku_hton_update_primary_key_bytes_inserted(uint64_t row_size) {
increment_partitioned_counter(tokudb_primary_key_bytes_inserted, row_size);
}
static void tokudb_lock_timeout_callback(DB *db, uint64_t requesting_txnid, const DBT *left_key, const DBT *right_key, uint64_t blocking_txnid);
static ulong tokudb_cleaner_period;
static ulong tokudb_cleaner_iterations;
#define ASSERT_MSGLEN 1024
void toku_hton_assert_fail(const char* expr_as_string, const char * fun, const char * file, int line, int caller_errno) {
char msg[ASSERT_MSGLEN];
if (db_env) {
snprintf(msg, ASSERT_MSGLEN, "Handlerton: %s ", expr_as_string);
db_env->crash(db_env, msg, fun, file, line,caller_errno);
}
else {
snprintf(msg, ASSERT_MSGLEN, "Handlerton assertion failed, no env, %s, %d, %s, %s (errno=%d)\n", file, line, fun, expr_as_string, caller_errno);
perror(msg);
fflush(stderr);
}
abort();
}
//my_bool tokudb_shared_data = false;
static uint32_t tokudb_init_flags =
DB_CREATE | DB_THREAD | DB_PRIVATE |
DB_INIT_LOCK |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_INIT_LOG |
DB_RECOVER;
static uint32_t tokudb_env_flags = 0;
// static uint32_t tokudb_lock_type = DB_LOCK_DEFAULT;
// static ulong tokudb_log_buffer_size = 0;
// static ulong tokudb_log_file_size = 0;
static my_bool tokudb_directio = FALSE;
static my_bool tokudb_checkpoint_on_flush_logs = FALSE;
static ulonglong tokudb_cache_size = 0;
static ulonglong tokudb_max_lock_memory = 0;
static char *tokudb_home;
static char *tokudb_tmp_dir;
static char *tokudb_log_dir;
// static long tokudb_lock_scan_time = 0;
// static ulong tokudb_region_size = 0;
// static ulong tokudb_cache_parts = 1;
const char *tokudb_hton_name = "TokuDB";
static uint32_t tokudb_checkpointing_period;
static uint32_t tokudb_fsync_log_period;
uint32_t tokudb_write_status_frequency;
uint32_t tokudb_read_status_frequency;
#ifdef TOKUDB_VERSION
char *tokudb_version = (char*) TOKUDB_VERSION;
#else
char *tokudb_version;
#endif
static int tokudb_fs_reserve_percent; // file system reserve as a percentage of total disk space
#if defined(_WIN32)
extern "C" {
#include "ydb.h"
}
#endif
ha_create_table_option tokudb_table_options[]=
{
HA_TOPTION_SYSVAR("compression", row_format, row_format),
HA_TOPTION_END
};
// A flag set if the handlerton is in an initialized, usable state,
// plus a reader-write lock to protect it without serializing reads.
// Since we don't have static initializers for the opaque rwlock type,
// use constructor and destructor functions to create and destroy
// the lock before and after main(), respectively.
static int tokudb_hton_initialized;
static rw_lock_t tokudb_hton_initialized_lock;
static void create_tokudb_hton_intialized_lock(void) __attribute__((constructor));
static void create_tokudb_hton_intialized_lock(void) {
my_rwlock_init(&tokudb_hton_initialized_lock, 0);
}
static void destroy_tokudb_hton_initialized_lock(void) __attribute__((destructor));
static void destroy_tokudb_hton_initialized_lock(void) {
rwlock_destroy(&tokudb_hton_initialized_lock);
}
static SHOW_VAR *toku_global_status_variables = NULL;
static uint64_t toku_global_status_max_rows;
static TOKU_ENGINE_STATUS_ROW_S* toku_global_status_rows = NULL;
static void handle_ydb_error(int error) {
switch (error) {
case TOKUDB_HUGE_PAGES_ENABLED:
fprintf(stderr, "************************************************************\n");
fprintf(stderr, " \n");
fprintf(stderr, " @@@@@@@@@@@ \n");
fprintf(stderr, " @@' '@@ \n");
fprintf(stderr, " @@ _ _ @@ \n");
fprintf(stderr, " | (.) (.) | \n");
fprintf(stderr, " | ` | \n");
fprintf(stderr, " | > ' | \n");
fprintf(stderr, " | .----. | \n");
fprintf(stderr, " .. |.----.| .. \n");
fprintf(stderr, " .. ' ' .. \n");
fprintf(stderr, " .._______,. \n");
fprintf(stderr, " \n");
fprintf(stderr, " %s will not run with transparent huge pages enabled. \n", tokudb_hton_name);
fprintf(stderr, " Please disable them to continue. \n");
fprintf(stderr, " (echo never > /sys/kernel/mm/transparent_hugepage/enabled) \n");
fprintf(stderr, " \n");
fprintf(stderr, "************************************************************\n");
fflush(stderr);
break;
}
}
static int tokudb_init_func(void *p) {
TOKUDB_DBUG_ENTER("");
int r;
#if defined(_WIN64)
r = toku_ydb_init();
if (r) {
fprintf(stderr, "got error %d\n", r);
goto error;
}
#endif
// 3938: lock the handlerton's initialized status flag for writing
r = rw_wrlock(&tokudb_hton_initialized_lock);
assert(r == 0);
db_env = NULL;
tokudb_hton = (handlerton *) p;
tokudb_pthread_mutex_init(&tokudb_mutex, MY_MUTEX_INIT_FAST);
(void) my_hash_init(&tokudb_open_tables, table_alias_charset, 32, 0, 0, (my_hash_get_key) tokudb_get_key, 0, 0);
tokudb_hton->state = SHOW_OPTION_YES;
// tokudb_hton->flags= HTON_CAN_RECREATE; // QQQ this came from skeleton
tokudb_hton->flags = HTON_CLOSE_CURSORS_AT_COMMIT | HTON_SUPPORTS_EXTENDED_KEYS;
#if defined(TOKU_INCLUDE_EXTENDED_KEYS) && TOKU_INCLUDE_EXTENDED_KEYS
#if defined(HTON_SUPPORTS_EXTENDED_KEYS)
tokudb_hton->flags |= HTON_SUPPORTS_EXTENDED_KEYS;
#endif
#if defined(HTON_EXTENDED_KEYS)
tokudb_hton->flags |= HTON_EXTENDED_KEYS;
#endif
#endif
#if defined(HTON_SUPPORTS_CLUSTERED_KEYS)
tokudb_hton->flags |= HTON_SUPPORTS_CLUSTERED_KEYS;
#endif
#if defined(TOKU_USE_DB_TYPE_TOKUDB) && TOKU_USE_DB_TYPE_TOKUDB
tokudb_hton->db_type = DB_TYPE_TOKUDB;
#elif defined(TOKU_USE_DB_TYPE_UNKNOWN) && TOKU_USE_DB_TYPE_UNKNOWN
tokudb_hton->db_type = DB_TYPE_UNKNOWN;
#else
#error
#endif
tokudb_hton->create = tokudb_create_handler;
tokudb_hton->close_connection = tokudb_close_connection;
tokudb_hton->savepoint_offset = sizeof(SP_INFO_T);
tokudb_hton->savepoint_set = tokudb_savepoint;
tokudb_hton->savepoint_rollback = tokudb_rollback_to_savepoint;
tokudb_hton->savepoint_release = tokudb_release_savepoint;
tokudb_hton->discover_table = tokudb_discover_table;
tokudb_hton->discover_table_existence = tokudb_discover_table_existence;
#if defined(MYSQL_HANDLERTON_INCLUDE_DISCOVER2)
tokudb_hton->discover2 = tokudb_discover2;
#endif
tokudb_hton->commit = tokudb_commit;
tokudb_hton->rollback = tokudb_rollback;
#if TOKU_INCLUDE_XA
tokudb_hton->prepare=tokudb_xa_prepare;
tokudb_hton->recover=tokudb_xa_recover;
tokudb_hton->commit_by_xid=tokudb_commit_by_xid;
tokudb_hton->rollback_by_xid=tokudb_rollback_by_xid;
#endif
tokudb_hton->table_options= tokudb_table_options;
tokudb_hton->index_options= tokudb_index_options;
tokudb_hton->panic = tokudb_end;
tokudb_hton->flush_logs = tokudb_flush_logs;
tokudb_hton->show_status = tokudb_show_status;
#if TOKU_INCLUDE_HANDLERTON_HANDLE_FATAL_SIGNAL
tokudb_hton->handle_fatal_signal = tokudb_handle_fatal_signal;
#endif
#if defined(MARIADB_BASE_VERSION)
tokudb_hton->index_options = tokudb_index_options;
#endif
if (!tokudb_home)
tokudb_home = mysql_real_data_home;
DBUG_PRINT("info", ("tokudb_home: %s", tokudb_home));
if ((r = db_env_create(&db_env, 0))) {
DBUG_PRINT("info", ("db_env_create %d\n", r));
handle_ydb_error(r);
goto error;
}
DBUG_PRINT("info", ("tokudb_env_flags: 0x%x\n", tokudb_env_flags));
r = db_env->set_flags(db_env, tokudb_env_flags, 1);
if (r) { // QQQ
if (tokudb_debug & TOKUDB_DEBUG_INIT)
TOKUDB_TRACE("WARNING: flags=%x r=%d", tokudb_env_flags, r);
// goto error;
}
// config error handling
db_env->set_errcall(db_env, tokudb_print_error);
db_env->set_errpfx(db_env, tokudb_hton_name);
//
// set default comparison functions
//
r = db_env->set_default_bt_compare(db_env, tokudb_cmp_dbt_key);
if (r) {
DBUG_PRINT("info", ("set_default_bt_compare%d\n", r));
goto error;
}
{
char *tmp_dir = tokudb_tmp_dir;
char *data_dir = tokudb_data_dir;
if (data_dir == 0) {
data_dir = mysql_data_home;
}
if (tmp_dir == 0) {
tmp_dir = data_dir;
}
DBUG_PRINT("info", ("tokudb_data_dir: %s\n", data_dir));
db_env->set_data_dir(db_env, data_dir);
DBUG_PRINT("info", ("tokudb_tmp_dir: %s\n", tmp_dir));
db_env->set_tmp_dir(db_env, tmp_dir);
}
if (tokudb_log_dir) {
DBUG_PRINT("info", ("tokudb_log_dir: %s\n", tokudb_log_dir));
db_env->set_lg_dir(db_env, tokudb_log_dir);
}
// config the cache table size to min(1/2 of physical memory, 1/8 of the process address space)
if (tokudb_cache_size == 0) {
uint64_t physmem, maxdata;
physmem = toku_os_get_phys_memory_size();
tokudb_cache_size = physmem / 2;
r = toku_os_get_max_process_data_size(&maxdata);
if (r == 0) {
if (tokudb_cache_size > maxdata / 8)
tokudb_cache_size = maxdata / 8;
}
}
if (tokudb_cache_size) {
DBUG_PRINT("info", ("tokudb_cache_size: %lld\n", tokudb_cache_size));
r = db_env->set_cachesize(db_env, (uint32_t)(tokudb_cache_size >> 30), (uint32_t)(tokudb_cache_size % (1024L * 1024L * 1024L)), 1);
if (r) {
DBUG_PRINT("info", ("set_cachesize %d\n", r));
goto error;
}
}
if (tokudb_max_lock_memory == 0) {
tokudb_max_lock_memory = tokudb_cache_size/8;
}
if (tokudb_max_lock_memory) {
DBUG_PRINT("info", ("tokudb_max_lock_memory: %lld\n", tokudb_max_lock_memory));
r = db_env->set_lk_max_memory(db_env, tokudb_max_lock_memory);
if (r) {
DBUG_PRINT("info", ("set_lk_max_memory %d\n", r));
goto error;
}
}
uint32_t gbytes, bytes; int parts;
r = db_env->get_cachesize(db_env, &gbytes, &bytes, &parts);
if (tokudb_debug & TOKUDB_DEBUG_INIT)
TOKUDB_TRACE("tokudb_cache_size=%lld r=%d", ((unsigned long long) gbytes << 30) + bytes, r);
if (db_env->set_redzone) {
r = db_env->set_redzone(db_env, tokudb_fs_reserve_percent);
if (tokudb_debug & TOKUDB_DEBUG_INIT)
TOKUDB_TRACE("set_redzone r=%d", r);
}
if (tokudb_debug & TOKUDB_DEBUG_INIT)
TOKUDB_TRACE("env open:flags=%x", tokudb_init_flags);
r = db_env->set_generate_row_callback_for_put(db_env,generate_row_for_put);
assert(r == 0);
r = db_env->set_generate_row_callback_for_del(db_env,generate_row_for_del);
assert(r == 0);
db_env->set_update(db_env, tokudb_update_fun);
db_env_set_direct_io(tokudb_directio == TRUE);
db_env->change_fsync_log_period(db_env, tokudb_fsync_log_period);
db_env->set_lock_timeout_callback(db_env, tokudb_lock_timeout_callback);
db_env->set_loader_memory_size(db_env, tokudb_get_loader_memory_size_callback);
r = db_env->open(db_env, tokudb_home, tokudb_init_flags, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
if (tokudb_debug & TOKUDB_DEBUG_INIT)
TOKUDB_TRACE("env opened:return=%d", r);
if (r) {
DBUG_PRINT("info", ("env->open %d", r));
goto error;
}
r = db_env->checkpointing_set_period(db_env, tokudb_checkpointing_period);
assert(r == 0);
r = db_env->cleaner_set_period(db_env, tokudb_cleaner_period);
assert(r == 0);
r = db_env->cleaner_set_iterations(db_env, tokudb_cleaner_iterations);
assert(r == 0);
r = db_env->set_lock_timeout(db_env, DEFAULT_TOKUDB_LOCK_TIMEOUT, tokudb_get_lock_wait_time_callback);
assert(r == 0);
db_env->set_killed_callback(db_env, DEFAULT_TOKUDB_KILLED_TIME, tokudb_get_killed_time_callback, tokudb_killed_callback);
r = db_env->get_engine_status_num_rows (db_env, &toku_global_status_max_rows);
assert(r == 0);
{
const myf mem_flags = MY_FAE|MY_WME|MY_ZEROFILL|MY_ALLOW_ZERO_PTR|MY_FREE_ON_ERROR;
toku_global_status_variables = (SHOW_VAR*)tokudb_my_malloc(sizeof(*toku_global_status_variables)*toku_global_status_max_rows, mem_flags);
toku_global_status_rows = (TOKU_ENGINE_STATUS_ROW_S*)tokudb_my_malloc(sizeof(*toku_global_status_rows)*toku_global_status_max_rows, mem_flags);
}
tokudb_primary_key_bytes_inserted = create_partitioned_counter();
#if TOKU_THDVAR_MEMALLOC_BUG
tokudb_pthread_mutex_init(&tokudb_map_mutex, MY_MUTEX_INIT_FAST);
init_tree(&tokudb_map, 0, 0, 0, tokudb_map_pair_cmp, true, NULL, NULL);
#endif
//3938: succeeded, set the init status flag and unlock
tokudb_hton_initialized = 1;
rw_unlock(&tokudb_hton_initialized_lock);
DBUG_RETURN(false);
error:
if (db_env) {
int rr= db_env->close(db_env, 0);
assert(rr==0);
db_env = 0;
}
// 3938: failed to initialized, drop the flag and lock
tokudb_hton_initialized = 0;
rw_unlock(&tokudb_hton_initialized_lock);
DBUG_RETURN(true);
}
static int tokudb_done_func(void *p) {
TOKUDB_DBUG_ENTER("");
tokudb_my_free(toku_global_status_variables);
toku_global_status_variables = NULL;
tokudb_my_free(toku_global_status_rows);
toku_global_status_rows = NULL;
my_hash_free(&tokudb_open_tables);
tokudb_pthread_mutex_destroy(&tokudb_mutex);
#if defined(_WIN64)
toku_ydb_destroy();
#endif
TOKUDB_DBUG_RETURN(0);
}
static handler *tokudb_create_handler(handlerton * hton, TABLE_SHARE * table, MEM_ROOT * mem_root) {
return new(mem_root) ha_tokudb(hton, table);
}
int tokudb_end(handlerton * hton, ha_panic_function type) {
TOKUDB_DBUG_ENTER("");
int error = 0;
// 3938: if we finalize the storage engine plugin, it is no longer
// initialized. grab a writer lock for the duration of the
// call, so we can drop the flag and destroy the mutexes
// in isolation.
rw_wrlock(&tokudb_hton_initialized_lock);
assert(tokudb_hton_initialized);
if (db_env) {
if (tokudb_init_flags & DB_INIT_LOG)
tokudb_cleanup_log_files();
error = db_env->close(db_env, 0); // Error is logged
assert(error==0);
db_env = NULL;
}
if (tokudb_primary_key_bytes_inserted) {
destroy_partitioned_counter(tokudb_primary_key_bytes_inserted);
tokudb_primary_key_bytes_inserted = NULL;
}
#if TOKU_THDVAR_MEMALLOC_BUG
tokudb_pthread_mutex_destroy(&tokudb_map_mutex);
delete_tree(&tokudb_map);
#endif
// 3938: drop the initialized flag and unlock
tokudb_hton_initialized = 0;
rw_unlock(&tokudb_hton_initialized_lock);
TOKUDB_DBUG_RETURN(error);
}
static int tokudb_close_connection(handlerton * hton, THD * thd) {
int error = 0;
tokudb_trx_data* trx = NULL;
trx = (tokudb_trx_data *) thd_data_get(thd, tokudb_hton->slot);
if (tokudb_debug & TOKUDB_DEBUG_TXN) {
TOKUDB_TRACE("trx %p", trx);
}
if (trx && trx->checkpoint_lock_taken) {
error = db_env->checkpointing_resume(db_env);
}
tokudb_my_free(trx);
#if TOKU_THDVAR_MEMALLOC_BUG
tokudb_pthread_mutex_lock(&tokudb_map_mutex);
struct tokudb_map_pair key = { thd, NULL };
struct tokudb_map_pair *found_key = (struct tokudb_map_pair *) tree_search(&tokudb_map, &key, NULL);
if (found_key) {
if (0) TOKUDB_TRACE("thd %p %p", thd, found_key->last_lock_timeout);
tokudb_my_free(found_key->last_lock_timeout);
tree_delete(&tokudb_map, found_key, sizeof *found_key, NULL);
}
tokudb_pthread_mutex_unlock(&tokudb_map_mutex);
#endif
return error;
}
bool tokudb_flush_logs(handlerton * hton) {
TOKUDB_DBUG_ENTER("");
int error;
bool result = 0;
if (tokudb_checkpoint_on_flush_logs) {
//
// take the checkpoint
//
error = db_env->txn_checkpoint(db_env, 0, 0, 0);
if (error) {
my_error(ER_ERROR_DURING_CHECKPOINT, MYF(0), error);
result = 1;
goto exit;
}
}
else {
error = db_env->log_flush(db_env, NULL);
assert(error == 0);
}
result = 0;
exit:
TOKUDB_DBUG_RETURN(result);
}
typedef struct txn_progress_info {
char status[200];
THD* thd;
} *TXN_PROGRESS_INFO;
static void txn_progress_func(TOKU_TXN_PROGRESS progress, void* extra) {
TXN_PROGRESS_INFO progress_info = (TXN_PROGRESS_INFO)extra;
int r = sprintf(progress_info->status,
"%sprocessing %s of transaction, %" PRId64 " out of %" PRId64,
progress->stalled_on_checkpoint ? "Writing committed changes to disk, " : "",
progress->is_commit ? "commit" : "abort",
progress->entries_processed,
progress->entries_total
);
assert(r >= 0);
thd_proc_info(progress_info->thd, progress_info->status);
}
static void commit_txn_with_progress(DB_TXN* txn, uint32_t flags, THD* thd) {
int r;
struct txn_progress_info info;
info.thd = thd;
r = txn->commit_with_progress(txn, flags, txn_progress_func, &info);
if (r != 0) {
sql_print_error("tried committing transaction %p and got error code %d", txn, r);
}
assert(r == 0);
}
static void abort_txn_with_progress(DB_TXN* txn, THD* thd) {
int r;
struct txn_progress_info info;
info.thd = thd;
r = txn->abort_with_progress(txn, txn_progress_func, &info);
if (r != 0) {
sql_print_error("tried aborting transaction %p and got error code %d", txn, r);
}
assert(r == 0);
}
static void tokudb_cleanup_handlers(tokudb_trx_data *trx, DB_TXN *txn) {
LIST *e;
while ((e = trx->handlers)) {
trx->handlers = list_delete(trx->handlers, e);
ha_tokudb *handler = (ha_tokudb *) e->data;
handler->cleanup_txn(txn);
}
}
static int tokudb_commit(handlerton * hton, THD * thd, bool all) {
TOKUDB_DBUG_ENTER("");
DBUG_PRINT("trans", ("ending transaction %s", all ? "all" : "stmt"));
uint32_t syncflag = THDVAR(thd, commit_sync) ? 0 : DB_TXN_NOSYNC;
tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
DB_TXN **txn = all ? &trx->all : &trx->stmt;
DB_TXN *this_txn = *txn;
if (this_txn) {
if (tokudb_debug & TOKUDB_DEBUG_TXN) {
TOKUDB_TRACE("commit trx %u trx %p txn %p", all, trx, this_txn);
}
// test hook to induce a crash on a debug build
DBUG_EXECUTE_IF("tokudb_crash_commit_before", DBUG_SUICIDE(););
tokudb_cleanup_handlers(trx, this_txn);
commit_txn_with_progress(this_txn, syncflag, thd);
// test hook to induce a crash on a debug build
DBUG_EXECUTE_IF("tokudb_crash_commit_after", DBUG_SUICIDE(););
if (this_txn == trx->sp_level) {
trx->sp_level = 0;
}
*txn = 0;
trx->sub_sp_level = NULL;
}
else if (tokudb_debug & TOKUDB_DEBUG_TXN) {
TOKUDB_TRACE("nothing to commit %d", all);
}
reset_stmt_progress(&trx->stmt_progress);
TOKUDB_DBUG_RETURN(0);
}
static int tokudb_rollback(handlerton * hton, THD * thd, bool all) {
TOKUDB_DBUG_ENTER("");
DBUG_PRINT("trans", ("aborting transaction %s", all ? "all" : "stmt"));
tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
DB_TXN **txn = all ? &trx->all : &trx->stmt;
DB_TXN *this_txn = *txn;
if (this_txn) {
if (tokudb_debug & TOKUDB_DEBUG_TXN) {
TOKUDB_TRACE("rollback %u trx %p txn %p", all, trx, this_txn);
}
tokudb_cleanup_handlers(trx, this_txn);
abort_txn_with_progress(this_txn, thd);
if (this_txn == trx->sp_level) {
trx->sp_level = 0;
}
*txn = 0;
trx->sub_sp_level = NULL;
}
else {
if (tokudb_debug & TOKUDB_DEBUG_TXN) {
TOKUDB_TRACE("abort0");
}
}
reset_stmt_progress(&trx->stmt_progress);
TOKUDB_DBUG_RETURN(0);
}
#if TOKU_INCLUDE_XA
static int tokudb_xa_prepare(handlerton* hton, THD* thd, bool all) {
TOKUDB_DBUG_ENTER("");
int r = 0;
DBUG_PRINT("trans", ("preparing transaction %s", all ? "all" : "stmt"));
tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
DB_TXN* txn = all ? trx->all : trx->stmt;
if (txn) {
if (tokudb_debug & TOKUDB_DEBUG_TXN) {
TOKUDB_TRACE("doing txn prepare:%d:%p", all, txn);
}
// a TOKU_XA_XID is identical to a MYSQL_XID
TOKU_XA_XID thd_xid;
thd_get_xid(thd, (MYSQL_XID*) &thd_xid);
// test hook to induce a crash on a debug build
DBUG_EXECUTE_IF("tokudb_crash_prepare_before", DBUG_SUICIDE(););
r = txn->xa_prepare(txn, &thd_xid);
// test hook to induce a crash on a debug build
DBUG_EXECUTE_IF("tokudb_crash_prepare_after", DBUG_SUICIDE(););
}
else if (tokudb_debug & TOKUDB_DEBUG_TXN) {
TOKUDB_TRACE("nothing to prepare %d", all);
}
TOKUDB_DBUG_RETURN(r);
}
static int tokudb_xa_recover(handlerton* hton, XID* xid_list, uint len) {
TOKUDB_DBUG_ENTER("");
int r = 0;
if (len == 0 || xid_list == NULL) {
TOKUDB_DBUG_RETURN(0);
}
long num_returned = 0;
r = db_env->txn_xa_recover(
db_env,
(TOKU_XA_XID*)xid_list,
len,
&num_returned,
DB_NEXT
);
assert(r == 0);
TOKUDB_DBUG_RETURN((int)num_returned);
}
static int tokudb_commit_by_xid(handlerton* hton, XID* xid) {
TOKUDB_DBUG_ENTER("");
int r = 0;
DB_TXN* txn = NULL;
TOKU_XA_XID* toku_xid = (TOKU_XA_XID*)xid;
r = db_env->get_txn_from_xid(db_env, toku_xid, &txn);
if (r) { goto cleanup; }
r = txn->commit(txn, 0);
if (r) { goto cleanup; }
r = 0;
cleanup:
TOKUDB_DBUG_RETURN(r);
}
static int tokudb_rollback_by_xid(handlerton* hton, XID* xid) {
TOKUDB_DBUG_ENTER("");
int r = 0;
DB_TXN* txn = NULL;
TOKU_XA_XID* toku_xid = (TOKU_XA_XID*)xid;
r = db_env->get_txn_from_xid(db_env, toku_xid, &txn);
if (r) { goto cleanup; }
r = txn->abort(txn);
if (r) { goto cleanup; }
r = 0;
cleanup:
TOKUDB_DBUG_RETURN(r);
}
#endif
static int tokudb_savepoint(handlerton * hton, THD * thd, void *savepoint) {
TOKUDB_DBUG_ENTER("");
int error;
SP_INFO save_info = (SP_INFO)savepoint;
tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
if (thd->in_sub_stmt) {
assert(trx->stmt);
error = txn_begin(db_env, trx->sub_sp_level, &(save_info->txn), DB_INHERIT_ISOLATION, thd);
if (error) {
goto cleanup;
}
trx->sub_sp_level = save_info->txn;
save_info->in_sub_stmt = true;
}
else {
error = txn_begin(db_env, trx->sp_level, &(save_info->txn), DB_INHERIT_ISOLATION, thd);
if (error) {
goto cleanup;
}
trx->sp_level = save_info->txn;
save_info->in_sub_stmt = false;
}
save_info->trx = trx;
error = 0;
cleanup:
TOKUDB_DBUG_RETURN(error);
}
static int tokudb_rollback_to_savepoint(handlerton * hton, THD * thd, void *savepoint) {
TOKUDB_DBUG_ENTER("");
int error;
SP_INFO save_info = (SP_INFO)savepoint;
DB_TXN* parent = NULL;
DB_TXN* txn_to_rollback = save_info->txn;
tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
parent = txn_to_rollback->parent;
if (!(error = txn_to_rollback->abort(txn_to_rollback))) {
if (save_info->in_sub_stmt) {
trx->sub_sp_level = parent;
}
else {
trx->sp_level = parent;
}
error = tokudb_savepoint(hton, thd, savepoint);
}
TOKUDB_DBUG_RETURN(error);
}
static int tokudb_release_savepoint(handlerton * hton, THD * thd, void *savepoint) {
TOKUDB_DBUG_ENTER("");
int error;
SP_INFO save_info = (SP_INFO)savepoint;
DB_TXN* parent = NULL;
DB_TXN* txn_to_commit = save_info->txn;
tokudb_trx_data *trx = (tokudb_trx_data *) thd_data_get(thd, hton->slot);
parent = txn_to_commit->parent;
if (!(error = txn_to_commit->commit(txn_to_commit, 0))) {
if (save_info->in_sub_stmt) {
trx->sub_sp_level = parent;
}
else {
trx->sp_level = parent;
}
save_info->txn = NULL;
}
TOKUDB_DBUG_RETURN(error);
}
static int tokudb_discover_table(handlerton *hton, THD* thd, TABLE_SHARE *ts) {
uchar *frmblob = 0;
size_t frmlen;
int res= tokudb_discover3(hton, thd, ts->db.str, ts->table_name.str,
ts->normalized_path.str, &frmblob, &frmlen);
if (!res)
res= ts->init_from_binary_frm_image(thd, true, frmblob, frmlen);
my_free(frmblob);
// discover_table should returns HA_ERR_NO_SUCH_TABLE for "not exists"
return res == ENOENT ? HA_ERR_NO_SUCH_TABLE : res;
}
static int tokudb_discover_table_existence(handlerton *hton, const char *db, const char *name) {
uchar *frmblob = 0;
size_t frmlen;
int res= tokudb_discover(hton, current_thd, db, name, &frmblob, &frmlen);
my_free(frmblob);
return res != ENOENT;
}
static int tokudb_discover(handlerton *hton, THD* thd, const char *db, const char *name, uchar **frmblob, size_t *frmlen) {
return tokudb_discover2(hton, thd, db, name, true, frmblob, frmlen);
}
static int tokudb_discover2(handlerton *hton, THD* thd, const char *db, const char *name, bool translate_name,
uchar **frmblob, size_t *frmlen) {
char path[FN_REFLEN + 1];
build_table_filename(path, sizeof(path) - 1, db, name, "", translate_name ? 0 : FN_IS_TMP);
return tokudb_discover3(hton, thd, db, name, path, frmblob, frmlen);
}
static int tokudb_discover3(handlerton *hton, THD* thd, const char *db, const char *name, char *path,
uchar **frmblob, size_t *frmlen) {
TOKUDB_DBUG_ENTER("%s %s", db, name);
int error;
DB* status_db = NULL;
DB_TXN* txn = NULL;
HA_METADATA_KEY curr_key = hatoku_frm_data;
DBT key, value;
tokudb_trx_data *trx = NULL;
bool do_commit = false;
memset(&key, 0, sizeof(key));
memset(&value, 0, sizeof(&value));
trx = (tokudb_trx_data *) thd_data_get(thd, tokudb_hton->slot);
if (thd_sql_command(thd) == SQLCOM_CREATE_TABLE && trx && trx->sub_sp_level) {
txn = trx->sub_sp_level;
}
else {
do_commit = true;
error = txn_begin(db_env, 0, &txn, 0, thd);
if (error) { goto cleanup; }
}
error = open_status_dictionary(&status_db, path, txn);
if (error) { goto cleanup; }
key.data = &curr_key;
key.size = sizeof(curr_key);
error = status_db->getf_set(
status_db,
txn,
0,
&key,
smart_dbt_callback_verify_frm,
&value
);
if (error) {
goto cleanup;
}
*frmblob = (uchar *)value.data;
*frmlen = value.size;
error = 0;
cleanup:
if (status_db) {
status_db->close(status_db,0);
}
if (do_commit && txn) {
commit_txn(txn,0);
}
TOKUDB_DBUG_RETURN(error);
}
#define STATPRINT(legend, val) if (legend != NULL && val != NULL) stat_print(thd, \
tokudb_hton_name, \
strlen(tokudb_hton_name), \
legend, \
strlen(legend), \
val, \
strlen(val))
extern sys_var *intern_find_sys_var(const char *str, uint length, bool no_error);
static bool tokudb_show_engine_status(THD * thd, stat_print_fn * stat_print) {
TOKUDB_DBUG_ENTER("");
int error;
uint64_t panic;
const int panic_string_len = 1024;
char panic_string[panic_string_len] = {'\0'};
uint64_t num_rows;
uint64_t max_rows;
fs_redzone_state redzone_state;
const int bufsiz = 1024;
char buf[bufsiz];
#if MYSQL_VERSION_ID < 50500
{
sys_var * version = intern_find_sys_var("version", 0, false);
snprintf(buf, bufsiz, "%s", version->value_ptr(thd, (enum_var_type)0, (LEX_STRING*)NULL));
STATPRINT("Version", buf);
}
#endif
error = db_env->get_engine_status_num_rows (db_env, &max_rows);
TOKU_ENGINE_STATUS_ROW_S mystat[max_rows];
error = db_env->get_engine_status (db_env, mystat, max_rows, &num_rows, &redzone_state, &panic, panic_string, panic_string_len, TOKU_ENGINE_STATUS);
if (strlen(panic_string)) {
STATPRINT("Environment panic string", panic_string);
}
if (error == 0) {
if (panic) {
snprintf(buf, bufsiz, "%" PRIu64, panic);
STATPRINT("Environment panic", buf);
}
if(redzone_state == FS_BLOCKED) {
STATPRINT("*** URGENT WARNING ***", "FILE SYSTEM IS COMPLETELY FULL");
snprintf(buf, bufsiz, "FILE SYSTEM IS COMPLETELY FULL");
}
else if (redzone_state == FS_GREEN) {
snprintf(buf, bufsiz, "more than %d percent of total file system space", 2*tokudb_fs_reserve_percent);
}
else if (redzone_state == FS_YELLOW) {
snprintf(buf, bufsiz, "*** WARNING *** FILE SYSTEM IS GETTING FULL (less than %d percent free)", 2*tokudb_fs_reserve_percent);
}
else if (redzone_state == FS_RED){
snprintf(buf, bufsiz, "*** WARNING *** FILE SYSTEM IS GETTING VERY FULL (less than %d percent free): INSERTS ARE PROHIBITED", tokudb_fs_reserve_percent);
}
else {
snprintf(buf, bufsiz, "information unavailable, unknown redzone state %d", redzone_state);
}
STATPRINT ("disk free space", buf);
for (uint64_t row = 0; row < num_rows; row++) {
switch (mystat[row].type) {
case FS_STATE:
snprintf(buf, bufsiz, "%" PRIu64 "", mystat[row].value.num);
break;
case UINT64:
snprintf(buf, bufsiz, "%" PRIu64 "", mystat[row].value.num);
break;
case CHARSTR:
snprintf(buf, bufsiz, "%s", mystat[row].value.str);
break;
case UNIXTIME:
{
time_t t = mystat[row].value.num;
char tbuf[26];
snprintf(buf, bufsiz, "%.24s", ctime_r(&t, tbuf));
}
break;
case TOKUTIME:
{
double t = tokutime_to_seconds(mystat[row].value.num);
snprintf(buf, bufsiz, "%.6f", t);
}
break;
case PARCOUNT:
{
uint64_t v = read_partitioned_counter(mystat[row].value.parcount);
snprintf(buf, bufsiz, "%" PRIu64, v);
}
break;
default:
snprintf(buf, bufsiz, "UNKNOWN STATUS TYPE: %d", mystat[row].type);
break;
}
STATPRINT(mystat[row].legend, buf);
}
uint64_t bytes_inserted = read_partitioned_counter(tokudb_primary_key_bytes_inserted);
snprintf(buf, bufsiz, "%" PRIu64, bytes_inserted);
STATPRINT("handlerton: primary key bytes inserted", buf);
}
if (error) { my_errno = error; }
TOKUDB_DBUG_RETURN(error);
}
static void tokudb_checkpoint_lock(THD * thd) {
int error;
const char *old_proc_info;
tokudb_trx_data* trx = NULL;
trx = (tokudb_trx_data *) thd_data_get(thd, tokudb_hton->slot);
if (!trx) {
error = create_tokudb_trx_data_instance(&trx);
//
// can only fail due to memory allocation, so ok to assert
//
assert(!error);
thd_data_set(thd, tokudb_hton->slot, trx);
}
if (trx->checkpoint_lock_taken) {
goto cleanup;
}
//
// This can only fail if environment is not created, which is not possible
// in handlerton
//
old_proc_info = tokudb_thd_get_proc_info(thd);
thd_proc_info(thd, "Trying to grab checkpointing lock.");
error = db_env->checkpointing_postpone(db_env);
assert(!error);
thd_proc_info(thd, old_proc_info);
trx->checkpoint_lock_taken = true;
cleanup:
return;
}
static void tokudb_checkpoint_unlock(THD * thd) {
int error;
const char *old_proc_info;
tokudb_trx_data* trx = NULL;
trx = (tokudb_trx_data *) thd_data_get(thd, tokudb_hton->slot);
if (!trx) {
error = 0;
goto cleanup;
}
if (!trx->checkpoint_lock_taken) {
error = 0;
goto cleanup;
}
//
// at this point, we know the checkpoint lock has been taken
//
old_proc_info = tokudb_thd_get_proc_info(thd);
thd_proc_info(thd, "Trying to release checkpointing lock.");
error = db_env->checkpointing_resume(db_env);
assert(!error);
thd_proc_info(thd, old_proc_info);
trx->checkpoint_lock_taken = false;
cleanup:
return;
}
static bool tokudb_show_status(handlerton * hton, THD * thd, stat_print_fn * stat_print, enum ha_stat_type stat_type) {
switch (stat_type) {
case HA_ENGINE_STATUS:
return tokudb_show_engine_status(thd, stat_print);
break;
default:
break;
}
return false;
}
#if TOKU_INCLUDE_HANDLERTON_HANDLE_FATAL_SIGNAL
static void tokudb_handle_fatal_signal(handlerton *hton __attribute__ ((__unused__)), THD *thd __attribute__ ((__unused__)), int sig) {
if (tokudb_gdb_on_fatal) {
db_env_try_gdb_stack_trace(tokudb_gdb_path);
}
}
#endif
static void tokudb_print_error(const DB_ENV * db_env, const char *db_errpfx, const char *buffer) {
sql_print_error("%s: %s", db_errpfx, buffer);
}
static void tokudb_cleanup_log_files(void) {
TOKUDB_DBUG_ENTER("");
char **names;
int error;
if ((error = db_env->txn_checkpoint(db_env, 0, 0, 0)))
my_error(ER_ERROR_DURING_CHECKPOINT, MYF(0), error);
if ((error = db_env->log_archive(db_env, &names, 0)) != 0) {
DBUG_PRINT("error", ("log_archive failed (error %d)", error));
db_env->err(db_env, error, "log_archive");
DBUG_VOID_RETURN;
}
if (names) {
char **np;
for (np = names; *np; ++np) {
#if 1
if (tokudb_debug)
TOKUDB_TRACE("cleanup:%s", *np);
#else
my_delete(*np, MYF(MY_WME));
#endif
}
free(names);
}
DBUG_VOID_RETURN;
}
// options flags
// PLUGIN_VAR_THDLOCAL Variable is per-connection
// PLUGIN_VAR_READONLY Server variable is read only
// PLUGIN_VAR_NOSYSVAR Not a server variable
// PLUGIN_VAR_NOCMDOPT Not a command line option
// PLUGIN_VAR_NOCMDARG No argument for cmd line
// PLUGIN_VAR_RQCMDARG Argument required for cmd line
// PLUGIN_VAR_OPCMDARG Argument optional for cmd line
// PLUGIN_VAR_MEMALLOC String needs memory allocated
// system variables
static void tokudb_cleaner_period_update(THD * thd, struct st_mysql_sys_var * sys_var, void * var, const void * save) {
ulong * cleaner_period = (ulong *) var;
*cleaner_period = *(const ulonglong *) save;
int r = db_env->cleaner_set_period(db_env, *cleaner_period);
assert(r == 0);
}
#define DEFAULT_CLEANER_PERIOD 1
static MYSQL_SYSVAR_ULONG(cleaner_period, tokudb_cleaner_period,
0, "TokuDB cleaner_period",
NULL, tokudb_cleaner_period_update, DEFAULT_CLEANER_PERIOD,
0, ~0UL, 0);
static void tokudb_cleaner_iterations_update(THD * thd, struct st_mysql_sys_var * sys_var, void * var, const void * save) {
ulong * cleaner_iterations = (ulong *) var;
*cleaner_iterations = *(const ulonglong *) save;
int r = db_env->cleaner_set_iterations(db_env, *cleaner_iterations);
assert(r == 0);
}
#define DEFAULT_CLEANER_ITERATIONS 5
static MYSQL_SYSVAR_ULONG(cleaner_iterations, tokudb_cleaner_iterations,
0, "TokuDB cleaner_iterations",
NULL, tokudb_cleaner_iterations_update, DEFAULT_CLEANER_ITERATIONS,
0, ~0UL, 0);
static void tokudb_checkpointing_period_update(THD * thd, struct st_mysql_sys_var * sys_var, void * var, const void * save) {
uint * checkpointing_period = (uint *) var;
*checkpointing_period = *(const ulonglong *) save;
int r = db_env->checkpointing_set_period(db_env, *checkpointing_period);
assert(r == 0);
}
static MYSQL_SYSVAR_UINT(checkpointing_period, tokudb_checkpointing_period,
0, "TokuDB Checkpointing period",
NULL, tokudb_checkpointing_period_update, 60,
0, ~0U, 0);
static MYSQL_SYSVAR_BOOL(directio, tokudb_directio,
PLUGIN_VAR_READONLY,
"TokuDB Enable Direct I/O ",
NULL, NULL, FALSE);
static MYSQL_SYSVAR_BOOL(checkpoint_on_flush_logs, tokudb_checkpoint_on_flush_logs,
0,
"TokuDB Checkpoint on Flush Logs ",
NULL, NULL, FALSE);
static MYSQL_SYSVAR_ULONGLONG(cache_size, tokudb_cache_size,
PLUGIN_VAR_READONLY, "TokuDB cache table size", NULL, NULL, 0,
0, ~0ULL, 0);
static MYSQL_SYSVAR_ULONGLONG(max_lock_memory, tokudb_max_lock_memory, PLUGIN_VAR_READONLY, "TokuDB max memory for locks", NULL, NULL, 0, 0, ~0ULL, 0);
static MYSQL_SYSVAR_ULONG(debug, tokudb_debug, 0, "TokuDB Debug", NULL, NULL, 0, 0, ~0UL, 0);
static MYSQL_SYSVAR_STR(log_dir, tokudb_log_dir, PLUGIN_VAR_READONLY, "TokuDB Log Directory", NULL, NULL, NULL);
static MYSQL_SYSVAR_STR(data_dir, tokudb_data_dir, PLUGIN_VAR_READONLY, "TokuDB Data Directory", NULL, NULL, NULL);
static MYSQL_SYSVAR_STR(version, tokudb_version, PLUGIN_VAR_READONLY, "TokuDB Version", NULL, NULL, NULL);
static MYSQL_SYSVAR_UINT(init_flags, tokudb_init_flags, PLUGIN_VAR_READONLY, "Sets TokuDB DB_ENV->open flags", NULL, NULL, tokudb_init_flags, 0, ~0U, 0);
static MYSQL_SYSVAR_UINT(write_status_frequency, tokudb_write_status_frequency, 0, "TokuDB frequency that show processlist updates status of writes", NULL, NULL, 1000, 0, ~0U, 0);
static MYSQL_SYSVAR_UINT(read_status_frequency, tokudb_read_status_frequency, 0, "TokuDB frequency that show processlist updates status of reads", NULL, NULL, 10000, 0, ~0U, 0);
static MYSQL_SYSVAR_INT(fs_reserve_percent, tokudb_fs_reserve_percent, PLUGIN_VAR_READONLY, "TokuDB file system space reserve (percent free required)", NULL, NULL, 5, 0, 100, 0);
static MYSQL_SYSVAR_STR(tmp_dir, tokudb_tmp_dir, PLUGIN_VAR_READONLY, "Tokudb Tmp Dir", NULL, NULL, NULL);
#if TOKU_INCLUDE_HANDLERTON_HANDLE_FATAL_SIGNAL
static MYSQL_SYSVAR_STR(gdb_path, tokudb_gdb_path, PLUGIN_VAR_READONLY|PLUGIN_VAR_RQCMDARG, "TokuDB path to gdb for extra debug info on fatal signal", NULL, NULL, "/usr/bin/gdb");
static MYSQL_SYSVAR_BOOL(gdb_on_fatal, tokudb_gdb_on_fatal, 0, "TokuDB enable gdb debug info on fatal signal", NULL, NULL, true);
#endif
static void tokudb_fsync_log_period_update(THD *thd, struct st_mysql_sys_var *sys_var, void *var, const void *save) {
uint32 *period = (uint32 *) var;
*period = *(const ulonglong *) save;
db_env->change_fsync_log_period(db_env, *period);
}
static MYSQL_SYSVAR_UINT(fsync_log_period, tokudb_fsync_log_period, 0, "TokuDB fsync log period", NULL, tokudb_fsync_log_period_update, 0, 0, ~0U, 0);
static struct st_mysql_sys_var *tokudb_system_variables[] = {
MYSQL_SYSVAR(cache_size),
MYSQL_SYSVAR(max_lock_memory),
MYSQL_SYSVAR(data_dir),
MYSQL_SYSVAR(log_dir),
MYSQL_SYSVAR(debug),
MYSQL_SYSVAR(commit_sync),
MYSQL_SYSVAR(lock_timeout),
MYSQL_SYSVAR(cleaner_period),
MYSQL_SYSVAR(cleaner_iterations),
MYSQL_SYSVAR(pk_insert_mode),
MYSQL_SYSVAR(load_save_space),
MYSQL_SYSVAR(disable_slow_alter),
MYSQL_SYSVAR(disable_hot_alter),
MYSQL_SYSVAR(alter_print_error),
MYSQL_SYSVAR(create_index_online),
MYSQL_SYSVAR(disable_prefetching),
MYSQL_SYSVAR(version),
MYSQL_SYSVAR(init_flags),
MYSQL_SYSVAR(checkpointing_period),
MYSQL_SYSVAR(prelock_empty),
MYSQL_SYSVAR(checkpoint_lock),
MYSQL_SYSVAR(write_status_frequency),
MYSQL_SYSVAR(read_status_frequency),
MYSQL_SYSVAR(fs_reserve_percent),
MYSQL_SYSVAR(tmp_dir),
MYSQL_SYSVAR(block_size),
MYSQL_SYSVAR(read_block_size),
MYSQL_SYSVAR(read_buf_size),
MYSQL_SYSVAR(row_format),
MYSQL_SYSVAR(directio),
MYSQL_SYSVAR(checkpoint_on_flush_logs),
#if TOKU_INCLUDE_UPSERT
MYSQL_SYSVAR(disable_slow_update),
MYSQL_SYSVAR(disable_slow_upsert),
#endif
MYSQL_SYSVAR(analyze_time),
MYSQL_SYSVAR(fsync_log_period),
#if TOKU_INCLUDE_HANDLERTON_HANDLE_FATAL_SIGNAL
MYSQL_SYSVAR(gdb_path),
MYSQL_SYSVAR(gdb_on_fatal),
#endif
MYSQL_SYSVAR(last_lock_timeout),
MYSQL_SYSVAR(lock_timeout_debug),
MYSQL_SYSVAR(loader_memory_size),
MYSQL_SYSVAR(hide_default_row_format),
MYSQL_SYSVAR(killed_time),
NULL
};
struct st_mysql_storage_engine tokudb_storage_engine = { MYSQL_HANDLERTON_INTERFACE_VERSION };
static struct st_mysql_information_schema tokudb_file_map_information_schema = { MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION };
static ST_FIELD_INFO tokudb_file_map_field_info[] = {
{"dictionary_name", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{"internal_file_name", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{"table_schema", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{"table_name", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{"table_dictionary_name", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{NULL, 0, MYSQL_TYPE_NULL, 0, 0, NULL, SKIP_OPEN_TABLE}
};
static int tokudb_file_map(TABLE *table, THD *thd) {
int error;
DB_TXN* txn = NULL;
DBC* tmp_cursor = NULL;
DBT curr_key;
DBT curr_val;
memset(&curr_key, 0, sizeof curr_key);
memset(&curr_val, 0, sizeof curr_val);
error = txn_begin(db_env, 0, &txn, DB_READ_UNCOMMITTED, thd);
if (error) {
goto cleanup;
}
error = db_env->get_cursor_for_directory(db_env, txn, &tmp_cursor);
if (error) {
goto cleanup;
}
while (error == 0) {
error = tmp_cursor->c_get(tmp_cursor, &curr_key, &curr_val, DB_NEXT);
if (!error) {
// We store the NULL terminator in the directory so it's included in the size.
// See #5789
// Recalculate and check just to be safe.
const char *dname = (const char *) curr_key.data;
size_t dname_len = strlen(dname);
assert(dname_len == curr_key.size - 1);
table->field[0]->store(dname, dname_len, system_charset_info);
const char *iname = (const char *) curr_val.data;
size_t iname_len = strlen(iname);
assert(iname_len == curr_val.size - 1);
table->field[1]->store(iname, iname_len, system_charset_info);
// denormalize the dname
const char *database_name = NULL;
size_t database_len = 0;
const char *table_name = NULL;
size_t table_len = 0;
const char *dictionary_name = NULL;
size_t dictionary_len = 0;
database_name = strchr(dname, '/');
if (database_name) {
database_name += 1;
table_name = strchr(database_name, '/');
if (table_name) {
database_len = table_name - database_name;
table_name += 1;
dictionary_name = strchr(table_name, '-');
if (dictionary_name) {
table_len = dictionary_name - table_name;
dictionary_name += 1;
dictionary_len = strlen(dictionary_name);
}
}
}
table->field[2]->store(database_name, database_len, system_charset_info);
table->field[3]->store(table_name, table_len, system_charset_info);
table->field[4]->store(dictionary_name, dictionary_len, system_charset_info);
error = schema_table_store_record(thd, table);
}
}
if (error == DB_NOTFOUND) {
error = 0;
}
cleanup:
if (tmp_cursor) {
int r = tmp_cursor->c_close(tmp_cursor);
assert(r == 0);
}
if (txn) {
commit_txn(txn, 0);
}
return error;
}
#if MYSQL_VERSION_ID >= 50600
static int tokudb_file_map_fill_table(THD *thd, TABLE_LIST *tables, Item *cond) {
#else
static int tokudb_file_map_fill_table(THD *thd, TABLE_LIST *tables, COND *cond) {
#endif
TOKUDB_DBUG_ENTER("");
int error;
TABLE *table = tables->table;
rw_rdlock(&tokudb_hton_initialized_lock);
if (!tokudb_hton_initialized) {
my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), "TokuDB");
error = -1;
} else {
error = tokudb_file_map(table, thd);
}
rw_unlock(&tokudb_hton_initialized_lock);
TOKUDB_DBUG_RETURN(error);
}
static int tokudb_file_map_init(void *p) {
ST_SCHEMA_TABLE *schema = (ST_SCHEMA_TABLE *) p;
schema->fields_info = tokudb_file_map_field_info;
schema->fill_table = tokudb_file_map_fill_table;
return 0;
}
static int tokudb_file_map_done(void *p) {
return 0;
}
static struct st_mysql_information_schema tokudb_fractal_tree_info_information_schema = { MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION };
static ST_FIELD_INFO tokudb_fractal_tree_info_field_info[] = {
{"dictionary_name", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{"internal_file_name", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{"bt_num_blocks_allocated", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
{"bt_num_blocks_in_use", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
{"bt_size_allocated", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
{"bt_size_in_use", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
{NULL, 0, MYSQL_TYPE_NULL, 0, 0, NULL, SKIP_OPEN_TABLE}
};
static int tokudb_report_fractal_tree_info_for_db(const DBT *dname, const DBT *iname, TABLE *table, THD *thd) {
int error;
DB *db;
uint64_t bt_num_blocks_allocated;
uint64_t bt_num_blocks_in_use;
uint64_t bt_size_allocated;
uint64_t bt_size_in_use;
error = db_create(&db, db_env, 0);
if (error) {
goto exit;
}
error = db->open(db, NULL, (char *)dname->data, NULL, DB_BTREE, 0, 0666);
if (error) {
goto exit;
}
error = db->get_fractal_tree_info64(db,
&bt_num_blocks_allocated, &bt_num_blocks_in_use,
&bt_size_allocated, &bt_size_in_use);
{
int close_error = db->close(db, 0);
if (!error) {
error = close_error;
}
}
if (error) {
goto exit;
}
// We store the NULL terminator in the directory so it's included in the size.
// See #5789
// Recalculate and check just to be safe.
{
size_t dname_len = strlen((const char *)dname->data);
size_t iname_len = strlen((const char *)iname->data);
assert(dname_len == dname->size - 1);
assert(iname_len == iname->size - 1);
table->field[0]->store(
(char *)dname->data,
dname_len,
system_charset_info
);
table->field[1]->store(
(char *)iname->data,
iname_len,
system_charset_info
);
}
table->field[2]->store(bt_num_blocks_allocated, false);
table->field[3]->store(bt_num_blocks_in_use, false);
table->field[4]->store(bt_size_allocated, false);
table->field[5]->store(bt_size_in_use, false);
error = schema_table_store_record(thd, table);
exit:
return error;
}
static int tokudb_fractal_tree_info(TABLE *table, THD *thd) {
int error;
DB_TXN* txn = NULL;
DBC* tmp_cursor = NULL;
DBT curr_key;
DBT curr_val;
memset(&curr_key, 0, sizeof curr_key);
memset(&curr_val, 0, sizeof curr_val);
error = txn_begin(db_env, 0, &txn, DB_READ_UNCOMMITTED, thd);
if (error) {
goto cleanup;
}
error = db_env->get_cursor_for_directory(db_env, txn, &tmp_cursor);
if (error) {
goto cleanup;
}
while (error == 0) {
error = tmp_cursor->c_get(
tmp_cursor,
&curr_key,
&curr_val,
DB_NEXT
);
if (!error) {
error = tokudb_report_fractal_tree_info_for_db(&curr_key, &curr_val, table, thd);
}
}
if (error == DB_NOTFOUND) {
error = 0;
}
cleanup:
if (tmp_cursor) {
int r = tmp_cursor->c_close(tmp_cursor);
assert(r == 0);
}
if (txn) {
commit_txn(txn, 0);
}
return error;
}
#if MYSQL_VERSION_ID >= 50600
static int tokudb_fractal_tree_info_fill_table(THD *thd, TABLE_LIST *tables, Item *cond) {
#else
static int tokudb_fractal_tree_info_fill_table(THD *thd, TABLE_LIST *tables, COND *cond) {
#endif
TOKUDB_DBUG_ENTER("");
int error;
TABLE *table = tables->table;
// 3938: Get a read lock on the status flag, since we must
// read it before safely proceeding
rw_rdlock(&tokudb_hton_initialized_lock);
if (!tokudb_hton_initialized) {
my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), "TokuDB");
error = -1;
} else {
error = tokudb_fractal_tree_info(table, thd);
}
//3938: unlock the status flag lock
rw_unlock(&tokudb_hton_initialized_lock);
TOKUDB_DBUG_RETURN(error);
}
static int tokudb_fractal_tree_info_init(void *p) {
ST_SCHEMA_TABLE *schema = (ST_SCHEMA_TABLE *) p;
schema->fields_info = tokudb_fractal_tree_info_field_info;
schema->fill_table = tokudb_fractal_tree_info_fill_table;
return 0;
}
static int tokudb_fractal_tree_info_done(void *p) {
return 0;
}
static struct st_mysql_information_schema tokudb_fractal_tree_block_map_information_schema = { MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION };
static ST_FIELD_INFO tokudb_fractal_tree_block_map_field_info[] = {
{"dictionary_name", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{"internal_file_name", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{"checkpoint_count", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
{"blocknum", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
{"offset", 0, MYSQL_TYPE_LONGLONG, 0, MY_I_S_MAYBE_NULL, NULL, SKIP_OPEN_TABLE },
{"size", 0, MYSQL_TYPE_LONGLONG, 0, MY_I_S_MAYBE_NULL, NULL, SKIP_OPEN_TABLE },
{NULL, 0, MYSQL_TYPE_NULL, 0, 0, NULL, SKIP_OPEN_TABLE}
};
struct tokudb_report_fractal_tree_block_map_iterator_extra {
int64_t num_rows;
int64_t i;
uint64_t *checkpoint_counts;
int64_t *blocknums;
int64_t *diskoffs;
int64_t *sizes;
};
// This iterator is called while holding the blocktable lock. We should be as quick as possible.
// We don't want to do one call to get the number of rows, release the blocktable lock, and then do another call to get all the rows because the number of rows may change if we don't hold the lock.
// As a compromise, we'll do some mallocs inside the lock on the first call, but everything else should be fast.
static int tokudb_report_fractal_tree_block_map_iterator(uint64_t checkpoint_count,
int64_t num_rows,
int64_t blocknum,
int64_t diskoff,
int64_t size,
void *iter_extra) {
struct tokudb_report_fractal_tree_block_map_iterator_extra *e = static_cast<struct tokudb_report_fractal_tree_block_map_iterator_extra *>(iter_extra);
assert(num_rows > 0);
if (e->num_rows == 0) {
e->checkpoint_counts = (uint64_t *) tokudb_my_malloc(num_rows * (sizeof *e->checkpoint_counts), MYF(MY_WME|MY_ZEROFILL|MY_FAE));
e->blocknums = (int64_t *) tokudb_my_malloc(num_rows * (sizeof *e->blocknums), MYF(MY_WME|MY_ZEROFILL|MY_FAE));
e->diskoffs = (int64_t *) tokudb_my_malloc(num_rows * (sizeof *e->diskoffs), MYF(MY_WME|MY_ZEROFILL|MY_FAE));
e->sizes = (int64_t *) tokudb_my_malloc(num_rows * (sizeof *e->sizes), MYF(MY_WME|MY_ZEROFILL|MY_FAE));
e->num_rows = num_rows;
}
e->checkpoint_counts[e->i] = checkpoint_count;
e->blocknums[e->i] = blocknum;
e->diskoffs[e->i] = diskoff;
e->sizes[e->i] = size;
++(e->i);
return 0;
}
static int tokudb_report_fractal_tree_block_map_for_db(const DBT *dname, const DBT *iname, TABLE *table, THD *thd) {
int error;
DB *db;
struct tokudb_report_fractal_tree_block_map_iterator_extra e = {}; // avoid struct initializers so that we can compile with older gcc versions
error = db_create(&db, db_env, 0);
if (error) {
goto exit;
}
error = db->open(db, NULL, (char *)dname->data, NULL, DB_BTREE, 0, 0666);
if (error) {
goto exit;
}
error = db->iterate_fractal_tree_block_map(db, tokudb_report_fractal_tree_block_map_iterator, &e);
{
int close_error = db->close(db, 0);
if (!error) {
error = close_error;
}
}
if (error) {
goto exit;
}
// If not, we should have gotten an error and skipped this section of code
assert(e.i == e.num_rows);
for (int64_t i = 0; error == 0 && i < e.num_rows; ++i) {
// We store the NULL terminator in the directory so it's included in the size.
// See #5789
// Recalculate and check just to be safe.
size_t dname_len = strlen((const char *)dname->data);
size_t iname_len = strlen((const char *)iname->data);
assert(dname_len == dname->size - 1);
assert(iname_len == iname->size - 1);
table->field[0]->store(
(char *)dname->data,
dname_len,
system_charset_info
);
table->field[1]->store(
(char *)iname->data,
iname_len,
system_charset_info
);
table->field[2]->store(e.checkpoint_counts[i], false);
table->field[3]->store(e.blocknums[i], false);
static const int64_t freelist_null = -1;
static const int64_t diskoff_unused = -2;
if (e.diskoffs[i] == diskoff_unused || e.diskoffs[i] == freelist_null) {
table->field[4]->set_null();
} else {
table->field[4]->set_notnull();
table->field[4]->store(e.diskoffs[i], false);
}
static const int64_t size_is_free = -1;
if (e.sizes[i] == size_is_free) {
table->field[5]->set_null();
} else {
table->field[5]->set_notnull();
table->field[5]->store(e.sizes[i], false);
}
error = schema_table_store_record(thd, table);
}
exit:
if (e.checkpoint_counts != NULL) {
tokudb_my_free(e.checkpoint_counts);
e.checkpoint_counts = NULL;
}
if (e.blocknums != NULL) {
tokudb_my_free(e.blocknums);
e.blocknums = NULL;
}
if (e.diskoffs != NULL) {
tokudb_my_free(e.diskoffs);
e.diskoffs = NULL;
}
if (e.sizes != NULL) {
tokudb_my_free(e.sizes);
e.sizes = NULL;
}
return error;
}
static int tokudb_fractal_tree_block_map(TABLE *table, THD *thd) {
int error;
DB_TXN* txn = NULL;
DBC* tmp_cursor = NULL;
DBT curr_key;
DBT curr_val;
memset(&curr_key, 0, sizeof curr_key);
memset(&curr_val, 0, sizeof curr_val);
error = txn_begin(db_env, 0, &txn, DB_READ_UNCOMMITTED, thd);
if (error) {
goto cleanup;
}
error = db_env->get_cursor_for_directory(db_env, txn, &tmp_cursor);
if (error) {
goto cleanup;
}
while (error == 0) {
error = tmp_cursor->c_get(
tmp_cursor,
&curr_key,
&curr_val,
DB_NEXT
);
if (!error) {
error = tokudb_report_fractal_tree_block_map_for_db(&curr_key, &curr_val, table, thd);
}
}
if (error == DB_NOTFOUND) {
error = 0;
}
cleanup:
if (tmp_cursor) {
int r = tmp_cursor->c_close(tmp_cursor);
assert(r == 0);
}
if (txn) {
commit_txn(txn, 0);
}
return error;
}
#if MYSQL_VERSION_ID >= 50600
static int tokudb_fractal_tree_block_map_fill_table(THD *thd, TABLE_LIST *tables, Item *cond) {
#else
static int tokudb_fractal_tree_block_map_fill_table(THD *thd, TABLE_LIST *tables, COND *cond) {
#endif
TOKUDB_DBUG_ENTER("");
int error;
TABLE *table = tables->table;
// 3938: Get a read lock on the status flag, since we must
// read it before safely proceeding
rw_rdlock(&tokudb_hton_initialized_lock);
if (!tokudb_hton_initialized) {
my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), "TokuDB");
error = -1;
} else {
error = tokudb_fractal_tree_block_map(table, thd);
}
//3938: unlock the status flag lock
rw_unlock(&tokudb_hton_initialized_lock);
TOKUDB_DBUG_RETURN(error);
}
static int tokudb_fractal_tree_block_map_init(void *p) {
ST_SCHEMA_TABLE *schema = (ST_SCHEMA_TABLE *) p;
schema->fields_info = tokudb_fractal_tree_block_map_field_info;
schema->fill_table = tokudb_fractal_tree_block_map_fill_table;
return 0;
}
static int tokudb_fractal_tree_block_map_done(void *p) {
return 0;
}
static void tokudb_pretty_key(const DB *db, const DBT *key, const char *default_key, String *out) {
if (key->data == NULL) {
out->append(default_key);
} else {
bool do_hexdump = true;
if (do_hexdump) {
// hexdump the key
const unsigned char *data = reinterpret_cast<const unsigned char *>(key->data);
for (size_t i = 0; i < key->size; i++) {
char str[3];
snprintf(str, sizeof str, "%2.2x", data[i]);
out->append(str);
}
}
}
}
static void tokudb_pretty_left_key(const DB *db, const DBT *key, String *out) {
tokudb_pretty_key(db, key, "-infinity", out);
}
static void tokudb_pretty_right_key(const DB *db, const DBT *key, String *out) {
tokudb_pretty_key(db, key, "+infinity", out);
}
static const char *tokudb_get_index_name(DB *db) {
if (db != NULL) {
return db->get_dname(db);
} else {
return "$ydb_internal";
}
}
static int tokudb_equal_key(const DBT *left_key, const DBT *right_key) {
if (left_key->data == NULL || right_key->data == NULL || left_key->size != right_key->size)
return 0;
else
return memcmp(left_key->data, right_key->data, left_key->size) == 0;
}
static void tokudb_lock_timeout_callback(DB *db, uint64_t requesting_txnid, const DBT *left_key, const DBT *right_key, uint64_t blocking_txnid) {
THD *thd = current_thd;
if (!thd)
return;
ulong lock_timeout_debug = THDVAR(thd, lock_timeout_debug);
if (lock_timeout_debug != 0) {
// generate a JSON document with the lock timeout info
String log_str;
log_str.append("{");
log_str.append("\"mysql_thread_id\":");
log_str.append_ulonglong(thd->thread_id);
log_str.append(", \"dbname\":");
log_str.append("\""); log_str.append(tokudb_get_index_name(db)); log_str.append("\"");
log_str.append(", \"requesting_txnid\":");
log_str.append_ulonglong(requesting_txnid);
log_str.append(", \"blocking_txnid\":");
log_str.append_ulonglong(blocking_txnid);
if (tokudb_equal_key(left_key, right_key)) {
String key_str;
tokudb_pretty_key(db, left_key, "?", &key_str);
log_str.append(", \"key\":");
log_str.append("\""); log_str.append(key_str); log_str.append("\"");
} else {
String left_str;
tokudb_pretty_left_key(db, left_key, &left_str);
log_str.append(", \"key_left\":");
log_str.append("\""); log_str.append(left_str); log_str.append("\"");
String right_str;
tokudb_pretty_right_key(db, right_key, &right_str);
log_str.append(", \"key_right\":");
log_str.append("\""); log_str.append(right_str); log_str.append("\"");
}
log_str.append("}");
// set last_lock_timeout
if (lock_timeout_debug & 1) {
char *old_lock_timeout = THDVAR(thd, last_lock_timeout);
char *new_lock_timeout = tokudb_my_strdup(log_str.c_ptr(), MY_FAE);
THDVAR(thd, last_lock_timeout) = new_lock_timeout;
tokudb_my_free(old_lock_timeout);
#if TOKU_THDVAR_MEMALLOC_BUG
if (0) TOKUDB_TRACE("thd %p %p %p", thd, old_lock_timeout, new_lock_timeout);
tokudb_pthread_mutex_lock(&tokudb_map_mutex);
struct tokudb_map_pair old_key = { thd, old_lock_timeout };
tree_delete(&tokudb_map, &old_key, sizeof old_key, NULL);
struct tokudb_map_pair new_key = { thd, new_lock_timeout };
tree_insert(&tokudb_map, &new_key, sizeof new_key, NULL);
tokudb_pthread_mutex_unlock(&tokudb_map_mutex);
#endif
}
// dump to stderr
if (lock_timeout_debug & 2) {
TOKUDB_TRACE("%s", log_str.c_ptr());
}
}
}
static struct st_mysql_information_schema tokudb_trx_information_schema = { MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION };
static ST_FIELD_INFO tokudb_trx_field_info[] = {
{"trx_id", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
{"trx_mysql_thread_id", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
{NULL, 0, MYSQL_TYPE_NULL, 0, 0, NULL, SKIP_OPEN_TABLE}
};
struct tokudb_trx_extra {
THD *thd;
TABLE *table;
};
static int tokudb_trx_callback(uint64_t txn_id, uint64_t client_id, iterate_row_locks_callback iterate_locks, void *locks_extra, void *extra) {
struct tokudb_trx_extra *e = reinterpret_cast<struct tokudb_trx_extra *>(extra);
THD *thd = e->thd;
TABLE *table = e->table;
table->field[0]->store(txn_id, false);
table->field[1]->store(client_id, false);
int error = schema_table_store_record(thd, table);
return error;
}
#if MYSQL_VERSION_ID >= 50600
static int tokudb_trx_fill_table(THD *thd, TABLE_LIST *tables, Item *cond) {
#else
static int tokudb_trx_fill_table(THD *thd, TABLE_LIST *tables, COND *cond) {
#endif
TOKUDB_DBUG_ENTER("");
int error;
rw_rdlock(&tokudb_hton_initialized_lock);
if (!tokudb_hton_initialized) {
my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), "TokuDB");
error = -1;
} else {
struct tokudb_trx_extra e = { thd, tables->table };
error = db_env->iterate_live_transactions(db_env, tokudb_trx_callback, &e);
}
rw_unlock(&tokudb_hton_initialized_lock);
TOKUDB_DBUG_RETURN(error);
}
static int tokudb_trx_init(void *p) {
ST_SCHEMA_TABLE *schema = (ST_SCHEMA_TABLE *) p;
schema->fields_info = tokudb_trx_field_info;
schema->fill_table = tokudb_trx_fill_table;
return 0;
}
static int tokudb_trx_done(void *p) {
return 0;
}
static struct st_mysql_information_schema tokudb_lock_waits_information_schema = { MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION };
static ST_FIELD_INFO tokudb_lock_waits_field_info[] = {
{"requesting_trx_id", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
{"blocking_trx_id", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
{"lock_waits_dname", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{"lock_waits_key_left", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{"lock_waits_key_right", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{"lock_waits_start_time", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
{NULL, 0, MYSQL_TYPE_NULL, 0, 0, NULL, SKIP_OPEN_TABLE}
};
struct tokudb_lock_waits_extra {
THD *thd;
TABLE *table;
};
static int tokudb_lock_waits_callback(DB *db, uint64_t requesting_txnid, const DBT *left_key, const DBT *right_key,
uint64_t blocking_txnid, uint64_t start_time, void *extra) {
struct tokudb_lock_waits_extra *e = reinterpret_cast<struct tokudb_lock_waits_extra *>(extra);
THD *thd = e->thd;
TABLE *table = e->table;
table->field[0]->store(requesting_txnid, false);
table->field[1]->store(blocking_txnid, false);
const char *dname = tokudb_get_index_name(db);
size_t dname_length = strlen(dname);
table->field[2]->store(dname, dname_length, system_charset_info);
String left_str;
tokudb_pretty_left_key(db, left_key, &left_str);
table->field[3]->store(left_str.ptr(), left_str.length(), system_charset_info);
String right_str;
tokudb_pretty_right_key(db, right_key, &right_str);
table->field[4]->store(right_str.ptr(), right_str.length(), system_charset_info);
table->field[5]->store(start_time, false);
int error = schema_table_store_record(thd, table);
return error;
}
#if MYSQL_VERSION_ID >= 50600
static int tokudb_lock_waits_fill_table(THD *thd, TABLE_LIST *tables, Item *cond) {
#else
static int tokudb_lock_waits_fill_table(THD *thd, TABLE_LIST *tables, COND *cond) {
#endif
TOKUDB_DBUG_ENTER("");
int error;
rw_rdlock(&tokudb_hton_initialized_lock);
if (!tokudb_hton_initialized) {
my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), "TokuDB");
error = -1;
} else {
struct tokudb_lock_waits_extra e = { thd, tables->table };
error = db_env->iterate_pending_lock_requests(db_env, tokudb_lock_waits_callback, &e);
}
rw_unlock(&tokudb_hton_initialized_lock);
TOKUDB_DBUG_RETURN(error);
}
static int tokudb_lock_waits_init(void *p) {
ST_SCHEMA_TABLE *schema = (ST_SCHEMA_TABLE *) p;
schema->fields_info = tokudb_lock_waits_field_info;
schema->fill_table = tokudb_lock_waits_fill_table;
return 0;
}
static int tokudb_lock_waits_done(void *p) {
return 0;
}
static struct st_mysql_information_schema tokudb_locks_information_schema = { MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION };
static ST_FIELD_INFO tokudb_locks_field_info[] = {
{"locks_trx_id", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
{"locks_mysql_thread_id", 0, MYSQL_TYPE_LONGLONG, 0, 0, NULL, SKIP_OPEN_TABLE },
{"locks_dname", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{"locks_key_left", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{"locks_key_right", 256, MYSQL_TYPE_STRING, 0, 0, NULL, SKIP_OPEN_TABLE },
{NULL, 0, MYSQL_TYPE_NULL, 0, 0, NULL, SKIP_OPEN_TABLE}
};
struct tokudb_locks_extra {
THD *thd;
TABLE *table;
};
static int tokudb_locks_callback(uint64_t txn_id, uint64_t client_id, iterate_row_locks_callback iterate_locks, void *locks_extra, void *extra) {
struct tokudb_locks_extra *e = reinterpret_cast<struct tokudb_locks_extra *>(extra);
THD *thd = e->thd;
TABLE *table = e->table;
int error = 0;
DB *db;
DBT left_key, right_key;
while (error == 0 && iterate_locks(&db, &left_key, &right_key, locks_extra) == 0) {
table->field[0]->store(txn_id, false);
table->field[1]->store(client_id, false);
const char *dname = tokudb_get_index_name(db);
size_t dname_length = strlen(dname);
table->field[2]->store(dname, dname_length, system_charset_info);
String left_str;
tokudb_pretty_left_key(db, &left_key, &left_str);
table->field[3]->store(left_str.ptr(), left_str.length(), system_charset_info);
String right_str;
tokudb_pretty_right_key(db, &right_key, &right_str);
table->field[4]->store(right_str.ptr(), right_str.length(), system_charset_info);
error = schema_table_store_record(thd, table);
}
return error;
}
#if MYSQL_VERSION_ID >= 50600
static int tokudb_locks_fill_table(THD *thd, TABLE_LIST *tables, Item *cond) {
#else
static int tokudb_locks_fill_table(THD *thd, TABLE_LIST *tables, COND *cond) {
#endif
TOKUDB_DBUG_ENTER("");
int error;
rw_rdlock(&tokudb_hton_initialized_lock);
if (!tokudb_hton_initialized) {
my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), "TokuDB");
error = -1;
} else {
struct tokudb_locks_extra e = { thd, tables->table };
error = db_env->iterate_live_transactions(db_env, tokudb_locks_callback, &e);
}
rw_unlock(&tokudb_hton_initialized_lock);
TOKUDB_DBUG_RETURN(error);
}
static int tokudb_locks_init(void *p) {
ST_SCHEMA_TABLE *schema = (ST_SCHEMA_TABLE *) p;
schema->fields_info = tokudb_locks_field_info;
schema->fill_table = tokudb_locks_fill_table;
return 0;
}
static int tokudb_locks_done(void *p) {
return 0;
}
enum { TOKUDB_PLUGIN_VERSION = 0x0400 };
#define TOKUDB_PLUGIN_VERSION_STR "1024"
// Retrieves variables for information_schema.global_status.
// Names (columnname) are automatically converted to upper case, and prefixed with "TOKUDB_"
static int show_tokudb_vars(THD *thd, SHOW_VAR *var, char *buff) {
TOKUDB_DBUG_ENTER("");
int error;
uint64_t panic;
const int panic_string_len = 1024;
char panic_string[panic_string_len] = {'\0'};
fs_redzone_state redzone_state;
uint64_t num_rows;
error = db_env->get_engine_status (db_env, toku_global_status_rows, toku_global_status_max_rows, &num_rows, &redzone_state, &panic, panic_string, panic_string_len, TOKU_GLOBAL_STATUS);
//TODO: Maybe do something with the panic output?
if (error == 0) {
assert(num_rows <= toku_global_status_max_rows);
//TODO: Maybe enable some of the items here: (copied from engine status
//TODO: (optionally) add redzone state, panic, panic string, etc. Right now it's being ignored.
for (uint64_t row = 0; row < num_rows; row++) {
SHOW_VAR &status_var = toku_global_status_variables[row];
TOKU_ENGINE_STATUS_ROW_S &status_row = toku_global_status_rows[row];
status_var.name = status_row.columnname;
switch (status_row.type) {
case FS_STATE:
case UINT64:
status_var.type = SHOW_LONGLONG;
status_var.value = (char*)&status_row.value.num;
break;
case CHARSTR:
status_var.type = SHOW_CHAR;
status_var.value = (char*)status_row.value.str;
break;
case UNIXTIME:
{
status_var.type = SHOW_CHAR;
time_t t = status_row.value.num;
char tbuf[26];
// Reuse the memory in status_row. (It belongs to us).
snprintf(status_row.value.datebuf, sizeof(status_row.value.datebuf), "%.24s", ctime_r(&t, tbuf));
status_var.value = (char*)&status_row.value.datebuf[0];
}
break;
case TOKUTIME:
{
status_var.type = SHOW_DOUBLE;
double t = tokutime_to_seconds(status_row.value.num);
// Reuse the memory in status_row. (It belongs to us).
status_row.value.dnum = t;
status_var.value = (char*)&status_row.value.dnum;
}
break;
case PARCOUNT:
{
status_var.type = SHOW_LONGLONG;
uint64_t v = read_partitioned_counter(status_row.value.parcount);
// Reuse the memory in status_row. (It belongs to us).
status_row.value.num = v;
status_var.value = (char*)&status_row.value.num;
}
break;
default:
{
status_var.type = SHOW_CHAR;
// Reuse the memory in status_row.datebuf. (It belongs to us).
// UNKNOWN TYPE: %d fits in 26 bytes (sizeof datebuf) for any integer.
snprintf(status_row.value.datebuf, sizeof(status_row.value.datebuf), "UNKNOWN TYPE: %d", status_row.type);
status_var.value = (char*)&status_row.value.datebuf[0];
}
break;
}
}
// Sentinel value at end.
toku_global_status_variables[num_rows].type = SHOW_LONG;
toku_global_status_variables[num_rows].value = (char*)NullS;
toku_global_status_variables[num_rows].name = (char*)NullS;
var->type= SHOW_ARRAY;
var->value= (char *) toku_global_status_variables;
}
if (error) { my_errno = error; }
TOKUDB_DBUG_RETURN(error);
}
static SHOW_VAR toku_global_status_variables_export[]= {
{"Tokudb", (char*)&show_tokudb_vars, SHOW_FUNC},
{NullS, NullS, SHOW_LONG}
};
mysql_declare_plugin(tokudb)
{
MYSQL_STORAGE_ENGINE_PLUGIN,
&tokudb_storage_engine,
tokudb_hton_name,
"Tokutek Inc",
"Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
PLUGIN_LICENSE_GPL,
tokudb_init_func, /* plugin init */
tokudb_done_func, /* plugin deinit */
TOKUDB_PLUGIN_VERSION, /* 4.0.0 */
toku_global_status_variables_export, /* status variables */
tokudb_system_variables, /* system variables */
NULL, /* config options */
#if MYSQL_VERSION_ID >= 50521
0, /* flags */
#endif
},
{
MYSQL_INFORMATION_SCHEMA_PLUGIN,
&tokudb_trx_information_schema,
"TokuDB_trx",
"Tokutek Inc",
"Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
PLUGIN_LICENSE_GPL,
tokudb_trx_init, /* plugin init */
tokudb_trx_done, /* plugin deinit */
TOKUDB_PLUGIN_VERSION, /* 4.0.0 */
NULL, /* status variables */
NULL, /* system variables */
NULL, /* config options */
#if MYSQL_VERSION_ID >= 50521
0, /* flags */
#endif
},
{
MYSQL_INFORMATION_SCHEMA_PLUGIN,
&tokudb_lock_waits_information_schema,
"TokuDB_lock_waits",
"Tokutek Inc",
"Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
PLUGIN_LICENSE_GPL,
tokudb_lock_waits_init, /* plugin init */
tokudb_lock_waits_done, /* plugin deinit */
TOKUDB_PLUGIN_VERSION, /* 4.0.0 */
NULL, /* status variables */
NULL, /* system variables */
NULL, /* config options */
#if MYSQL_VERSION_ID >= 50521
0, /* flags */
#endif
},
{
MYSQL_INFORMATION_SCHEMA_PLUGIN,
&tokudb_locks_information_schema,
"TokuDB_locks",
"Tokutek Inc",
"Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
PLUGIN_LICENSE_GPL,
tokudb_locks_init, /* plugin init */
tokudb_locks_done, /* plugin deinit */
TOKUDB_PLUGIN_VERSION, /* 4.0.0 */
NULL, /* status variables */
NULL, /* system variables */
NULL, /* config options */
#if MYSQL_VERSION_ID >= 50521
0, /* flags */
#endif
},
{
MYSQL_INFORMATION_SCHEMA_PLUGIN,
&tokudb_file_map_information_schema,
"TokuDB_file_map",
"Tokutek Inc",
"Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
PLUGIN_LICENSE_GPL,
tokudb_file_map_init, /* plugin init */
tokudb_file_map_done, /* plugin deinit */
TOKUDB_PLUGIN_VERSION, /* 4.0.0 */
NULL, /* status variables */
NULL, /* system variables */
NULL, /* config options */
#if MYSQL_VERSION_ID >= 50521
0, /* flags */
#endif
},
{
MYSQL_INFORMATION_SCHEMA_PLUGIN,
&tokudb_fractal_tree_info_information_schema,
"TokuDB_fractal_tree_info",
"Tokutek Inc",
"Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
PLUGIN_LICENSE_GPL,
tokudb_fractal_tree_info_init, /* plugin init */
tokudb_fractal_tree_info_done, /* plugin deinit */
TOKUDB_PLUGIN_VERSION, /* 4.0.0 */
NULL, /* status variables */
NULL, /* system variables */
NULL, /* config options */
#if MYSQL_VERSION_ID >= 50521
0, /* flags */
#endif
},
{
MYSQL_INFORMATION_SCHEMA_PLUGIN,
&tokudb_fractal_tree_block_map_information_schema,
"TokuDB_fractal_tree_block_map",
"Tokutek Inc",
"Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
PLUGIN_LICENSE_GPL,
tokudb_fractal_tree_block_map_init, /* plugin init */
tokudb_fractal_tree_block_map_done, /* plugin deinit */
TOKUDB_PLUGIN_VERSION, /* 4.0.0 */
NULL, /* status variables */
NULL, /* system variables */
NULL, /* config options */
#if MYSQL_VERSION_ID >= 50521
0, /* flags */
#endif
}
mysql_declare_plugin_end;
#ifdef MARIA_PLUGIN_INTERFACE_VERSION
maria_declare_plugin(tokudb)
{
MYSQL_STORAGE_ENGINE_PLUGIN,
&tokudb_storage_engine,
tokudb_hton_name,
"Tokutek Inc",
"Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
PLUGIN_LICENSE_GPL,
tokudb_init_func, /* plugin init */
tokudb_done_func, /* plugin deinit */
TOKUDB_PLUGIN_VERSION, /* 4.0.0 */
toku_global_status_variables_export, /* status variables */
tokudb_system_variables, /* system variables */
TOKUDB_PLUGIN_VERSION_STR, /* string version */
MariaDB_PLUGIN_MATURITY_GAMMA /* maturity */
},
{
MYSQL_INFORMATION_SCHEMA_PLUGIN,
&tokudb_trx_information_schema,
"TokuDB_trx",
"Tokutek Inc",
"Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
PLUGIN_LICENSE_GPL,
tokudb_trx_init, /* plugin init */
tokudb_trx_done, /* plugin deinit */
TOKUDB_PLUGIN_VERSION, /* 4.0.0 */
NULL, /* status variables */
NULL, /* system variables */
TOKUDB_PLUGIN_VERSION_STR, /* string version */
MariaDB_PLUGIN_MATURITY_GAMMA /* maturity */
},
{
MYSQL_INFORMATION_SCHEMA_PLUGIN,
&tokudb_lock_waits_information_schema,
"TokuDB_lock_waits",
"Tokutek Inc",
"Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
PLUGIN_LICENSE_GPL,
tokudb_lock_waits_init, /* plugin init */
tokudb_lock_waits_done, /* plugin deinit */
TOKUDB_PLUGIN_VERSION, /* 4.0.0 */
NULL, /* status variables */
NULL, /* system variables */
TOKUDB_PLUGIN_VERSION_STR, /* string version */
MariaDB_PLUGIN_MATURITY_GAMMA /* maturity */
},
{
MYSQL_INFORMATION_SCHEMA_PLUGIN,
&tokudb_locks_information_schema,
"TokuDB_locks",
"Tokutek Inc",
"Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
PLUGIN_LICENSE_GPL,
tokudb_locks_init, /* plugin init */
tokudb_locks_done, /* plugin deinit */
TOKUDB_PLUGIN_VERSION, /* 4.0.0 */
NULL, /* status variables */
NULL, /* system variables */
TOKUDB_PLUGIN_VERSION_STR, /* string version */
MariaDB_PLUGIN_MATURITY_GAMMA /* maturity */
},
{
MYSQL_INFORMATION_SCHEMA_PLUGIN,
&tokudb_file_map_information_schema,
"TokuDB_file_map",
"Tokutek Inc",
"Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
PLUGIN_LICENSE_GPL,
tokudb_file_map_init, /* plugin init */
tokudb_file_map_done, /* plugin deinit */
TOKUDB_PLUGIN_VERSION, /* 4.0.0 */
NULL, /* status variables */
NULL, /* system variables */
TOKUDB_PLUGIN_VERSION_STR, /* string version */
MariaDB_PLUGIN_MATURITY_GAMMA /* maturity */
},
{
MYSQL_INFORMATION_SCHEMA_PLUGIN,
&tokudb_fractal_tree_info_information_schema,
"TokuDB_fractal_tree_info",
"Tokutek Inc",
"Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
PLUGIN_LICENSE_GPL,
tokudb_fractal_tree_info_init, /* plugin init */
tokudb_fractal_tree_info_done, /* plugin deinit */
TOKUDB_PLUGIN_VERSION, /* 4.0.0 */
NULL, /* status variables */
NULL, /* system variables */
TOKUDB_PLUGIN_VERSION_STR, /* string version */
MariaDB_PLUGIN_MATURITY_GAMMA /* maturity */
},
{
MYSQL_INFORMATION_SCHEMA_PLUGIN,
&tokudb_fractal_tree_block_map_information_schema,
"TokuDB_fractal_tree_block_map",
"Tokutek Inc",
"Tokutek TokuDB Storage Engine with Fractal Tree(tm) Technology",
PLUGIN_LICENSE_GPL,
tokudb_fractal_tree_block_map_init, /* plugin init */
tokudb_fractal_tree_block_map_done, /* plugin deinit */
TOKUDB_PLUGIN_VERSION, /* 4.0.0 */
NULL, /* status variables */
NULL, /* system variables */
TOKUDB_PLUGIN_VERSION_STR, /* string version */
MariaDB_PLUGIN_MATURITY_GAMMA /* maturity */
}
maria_declare_plugin_end;
#endif
| SunguckLee/MariaDB | storage/tokudb/hatoku_hton.cc | C++ | gpl-2.0 | 90,471 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.3 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2013 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2013
* $Id$
*
*/
/**
* This class contains all the function that are called using AJAX
*/
class CRM_Core_Page_AJAX_Location {
/**
* FIXME: we should make this method like getLocBlock() OR use the same method and
* remove this one.
*
* Function to obtain the location of given contact-id.
* This method is used by on-behalf-of form to dynamically generate poulate the
* location field values for selected permissioned contact.
*/
function getPermissionedLocation() {
$cid = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
if ($_GET['ufId']) {
$ufId = CRM_Utils_Type::escape($_GET['ufId'], 'Integer');
}
elseif ($_GET['relContact']) {
$relContact = CRM_Utils_Type::escape($_GET['relContact'], 'Integer');
}
$values = array();
$entityBlock = array('contact_id' => $cid);
$location = CRM_Core_BAO_Location::getValues($entityBlock);
$config = CRM_Core_Config::singleton();
$addressSequence = array_flip($config->addressSequence());
if ($relContact) {
$elements = array(
"phone_1_phone" =>
$location['phone'][1]['phone'],
"email_1_email" =>
$location['email'][1]['email'],
);
if (array_key_exists('street_address', $addressSequence)) {
$elements["address_1_street_address"] = $location['address'][1]['street_address'];
}
if (array_key_exists('supplemental_address_1', $addressSequence)) {
$elements['address_1_supplemental_address_1'] = $location['address'][1]['supplemental_address_1'];
}
if (array_key_exists('supplemental_address_2', $addressSequence)) {
$elements['address_1_supplemental_address_2'] = $location['address'][1]['supplemental_address_2'];
}
if (array_key_exists('city', $addressSequence)) {
$elements['address_1_city'] = $location['address'][1]['city'];
}
if (array_key_exists('postal_code', $addressSequence)) {
$elements['address_1_postal_code'] = $location['address'][1]['postal_code'];
$elements['address_1_postal_code_suffix'] = $location['address'][1]['postal_code_suffix'];
}
if (array_key_exists('country', $addressSequence)) {
$elements['address_1_country_id'] = $location['address'][1]['country_id'];
}
if (array_key_exists('state_province', $addressSequence)) {
$elements['address_1_state_province_id'] = $location['address'][1]['state_province_id'];
}
}
else {
$profileFields = CRM_Core_BAO_UFGroup::getFields($ufId, FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE,
NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL
);
$website = CRM_Core_BAO_Website::getValues($entityBlock, $values);
foreach ($location as $fld => $values) {
if (is_array($values) && !empty($values)) {
$locType = $values[1]['location_type_id'];
if ($fld == 'email') {
$elements["onbehalf_{$fld}-{$locType}"] = array(
'type' => 'Text',
'value' => $location[$fld][1][$fld],
);
unset($profileFields["{$fld}-{$locType}"]);
}
elseif ($fld == 'phone') {
$phoneTypeId = $values[1]['phone_type_id'];
$elements["onbehalf_{$fld}-{$locType}-{$phoneTypeId}"] = array(
'type' => 'Text',
'value' => $location[$fld][1][$fld],
);
unset($profileFields["{$fld}-{$locType}-{$phoneTypeId}"]);
}
elseif ($fld == 'im') {
$providerId = $values[1]['provider_id'];
$elements["onbehalf_{$fld}-{$locType}"] = array(
'type' => 'Text',
'value' => $location[$fld][1][$fld],
);
$elements["onbehalf_{$fld}-{$locType}provider_id"] = array(
'type' => 'Select',
'value' => $location[$fld][1]['provider_id'],
);
unset($profileFields["{$fld}-{$locType}-{$providerId}"]);
}
}
}
if (!empty($website)) {
foreach ($website as $key => $val) {
$websiteTypeId = $values[1]['website_type_id'];
$elements["onbehalf_url-1"] = array(
'type' => 'Text',
'value' => $website[1]['url'],
);
$elements["onbehalf_url-1-website_type_id"] = array(
'type' => 'Select',
'value' => $website[1]['website_type_id'],
);
unset($profileFields["url-1"]);
}
}
$locTypeId = $location['address'][1]['location_type_id'];
$addressFields = array(
'street_address',
'supplemental_address_1',
'supplemental_address_2',
'city',
'postal_code',
'country',
'state_province',
);
foreach ($addressFields as $field) {
if (array_key_exists($field, $addressSequence)) {
$addField = $field;
if (in_array($field, array(
'state_province', 'country'))) {
$addField = "{$field}_id";
}
$elements["onbehalf_{$field}-{$locTypeId}"] = array(
'type' => 'Text',
'value' => $location['address'][1][$addField],
);
unset($profileFields["{$field}-{$locTypeId}"]);
}
}
//set custom field defaults
$defaults = array();
CRM_Core_BAO_UFGroup::setProfileDefaults($cid, $profileFields, $defaults, TRUE, NULL, NULL, TRUE);
if (!empty($defaults)) {
foreach ($profileFields as $key => $val) {
if (array_key_exists($key, $defaults)) {
$htmlType = CRM_Utils_Array::value('html_type', $val);
if ($htmlType == 'Radio') {
$elements["onbehalf[{$key}]"]['type'] = $htmlType;
$elements["onbehalf[{$key}]"]['value'] = $defaults[$key];
}
elseif ($htmlType == 'CheckBox') {
foreach ($defaults[$key] as $k => $v) {
$elements["onbehalf[{$key}][{$k}]"]['type'] = $htmlType;
$elements["onbehalf[{$key}][{$k}]"]['value'] = $v;
}
}
elseif ($htmlType == 'Multi-Select') {
foreach ($defaults[$key] as $k => $v) {
$elements["onbehalf_{$key}"]['type'] = $htmlType;
$elements["onbehalf_{$key}"]['value'][$k] = $v;
}
}
elseif ($htmlType == 'Autocomplete-Select') {
$elements["onbehalf_{$key}"]['type'] = $htmlType;
$elements["onbehalf_{$key}"]['value'] = $defaults[$key];
$elements["onbehalf_{$key}"]['id'] = $defaults["{$key}_id"];
}
else {
$elements["onbehalf_{$key}"]['type'] = $htmlType;
$elements["onbehalf_{$key}"]['value'] = $defaults[$key];
}
}
else {
$elements["onbehalf_{$key}"]['value'] = '';
}
}
}
}
echo json_encode($elements);
CRM_Utils_System::civiExit();
}
function jqState($config) {
if (!isset($_GET['_value']) ||
empty($_GET['_value'])
) {
CRM_Utils_System::civiExit();
}
$result = CRM_Core_PseudoConstant::stateProvinceForCountry($_GET['_value']);
$elements = array(array('name' => ts('- select a state -'),
'value' => '',
));
foreach ($result as $id => $name) {
$elements[] = array(
'name' => $name,
'value' => $id,
);
}
echo json_encode($elements);
CRM_Utils_System::civiExit();
}
function jqCounty($config) {
if (CRM_Utils_System::isNull($_GET['_value'])) {
$elements = array(array('name' => ts('- select state -'),
'value' => '',
));
}
else {
$result = CRM_Core_PseudoConstant::countyForState($_GET['_value']);
$elements = array(array('name' => ts('- select -'),
'value' => '',
));
foreach ($result as $id => $name) {
$elements[] = array(
'name' => $name,
'value' => $id,
);
}
if ($elements == array(
array('name' => ts('- select -'), 'value' => ''))) {
$elements = array(array('name' => ts('- no counties -'),
'value' => '',
));
}
}
echo json_encode($elements);
CRM_Utils_System::civiExit();
}
function getLocBlock() {
// i wish i could retrieve loc block info based on loc_block_id,
// Anyway, lets retrieve an event which has loc_block_id set to 'lbid'.
if ($_POST['lbid']) {
$params = array('1' => array($_POST['lbid'], 'Integer'));
$eventId = CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_event WHERE loc_block_id=%1 LIMIT 1', $params);
}
// now lets use the event-id obtained above, to retrieve loc block information.
if ($eventId) {
$params = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
// second parameter is of no use, but since required, lets use the same variable.
$location = CRM_Core_BAO_Location::getValues($params, $params);
}
$result = array();
$addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'address_options', TRUE, NULL, TRUE
);
// lets output only required fields.
foreach ($addressOptions as $element => $isSet) {
if ($isSet && (!in_array($element, array(
'im', 'openid')))) {
if (in_array($element, array(
'country', 'state_province', 'county'))) {
$element .= '_id';
}
elseif ($element == 'address_name') {
$element = 'name';
}
$fld = "address[1][{$element}]";
$value = CRM_Utils_Array::value($element, $location['address'][1]);
$value = $value ? $value : "";
$result[str_replace(array(
'][', '[', "]"), array('_', '_', ''), $fld)] = $value;
}
}
foreach (array(
'email', 'phone_type_id', 'phone') as $element) {
$block = ($element == 'phone_type_id') ? 'phone' : $element;
for ($i = 1; $i < 3; $i++) {
$fld = "{$block}[{$i}][{$element}]";
$value = CRM_Utils_Array::value($element, $location[$block][$i]);
$value = $value ? $value : "";
$result[str_replace(array(
'][', '[', "]"), array('_', '_', ''), $fld)] = $value;
}
}
// set the message if loc block is being used by more than one event.
$result['count_loc_used'] = CRM_Event_BAO_Event::countEventsUsingLocBlockId($_POST['lbid']);
echo json_encode($result);
CRM_Utils_System::civiExit();
}
}
| TheCraftyCanvas/folkshuln | sites/all/modules/civicrm/CRM/Core/Page/AJAX/Location.php | PHP | gpl-2.0 | 12,375 |
// $Id$
// QtLobby released under the GPLv3, see COPYING for details.
#include "TLDList.h"
QMap<QString, QString>* TLDList::TLDMap;
TLDList::TLDList( QObject* parent) : QObject(parent){
if ( TLDMap == NULL ) {
TLDMap = new QMap<QString, QString>;
QString TLDString = tr("AC:Ascension Island\n"
"AD:Andorra\n"
"AE:United Arab Emirates\n"
"AERO:Aircraft-related\n"
"AF:Afghanistan\n"
"AG:Antigua and Barbuda\n"
"AI:Anguilla\n"
"AL:Albania\n"
"AM:Armenia\n"
"AN:Netherland Antilles\n"
"AO:Angola\n"
"AQ:Antarctica\n"
"AR:Argentina\n"
"ARPA:Address and Routing Parameter Area\n"
"AS:American Samoa\n"
"AT:Austria\n"
"AU:Australia\n"
"AW:Aruba\n"
"AZ:Azerbaijan\n"
"BA:Bosnia-Herzegovina\n"
"BB:Barbados\n"
"BE:Belgium\n"
"BF:Burkina Faso\n"
"BG:Bulgaria\n"
"BH:Bahrain\n"
"BI:Burundi\n"
"BIz:Business\n"
"BJ:Benin\n"
"BM:Bermuda\n"
"BN:Brunei Darussalam\n"
"BO:Bolivia\n"
"BR:Brazil\n"
"BS:Bahamas\n"
"BT:Bhutan\n"
"BW:Botswana\n"
"BY:Belarus\n"
"BZ:Belize\n"
"CA:Canada\n"
"CC:Cocos (Keeling) Islands\n"
"CD:Democratic Republic of Congo\n"
"CF:Central African Republic\n"
"CG:Congo\n"
"CH:Switzerland\n"
"CI:Ivory Coast\n"
"CK:Cook Islands\n"
"CL:Chile\n"
"CM:Cameroon\n"
"CN:China\n"
"CO:Colombia\n"
"COM:Commercial\n"
"COOP:Cooperative-related\n"
"CR:Costa Rica\n"
"CU:Cuba\n"
"CV:Cape Verde\n"
"CX:Christmas Island\n"
"CY:Cyprus\n"
"CZ:Czech Republic\n"
"DE:Germany\n"
"DJ:Djibouti\n"
"DK:Denmark\n"
"DM:Dominica\n"
"DO:Dominican Republic\n"
"DZ:Algeria\n"
"EC:Ecuador\n"
"EDU:Educational\n"
"EE:Estonia\n"
"EG:Egypt\n"
"ES:Spain\n"
"ET:Ethiopia\n"
"FI:Finland\n"
"FJ:Fiji\n"
"FK:Falkland Islands (Malvinas)\n"
"FM:Micronesia\n"
"FO:Faroe Islands\n"
"FR:France\n"
"GB:Great Britan\n"
"GA:Gabon\n"
"GD:Grenada\n"
"GE:Georgia\n"
"GF:French Guyana\n"
"GH:Ghana\n"
"GI:Gibraltar\n"
"GL:Greenland\n"
"GM:Gambia\n"
"GN:Guinea\n"
"GOV:Government\n"
"GP:Guadeloupe (French)\n"
"GQ:Equatorial Guinea\n"
"GR:Greece\n"
"GT:Guatemala\n"
"GU:Guam (US)\n"
"GY:Guyana\n"
"HK:Hong Kong\n"
"HM:Heard and McDonald Islands\n"
"HN:Honduras\n"
"HR:Croatia (Hrvatska)\n"
"HU:Hungary\n"
"ID:Indonesia\n"
"IE:Ireland\n"
"IL:Israel\n"
"IN:India\n"
"INFO:General-purpose TLD\n"
"INT:International\n"
"IO:British Indian Ocean Territory\n"
"IR:Islamic Republic of Iran\n"
"IS:Iceland\n"
"IT:Italy\n"
"JM:Jamaica\n"
"JO:Jordan\n"
"JP:Japan\n"
"KE:Kenya\n"
"KG:Kyrgyzstan\n"
"KH:Cambodia\n"
"KI:Kiribati\n"
"KM:Comoros\n"
"KN:Saint Kitts Nevis Anguilla\n"
"KR:South Korea\n"
"KW:Kuwait\n"
"KY:Cayman Islands\n"
"KZ:Kazakhstan\n"
"LA:Laos (People's Democratic Republic)\n"
"LB:Lebanon\n"
"LC:Saint Lucia\n"
"LI:Liechtenstein\n"
"LK:Sri Lanka\n"
"LR:Liberia\n"
"LS:Lesotho\n"
"LT:Lithuania\n"
"LU:Luxembourg\n"
"LV:Latvia\n"
"LY:Libya (Libyan Arab Jamahiriya)\n"
"MA:Morocco\n"
"MC:Monaco\n"
"MD:Moldavia\n"
"MG:Madagascar\n"
"MH:Marshall Islands\n"
"MIL:US Military\n"
"MK:Macedonia\n"
"ML:Mali\n"
"MM:Myanmar\n"
"MN:Mongolia\n"
"MO:Macau\n"
"MP:Northern Mariana Islands\n"
"MQ:Martinique (French)\n"
"MR:Mauritania\n"
"MS:Montserrat\n"
"MT:Malta\n"
"MU:Mauritius\n"
"MUseum:Museum-related\n"
"MV:Maldives\n"
"MW:Malawi\n"
"MX:Mexico\n"
"MY:Malaysia\n"
"MZ:Mozambique\n"
"NA:Namibia\n"
"NAME:Personal name\n"
"NC:New Caledonia (French)\n"
"NE:Niger\n"
"NET:Network Infrastructure\n"
"NF:Norfolk Island\n"
"NG:Nigeria\n"
"NI:Nicaragua\n"
"NL:Netherlands\n"
"NO:Norway\n"
"NP:Nepal\n"
"NR:Nauru\n"
"NU:Niue\n"
"NZ:New Zealand\n"
"OM:Oman\n"
"ORG:Nonprofit\n"
"PA:Panama\n"
"PE:Peru\n"
"PF:French Polynesia\n"
"PF:Polynesia (French)\n"
"PG:Papua New Guinea\n"
"PH:Philippines\n"
"PK:Pakistan\n"
"PL:Poland\n"
"PM:Saint Pierre and Miquelon\n"
"PN:Pitcairn\n"
"PR:Puerto Rico (US)\n"
"PRo:Professional domain\n"
"PS:Palestina\n"
"PT:Portugal\n"
"PW:Palau\n"
"PY:Paraguay\n"
"QA:Qatar\n"
"RE:Reunion (French)\n"
"RO:Romania\n"
"RU:Russian Federation\n"
"RW:Rwanda\n"
"SA:Saudi Arabia\n"
"SB:Solomon Islands\n"
"SC:Seychelles\n"
"SE:Sweden\n"
"SG:Singapore\n"
"SH:Saint Helena\n"
"SI:Slovenia\n"
"SK:Slovak Republic (Slovakia)\n"
"SL:Sierra Leone\n"
"SM:San Marino\n"
"SN:Senegal\n"
"SO:Somalia\n"
"SR:Surinam\n"
"ST:Saint Tome and Principe\n"
"SU:Soviet Union\n"
"SV:El Salvador\n"
"SZ:Swaziland\n"
"TC:Turks and Caicos Islands\n"
"TD:Chad\n"
"TF:French Southern Territories\n"
"TG:Togo\n"
"TH:Thailand\n"
"TJ:Tajikistan\n"
"TK:Tokelau\n"
"TM:Turkmenistan\n"
"TN:Tunisia\n"
"TO:Tonga\n"
"TP:East Timor\n"
"TR:Turkey\n"
"TT:Trinidad and Tobago\n"
"TV:Tuvalu\n"
"TW:Taiwan\n"
"TZ:Tanzania\n"
"UA:Ukraine\n"
"UG:Uganda\n"
"UK:United Kingdom\n"
"US:United States of America\n"
"UY:Uruguay\n"
"UZ:Uzbekistan\n"
"VA:Vatican City State\n"
"VC:Saint Vincent and the Grenadines\n"
"VE:Venezuela\n"
"VG:Virgin Islands (British)\n"
"VI:Virgin Islands (US)\n"
"VN:Vietnam\n"
"VU:Vanuatu\n"
"WS:Samoa\n"
"YE:Yemen\n"
"YU:Yugoslavia\n"
"ZA:South Africa\n"
"ZM:Zambia\n"
"ZR:Zaire\n"
"ZW:Zimbabwe\n"
"XX:?\n"
);
QStringList list = TLDString.split( "\n" );
foreach( QString s, list ) {
TLDMap->insert( s.section( ":", 0, 0 ), s.section( ":", 1, 1 ) );
}
}
}
TLDList::~TLDList() {
}
| tizbac/qtlobby | src/TLDList.cpp | C++ | gpl-2.0 | 9,013 |
<?php
namespace Drupal\webform_node;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleUninstallValidatorInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
/**
* Prevents webform_node module from being uninstalled whilst any webform nodes exist.
*/
class WebformNodeUninstallValidator implements ModuleUninstallValidatorInterface {
use StringTranslationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a WebformNodeUninstallValidator.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, TranslationInterface $string_translation) {
$this->entityTypeManager = $entity_type_manager;
$this->stringTranslation = $string_translation;
}
/**
* {@inheritdoc}
*/
public function validate($module) {
$reasons = [];
if ($module === 'webform_node') {
// The webform node type is provided by the Webform node module. Prevent
// uninstall if there are any nodes of that type.
if ($this->hasWebformNodes()) {
$reasons[] = $this->t('To uninstall Webform node, delete all content that has the Webform content type.');
}
}
return $reasons;
}
/**
* Determines if there is any webform nodes or not.
*
* @return bool
* TRUE if there are webform nodes, FALSE otherwise.
*/
protected function hasWebformNodes() {
$nodes = $this->entityTypeManager->getStorage('node')->getQuery()
->condition('type', 'webform')
->accessCheck(FALSE)
->range(0, 1)
->execute();
return !empty($nodes);
}
}
| YaManicKill/viewfield | web/modules/webform/modules/webform_node/src/WebformNodeUninstallValidator.php | PHP | gpl-2.0 | 1,995 |
<?php
/**
* Custom template tags for this theme.
*
* Eventually, some of the functionality here could be replaced by core features.
*
* @package testwp_ssass
*/
if ( ! function_exists( 'testwp_ssass_paging_nav' ) ) :
/**
* Display navigation to next/previous set of posts when applicable.
*/
function testwp_ssass_paging_nav() {
// Don't print empty markup if there's only one page.
if ( $GLOBALS['wp_query']->max_num_pages < 2 ) {
return;
}
?>
<nav class="navigation paging-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Posts navigation', 'testwp_ssass' ); ?></h1>
<div class="nav-links">
<?php if ( get_next_posts_link() ) : ?>
<div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">←</span> Older posts', 'testwp_ssass' ) ); ?></div>
<?php endif; ?>
<?php if ( get_previous_posts_link() ) : ?>
<div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">→</span>', 'testwp_ssass' ) ); ?></div>
<?php endif; ?>
</div><!-- .nav-links -->
</nav><!-- .navigation -->
<?php
}
endif;
if ( ! function_exists( 'testwp_ssass_post_nav' ) ) :
/**
* Display navigation to next/previous post when applicable.
*/
function testwp_ssass_post_nav() {
// Don't print empty markup if there's nowhere to navigate.
$previous = ( is_attachment() ) ? get_post( get_post()->post_parent ) : get_adjacent_post( false, '', true );
$next = get_adjacent_post( false, '', false );
if ( ! $next && ! $previous ) {
return;
}
?>
<nav class="navigation post-navigation" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Post navigation', 'testwp_ssass' ); ?></h1>
<div class="nav-links">
<?php
previous_post_link( '<div class="nav-previous">%link</div>', _x( '<span class="meta-nav">←</span> %title', 'Previous post link', 'testwp_ssass' ) );
next_post_link( '<div class="nav-next">%link</div>', _x( '%title <span class="meta-nav">→</span>', 'Next post link', 'testwp_ssass' ) );
?>
</div><!-- .nav-links -->
</nav><!-- .navigation -->
<?php
}
endif;
if ( ! function_exists( 'testwp_ssass_posted_on' ) ) :
/**
* Prints HTML with meta information for the current post-date/time and author.
*/
function testwp_ssass_posted_on() {
$time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) {
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
}
$time_string = sprintf( $time_string,
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() ),
esc_attr( get_the_modified_date( 'c' ) ),
esc_html( get_the_modified_date() )
);
$posted_on = sprintf(
_x( 'Posted on %s', 'post date', 'testwp_ssass' ),
'<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>'
);
$byline = sprintf(
_x( 'by %s', 'post author', 'testwp_ssass' ),
'<span class="author vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . '">' . esc_html( get_the_author() ) . '</a></span>'
);
echo '<span class="posted-on">' . $posted_on . '</span><span class="byline"> ' . $byline . '</span>';
}
endif;
if ( ! function_exists( 'testwp_ssass_entry_footer' ) ) :
/**
* Prints HTML with meta information for the categories, tags and comments.
*/
function testwp_ssass_entry_footer() {
// Hide category and tag text for pages.
if ( 'post' == get_post_type() ) {
/* translators: used between list items, there is a space after the comma */
$categories_list = get_the_category_list( __( ', ', 'testwp_ssass' ) );
if ( $categories_list && testwp_ssass_categorized_blog() ) {
printf( '<span class="cat-links">' . __( 'Posted in %1$s', 'testwp_ssass' ) . '</span>', $categories_list );
}
/* translators: used between list items, there is a space after the comma */
$tags_list = get_the_tag_list( '', __( ', ', 'testwp_ssass' ) );
if ( $tags_list ) {
printf( '<span class="tags-links">' . __( 'Tagged %1$s', 'testwp_ssass' ) . '</span>', $tags_list );
}
}
if ( ! is_single() && ! post_password_required() && ( comments_open() || get_comments_number() ) ) {
echo '<span class="comments-link">';
comments_popup_link( __( 'Leave a comment', 'testwp_ssass' ), __( '1 Comment', 'testwp_ssass' ), __( '% Comments', 'testwp_ssass' ) );
echo '</span>';
}
edit_post_link( __( 'Edit', 'testwp_ssass' ), '<span class="edit-link">', '</span>' );
}
endif;
/**
* Returns true if a blog has more than 1 category.
*
* @return bool
*/
function testwp_ssass_categorized_blog() {
if ( false === ( $all_the_cool_cats = get_transient( 'testwp_ssass_categories' ) ) ) {
// Create an array of all the categories that are attached to posts.
$all_the_cool_cats = get_categories( array(
'fields' => 'ids',
'hide_empty' => 1,
// We only need to know if there is more than one category.
'number' => 2,
) );
// Count the number of categories that are attached to the posts.
$all_the_cool_cats = count( $all_the_cool_cats );
set_transient( 'testwp_ssass_categories', $all_the_cool_cats );
}
if ( $all_the_cool_cats > 1 ) {
// This blog has more than 1 category so testwp_ssass_categorized_blog should return true.
return true;
} else {
// This blog has only 1 category so testwp_ssass_categorized_blog should return false.
return false;
}
}
/**
* Flush out the transients used in testwp_ssass_categorized_blog.
*/
function testwp_ssass_category_transient_flusher() {
// Like, beat it. Dig?
delete_transient( 'testwp_ssass_categories' );
}
add_action( 'edit_category', 'testwp_ssass_category_transient_flusher' );
add_action( 'save_post', 'testwp_ssass_category_transient_flusher' );
| stoicattempt/testwp_ssass | wp-content/themes/testwp_ssass/inc/template-tags.php | PHP | gpl-2.0 | 5,871 |
<?php
/**
* Represents the view for the public-facing component of the plugin.
*
* This typically includes any information, if any, that is rendered to the
* frontend of the theme when the plugin is activated.
*
* @package Changelog
* @author averta < >
* @license GPL-2.0+
* @link http://example.com
* @copyright 2014
*/
?>
<!-- This file is used to markup the public facing aspect of the plugin. -->
| M4Gd/changelog | public/views/public.php | PHP | gpl-2.0 | 427 |
<?php $orig_post = $post;
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=> 4, // Number of related posts that will be shown.
'caller_get_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() )
{
echo '<div id="related_posts" class="bottom-single-related"><h3 class="rs">Также рекомендуем прочитать</h3><ul>';
while( $my_query->have_posts() ) {
$my_query->the_post();
$thumb2 = get_post_thumbnail_id();$img_url2 = wp_get_attachment_url( $thumb2,'index-blog' );$image2 = aq_resize( $img_url2, 150,150,true );
?>
<li>
<?php if ($image){ ?>
<img src="<?php echo $image2; ?>">
<?php } ?>
<h2><a href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2></li>
<?php } echo '</ul></div>'; } }
$post = $orig_post;
wp_reset_query();
?> | achyutdahal/1234 | wp-content/themes/urbannews32/framework/includes/related-img.php | PHP | gpl-2.0 | 1,123 |
package com.oinux.lanmitm.service;
import com.oinux.lanmitm.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class BaseService extends Service {
public static final int HTTP_SERVER_NOTICE = 1;
public static final int HIJACK_NOTICE = 2;
public static final int SNIFFER_NOTICE = 3;
public static final int INJECT_NOTICE = 4;
public static final int ARPSPOOF_NOTICE = 0;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@SuppressWarnings("deprecation")
protected void notice(String tickerText, int id, Class<?> cls) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = new Notification(R.drawable.ic_launch_notice,
getString(R.string.app_name), System.currentTimeMillis());
n.flags = Notification.FLAG_NO_CLEAR;
Intent intent = new Intent(this, cls);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this,
R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);
n.setLatestEventInfo(this, this.getString(R.string.app_name),
tickerText, contentIntent);
nm.notify(id, n);
}
}
| vaginessa/Lanmitm | src/com/oinux/lanmitm/service/BaseService.java | Java | gpl-2.0 | 1,380 |
<?php
/**
* This is the model class for table "message".
*
* The followings are the available columns in table 'message':
* @property integer $msg_id
* @property string $subject
* @property string $msg_content
* @property string $msg_uploads
* @property integer $user_id
* @property string $msg_time
* @property string $msg_date
* @property integer $is_read
*/
class Message extends CActiveRecord
{
/* PROPERTY FOR RECEIVING THE FILE FROM FORM*/
public $msg_uploads;
public $to;
public $attribute_id;
/**
* Returns the static model of the specified AR class.
* @return Message the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'message';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('subject, msg_content, msg_time, msg_date,to', 'required'),
array('user_id, is_read, sender_id, user_id, is_task, is_deleted', 'numerical', 'integerOnly'=>true),
array('subject, msg_uploads', 'length', 'max'=>120),
array('msg_content', 'length'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('msg_id, subject, msg_content, msg_uploads, user_id, msg_time, msg_date, is_read', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'msg_id' => 'Msg',
'subject' => 'Subject',
'msg_content' => 'Msg Content',
'msg_uploads' => 'Msg Uploads',
'user_id' => 'User',
'msg_time' => 'Msg Time',
'msg_date' => 'Msg Date',
'is_read' => 'Is Read',
'is_task' => 'Is Task'
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('msg_id',$this->msg_id);
$criteria->compare('subject',$this->subject,true);
$criteria->compare('msg_content',$this->msg_content,true);
$criteria->compare('msg_uploads',$this->msg_uploads,true);
$criteria->compare('user_id',$this->user_id);
$criteria->compare('msg_time',$this->msg_time,true);
$criteria->compare('msg_date',$this->msg_date,true);
$criteria->compare('is_read',$this->is_read);
return new CActiveDataProvider(get_class($this), array(
'criteria'=>$criteria,
));
}
public function actionSearch($term)
{
if(Yii::app()->request->isAjaxRequest && !empty($term))
{
$variants = array();
$criteria = new CDbCriteria;
$criteria->select='tag';
$criteria->addSearchCondition('tag',$term.'%',false);
$tags = tagsModel::model()->findAll($criteria);
if(!empty($tags))
{
foreach($tags as $tag)
{
$variants[] = $tag->attributes['tag'];
}
}
echo CJSON::encode($variants);
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
// functions
public function setMsg()
{
$connection = Yii::app()->db;
$sql="SELECT * FROM user";
$command = $connection->createCommand($sql);
$results = $command->queryAll();
return $results;
}
public function setGroup()
{
$connection = Yii::app()->db;
$sql="SELECT * FROM groups";
$command = $connection->createCommand($sql);
$results = $command->queryAll();
return $results;
}
public function getMsg($id)
{
$i=0;
$connection = Yii::app()->db;
$sql="SELECT t1.message_id,t1.user_id FROM message_user AS t1 INNER JOIN message AS t2 ON t1.message_id = t2.msg_id WHERE t2.is_task IS NULL ORDER BY t2.msg_id DESC";
$command = $connection->createCommand($sql);
$results = $command->queryAll();
$data=array();
foreach($results as $temp)
{
//print_r($temp['user_id']);
$msg=$temp['message_id'];
$value1 = explode(",",$temp['user_id']);
//print_r($value1);
foreach($value1 as $value2)
{
//print_r($value2);
if($value2==$id)
{
//echo 'message';
//print_r($msg);
$data[$i]=$msg;
$i++;
}
}
}
return $data;
}
public function getTasks($id,$status)
{
$i=0;
$connection = Yii::app()->db;
$sql="SELECT t1.message_id,t1.user_id FROM message_user AS t1 INNER JOIN message AS t2 ON t1.message_id = t2.msg_id WHERE t2.is_task IS NOT NULL ORDER BY t2.msg_id DESC";
$command = $connection->createCommand($sql);
$results = $command->queryAll();
$data=array();
foreach($results as $temp)
{
//print_r($temp['user_id']);
$msg=$temp['message_id'];
$task=TaskAssignToPatients::model()->findByAttributes(array('id'=>$msgids->is_task,'status'=>$status));
if($task != NULL )
{
$value1 = explode(",",$temp['user_id']);
//print_r($value1);
foreach($value1 as $value2)
{
//print_r($value2);
if($value2==$id)
{
$data[$i]=$msg;
$i++;
}
}
}
else if($status=='T')
{$value1 = explode(",",$temp['user_id']);
//print_r($value1);
foreach($value1 as $value2)
{
//print_r($value2);
if($value2==$id)
{
$data[$i]=$msg;
$i++;
}
}
}
}
return $data;
}
public function getMsgcontent($msgid)
{
$connection = Yii::app()->db;
$sql="SELECT * FROM message WHERE msg_id =".$msgid;
$command = $connection->createCommand($sql);
$users= $command->queryAll();
return $users;
}
public function getMsgvalue($msgid)
{
$connection = Yii::app()->db;
$sql="SELECT t1.subject, t1.msg_id, t1.msg_date,t1.user_id,t1.sender_id FROM message AS t1,message_user AS t2 WHERE t1.msg_id=t2.message_id AND t1.user_id=113 AND t1.is_task IS NULL";
$command = $connection->createCommand($sql);
$users= $command->queryAll();
return $users;
}
public function getTaskvalue($msgid)
{
$connection = Yii::app()->db;
$sql="SELECT * FROM message WHERE msg_id =".$msgid." AND is_task!='NULL'";
$command = $connection->createCommand($sql);
$users= $command->queryAll();
return $users;
}
// TO set Isread
public function setRead($msgid)
{
$connection = Yii::app()->db;
$sql="UPDATE message SET is_read = 1 WHERE msg_id =".$msgid;
$command = $connection->createCommand($sql);
$command->queryAll();
}
public function getUnreadMessages()
{
/* $command = Yii::app()->dbadvert->createCommand()
->select ('*')
->from('message')
->where('is_read=0')
->limit(14,0)
->order('msg_date desc')
->queryAll();
return $command;*/
$connection = Yii::app()->db;
$sql = 'SELECT * FROM `message` WHERE `is_read`=0 ORDER BY `message`.`msg_date` ASC LIMIT 0 , 30';
$command = $connection->createCommand($sql);
$uread_messages = $command->queryAll();
//For getting total number of messages
$sql = 'SELECT * FROM `message` WHERE `is_read`=0';
$command = $connection->createCommand($sql);
$total = $command->queryAll();
$total = sizeof($total);
return array ($uread_messages,$total);
}
public function getSysMessages()
{
/* $command = Yii::app()->dbadvert->createCommand()
->select ('*')
->from('message')
->where('is_read=0')
->limit(14,0)
->order('msg_date desc')
->queryAll();
return $command;*/
$connection = Yii::app()->sys_db;
$sql = 'SELECT * FROM `messages` WHERE `is_read`=0 ORDER BY `messages`.`date` ASC LIMIT 0 , 30';
$command = $connection->createCommand($sql);
$uread_messages = $command->queryAll();
//For getting total number of messages
$sql = 'SELECT * FROM `messages` WHERE `is_read`=0';
$command = $connection->createCommand($sql);
$total = $command->queryAll();
$total = sizeof($total);
return array ($uread_messages,$total);
}
// For Message Forward
public function messageForward()
{
$model=new Message;
if(isset($_POST['Message']))
{
$model->attributes=$_POST['Message'];
if($model->save())
{
$insert_id = Yii::app()->db->getLastInsertID();
$list = implode(",", $_POST['msg']);
//DB Insertion
$connection = Yii::app()->db;
$command = $connection->createCommand();
$results = $command->insert('message_user',array('user_id'=>$list,'message_id'=>$insert_id));
}
}
}
//To Delete user id from List of Message-User
public function deleteMessage($uid,$mid)
{
$connection = Yii::app()->db;
$sql="SELECT user_id FROM message_user WHERE message_id =".$mid;
$command = $connection->createCommand($sql);
$results = $command->queryAll();
foreach($results as $temp)
{
//print_r($temp['user_id');
//$msg=$temp['message_id'];
$list='';
$value1 = explode(",",$temp['user_id']);
foreach($value1 as $value2)
{
if($value2!=$uid)
{
$list .=$value2.',';
}}
$list1=trim($list,',');
$connection = Yii::app()->db;
$sql="UPDATE message_user SET user_id = '".$list1."' WHERE message_id =".$mid;
$command = $connection->createCommand($sql);
$command->execute();
}
}
// To get message Contents field by field
public function getMsgcontentView($msgid,$variable)
{
$connection = Yii::app()->db;
$sql="SELECT * FROM message WHERE msg_id =".$msgid;
$command = $connection->createCommand($sql);
$users= $command->queryAll();
foreach($users as $users1)
return $users1[$variable];
}
//To get Patient Name for Message
public function getName($id)
{
$users = Yii::app()->dbadvert->createCommand()
->select('patient_lname')
->from('patients')
->where('patient_id='.$id)
->queryAll();
foreach($users as $users1)
return $users1['patient_lname'];
}
//For Sent Message List
public function getSentmessage()
{
$connection = Yii::app()->db;
$sql="SELECT * FROM message_user ORDER BY id DESC";
$command = $connection->createCommand($sql);
$results = $command->queryAll();
return $results;
}
public function getUserName($id)
{
$connection = Yii::app()->db;
$sql="SELECT username FROM blog_user WHERE id=".$id;
$command = $connection->createCommand($sql);
$results = $command->queryAll();
foreach($results as $users1)
return $users1['username'];
}
public function getPhoto($id)
{
$connection = Yii::app()->db;
$sql="SELECT photo FROM user_details WHERE user_id =".$id;
$command = $connection->createCommand($sql);
$result=$command->queryAll();
if(count($result) == 0)
return '<img src="users/user.jpg" width="48" height="51" />';
else
return '<img src="users/'.$id.'/'.$result[0]['photo'].'.jpg" width="48" height="51" />';
}
public function getPhototask($id)
{
$connection = Yii::app()->db;
$sql="SELECT photo FROM user_details WHERE user_id =".$id;
$command = $connection->createCommand($sql);
$result=$command->queryAll();
if(count($result) == 0)
return '<img src="users/user.jpg" width="48" height="51" />';
else
return '<img src="users/'.$id.'/'.$result[0]['photo'].'.jpg" width="100" height="100" />';
}
public function getUserPhototask($id)
{
$connection = Yii::app()->db;
$sql="SELECT photo FROM user_details WHERE user_id =".$id;
$command = $connection->createCommand($sql);
$result=$command->queryAll();
if(count($result) == 0)
return '<img src="users/user.jpg" width="43" height="43" />';
else
return '<img src="users/'.$id.'/'.$result[0]['photo'].'.jpg" width="43" height="43" />';
}
// Reccurssive Function For Reply Ajax Link and disply Div, Rajith
public function getReply1($rid)
{
$next = Reply::model()->findByAttributes(array('uid'=>Yii::app()->user->id,'rid'=>$rid));
if($next!=NULL)
{
$details = Message::model()->findByAttributes(array('msg_id'=>$next->mid));
echo '<div >';
echo CHtml::ajaxLink('From ::- '.Message::model()->getUserName($details->sender_id).' Subject ::- '.$details->subject,Yii::app()->createUrl('Message/message_details' ),
array('type' =>'GET','data' => array('msg'=>$next->mid),
'dataType' => 'text','update' =>'#'.$next->mid));
echo '</div>';
echo '<div id='.$next->mid.'></div>';
Message::model()->getReply($next->mid);
}
else
{
return ;
}
}
public function getReply($mid)
{
$next = Reply::model()->findAll(array('order'=>'rid DESC', 'condition'=>'(uid=:x or sid=:y) and mid=:z', 'params'=>array(':x'=>Yii::app()->user->id,':y'=>Yii::app()->user->id,':z'=>$mid)));
if($next!=NULL)
{
$i=0;
foreach($next as $next1)
{
if($i!=0)
{
$details = Message::model()->findByAttributes(array('msg_id'=>$next1['rid']));
echo '<div class="msgacc_Con">';
echo CHtml::ajaxLink(' <strong>From</strong> : '.Message::model()->getUserName($details->sender_id).'<br/><strong>Subject</strong> : '.$details->subject,Yii::app()->createUrl('Message/message_details' ),
array('type' =>'GET','data' => array('msg'=>$next1['rid']),
'dataType' => 'text','update' =>'#'.$next1['rid']));
echo '</div>';
echo '<div id='.$next1['rid'].'></div>';
}
$i++;
}
$details = Message::model()->findByAttributes(array('msg_id'=>$mid));
echo '<div class="msgacc_Con">';
echo CHtml::ajaxLink(' <strong>From</strong> : '.Message::model()->getUserName($details->sender_id).' <br/><strong>Subject</strong> : '.$details->subject,Yii::app()->createUrl('Message/message_details' ),
array('type' =>'GET','data' => array('msg'=>$mid),
'dataType' => 'text','update' =>'#'.$mid));
echo '</div>';
echo '<div id='.$mid.'></div>';
}
else
{
return ;
}
}
// Reccurssive Function For Reply ID, Rajith
public function getReplyid1($mid)
{
$next = Reply::model()->findByAttributes(array('uid'=>Yii::app()->user->id,'mid'=>$mid));
if($next!=NULL)
{
$rid=Message::model()->getReplyid($next->rid);
return $rid;
}
return $mid;
}
public function getReplycount($mid)
{
$next = Reply::model()->findAll(array('order'=>'rid DESC', 'condition'=>'(uid=:x or sid=:y) and mid=:z', 'params'=>array(':x'=>Yii::app()->user->id,':y'=>Yii::app()->user->id,':z'=>$mid)));
if($next!=NULL)
{
return count($next);
}
else
{
return 0;
}
}
public function getReplyid($mid)
{
$next = Reply::model()->findAll(array('order'=>'rid DESC', 'condition'=>'(uid=:x or sid=:y) and mid=:z', 'params'=>array(':x'=>Yii::app()->user->id,':y'=>Yii::app()->user->id,':z'=>$mid)));
if($next!=NULL)
{
return $next[0]['rid'];
}
else
{
return $mid;
}
}
// Sort for task- Rajith
public function sorts($t,$status,$page)
{
switch($t)
{
case 0:
$subject='msg_id DESC';
break;
case 1:
$subject='subject';
break;
case 2:
$subject='subject DESC';
break;
}
$i=0;
$messageids=NULL;
$connection = Yii::app()->db;
$sql="SELECT t1.msg_id,t1.is_task FROM message AS t1 INNER JOIN message_user AS t2 ON t1.msg_id = t2.message_id WHERE t1.is_task IS NOT NULL AND t2.user_id =".Yii::app()->user->id." ORDER BY t1.".$subject;
$command = $connection->createCommand($sql);
$msgids = $command->queryAll();
if($msgids!=NULL)
{
foreach($msgids as $msgids1)
{
//only for T
if($status=='T')
{
$messageids[$i]=$msgids1['msg_id'];
$i++;
}
else
{
$task=TaskAssignToPatients::model()->findByAttributes(array('id'=>$msgids1['is_task'],'status'=>$status));
if($task != NULL )
{
$messageids[$i]=$msgids1['msg_id'];
$i++;
}
}
}
}
return $messageids;
}
public function sortsUsertask($t,$status,$user_id)
{
switch($t)
{
case 0:
$subject='msg_id DESC';
break;
case 1:
$subject='subject';
break;
case 2:
$subject='subject DESC';
break;
}
$i=0;
$messageids=NULL;
$connection = Yii::app()->db;
$sql="SELECT t1.msg_id,t1.is_task FROM message AS t1 INNER JOIN message_user AS t2 ON t1.msg_id = t2.message_id WHERE t1.is_task IS NOT NULL AND t2.user_id =".$user_id." ORDER BY t1.".$subject;
$command = $connection->createCommand($sql);
$msgids = $command->queryAll();
if($msgids!=NULL)
{
foreach($msgids as $msgids1)
{
//only for T
if($status=='T')
{
$messageids[$i]=$msgids1['msg_id'];
$i++;
}
else
{
$task=TaskAssignToPatients::model()->findByAttributes(array('id'=>$msgids1['is_task'],'status'=>$status));
if($task != NULL )
{
$messageids[$i]=$msgids1['msg_id'];
$i++;
}
}
}
}
return $messageids;
}
public function sortsAgencytask($t,$status)
{
switch($t)
{
case 0:
$subject='id DESC';
break;
case 1:
$subject='subject';
break;
case 2:
$subject='id DESC';
break;
}
$i=0;
$messageids=NULL;
//$msgids=TaskAssignToPatients::model()->findAll(array('order'=>$subject, 'condition'=>'is_task!=:z', 'params'=>array(':z'=>'')));
$msgids=TaskAssignToPatients::model()->findAll(array('order'=>$subject));
return $msgids;
}
} | napoleon789/qlkh | osv/protected/models/Message.php | PHP | gpl-2.0 | 18,568 |
# Copyright (C) 2019 Fassio Blatter
from stopeight import analyzer
version=analyzer.version
from stopeight.util.editor.data import ScribbleData
def legal_segments(data):
from stopeight.matrix import Vectors
from stopeight.analyzer import legal_segments
return legal_segments(Vectors(data)).__array__().view(ScribbleData)
legal_segments.__annotations__ = {'data':ScribbleData,'return':ScribbleData}
| specpose/stopeight | stopeight/util/editor/modules/analyzer.py | Python | gpl-2.0 | 413 |
<?php
if (is_category('stem')) {
get_template_part('templates/content', 'stem');
} else {
get_template_part('templates/content', 'category');
}
?>
| JulienMelissas/EdNC | wp-content/themes/ednc-roots/category.php | PHP | gpl-2.0 | 151 |
/* NicEdit - Micro Inline WYSIWYG
* Copyright 2007-2008 Brian Kirchoff
*
* NicEdit is distributed under the terms of the MIT license
* For more information visit http://nicedit.com/
* Do not remove this copyright message
*/
var bkExtend = function(){
var args = arguments;
if (args.length == 1) args = [this, args[0]];
for (var prop in args[1]) args[0][prop] = args[1][prop];
return args[0];
};
function bkClass() { }
bkClass.prototype.construct = function() {};
bkClass.extend = function(def) {
var classDef = function() {
if (arguments[0] !== bkClass) { return this.construct.apply(this, arguments); }
};
var proto = new this(bkClass);
bkExtend(proto,def);
classDef.prototype = proto;
classDef.extend = this.extend;
return classDef;
};
var bkElement = bkClass.extend({
construct : function(elm,d) {
if(typeof(elm) == "string") {
elm = (d || document).createElement(elm);
}
elm = $BK(elm);
return elm;
},
appendTo : function(elm) {
elm.appendChild(this);
return this;
},
appendBefore : function(elm) {
elm.parentNode.insertBefore(this,elm);
return this;
},
addEvent : function(type, fn) {
bkLib.addEvent(this,type,fn);
return this;
},
setContent : function(c) {
this.innerHTML = c;
return this;
},
pos : function() {
var curleft = curtop = 0;
var o = obj = this;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
var b = (!window.opera) ? parseInt(this.getStyle('border-width') || this.style.border) || 0 : 0;
return [curleft+b,curtop+b+this.offsetHeight];
},
noSelect : function() {
bkLib.noSelect(this);
return this;
},
parentTag : function(t) {
var elm = this;
do {
if(elm && elm.nodeName && elm.nodeName.toUpperCase() == t) {
return elm;
}
elm = elm.parentNode;
} while(elm);
return false;
},
hasClass : function(cls) {
return this.className.match(new RegExp('(\\s|^)nicEdit-'+cls+'(\\s|$)'));
},
addClass : function(cls) {
if (!this.hasClass(cls)) { this.className += " nicEdit-"+cls };
return this;
},
removeClass : function(cls) {
if (this.hasClass(cls)) {
this.className = this.className.replace(new RegExp('(\\s|^)nicEdit-'+cls+'(\\s|$)'),' ');
}
return this;
},
setStyle : function(st) {
var elmStyle = this.style;
for(var itm in st) {
switch(itm) {
case 'float':
elmStyle['cssFloat'] = elmStyle['styleFloat'] = st[itm];
break;
case 'opacity':
elmStyle.opacity = st[itm];
elmStyle.filter = "alpha(opacity=" + Math.round(st[itm]*100) + ")";
break;
case 'className':
this.className = st[itm];
break;
default:
//if(document.compatMode || itm != "cursor") { // Nasty Workaround for IE 5.5
elmStyle[itm] = st[itm];
//}
}
}
return this;
},
getStyle : function( cssRule, d ) {
var doc = (!d) ? document.defaultView : d;
if(this.nodeType == 1)
return (doc && doc.getComputedStyle) ? doc.getComputedStyle( this, null ).getPropertyValue(cssRule) : this.currentStyle[ bkLib.camelize(cssRule) ];
},
remove : function() {
this.parentNode.removeChild(this);
return this;
},
setAttributes : function(at) {
for(var itm in at) {
this[itm] = at[itm];
}
return this;
}
});
var bkLib = {
isMSIE : (navigator.appVersion.indexOf("MSIE") != -1),
addEvent : function(obj, type, fn) {
(obj.addEventListener) ? obj.addEventListener( type, fn, false ) : obj.attachEvent("on"+type, fn);
},
toArray : function(iterable) {
var length = iterable.length, results = new Array(length);
while (length--) { results[length] = iterable[length] };
return results;
},
noSelect : function(element) {
if(element.setAttribute && element.nodeName.toLowerCase() != 'input' && element.nodeName.toLowerCase() != 'textarea') {
element.setAttribute('unselectable','on');
}
for(var i=0;i<element.childNodes.length;i++) {
bkLib.noSelect(element.childNodes[i]);
}
},
camelize : function(s) {
return s.replace(/\-(.)/g, function(m, l){return l.toUpperCase()});
},
inArray : function(arr,item) {
return (bkLib.search(arr,item) != null);
},
search : function(arr,itm) {
for(var i=0; i < arr.length; i++) {
if(arr[i] == itm)
return i;
}
return null;
},
cancelEvent : function(e) {
e = e || window.event;
if(e.preventDefault && e.stopPropagation) {
e.preventDefault();
e.stopPropagation();
}
return false;
},
domLoad : [],
domLoaded : function() {
if (arguments.callee.done) return;
arguments.callee.done = true;
for (i = 0;i < bkLib.domLoad.length;i++) bkLib.domLoad[i]();
},
onDomLoaded : function(fireThis) {
this.domLoad.push(fireThis);
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", bkLib.domLoaded, null);
} else if(bkLib.isMSIE) {
document.write("<style>.nicEdit-main p { margin: 0; }</style><scr"+"ipt id=__ie_onload defer " + ((location.protocol == "https:") ? "src='javascript:void(0)'" : "src=//0") + "><\/scr"+"ipt>");
$BK("__ie_onload").onreadystatechange = function() {
if (this.readyState == "complete"){bkLib.domLoaded();}
};
}
window.onload = bkLib.domLoaded;
}
};
function $BK(elm) {
if(typeof(elm) == "string") {
elm = document.getElementById(elm);
}
return (elm && !elm.appendTo) ? bkExtend(elm,bkElement.prototype) : elm;
}
var bkEvent = {
addEvent : function(evType, evFunc) {
if(evFunc) {
this.eventList = this.eventList || {};
this.eventList[evType] = this.eventList[evType] || [];
this.eventList[evType].push(evFunc);
}
return this;
},
fireEvent : function() {
var args = bkLib.toArray(arguments), evType = args.shift();
if(this.eventList && this.eventList[evType]) {
for(var i=0;i<this.eventList[evType].length;i++) {
this.eventList[evType][i].apply(this,args);
}
}
}
};
function __(s) {
return s;
}
Function.prototype.closure = function() {
var __method = this, args = bkLib.toArray(arguments), obj = args.shift();
return function() { if(typeof(bkLib) != 'undefined') { return __method.apply(obj,args.concat(bkLib.toArray(arguments))); } };
}
Function.prototype.closureListener = function() {
var __method = this, args = bkLib.toArray(arguments), object = args.shift();
return function(e) {
e = e || window.event;
if(e.target) { var target = e.target; } else { var target = e.srcElement };
return __method.apply(object, [e,target].concat(args) );
};
}
/* START CONFIG */
var nicEditorConfig = bkClass.extend({
buttons : {
'bold' : {name : __('Click to Bold'), command : 'Bold', tags : ['B','STRONG'], css : {'font-weight' : 'bold'}, key : 'b'},
'italic' : {name : __('Click to Italic'), command : 'Italic', tags : ['EM','I'], css : {'font-style' : 'italic'}, key : 'i'},
'underline' : {name : __('Click to Underline'), command : 'Underline', tags : ['U'], css : {'text-decoration' : 'underline'}, key : 'u'},
'left' : {name : __('Left Align'), command : 'justifyleft', noActive : true},
'center' : {name : __('Center Align'), command : 'justifycenter', noActive : true},
'right' : {name : __('Right Align'), command : 'justifyright', noActive : true},
'justify' : {name : __('Justify Align'), command : 'justifyfull', noActive : true},
'ol' : {name : __('Insert Ordered List'), command : 'insertorderedlist', tags : ['OL']},
'ul' : {name : __('Insert Unordered List'), command : 'insertunorderedlist', tags : ['UL']},
'subscript' : {name : __('Click to Subscript'), command : 'subscript', tags : ['SUB']},
'superscript' : {name : __('Click to Superscript'), command : 'superscript', tags : ['SUP']},
'strikethrough' : {name : __('Click to Strike Through'), command : 'strikeThrough', css : {'text-decoration' : 'line-through'}},
'removeformat' : {name : __('Remove Formatting'), command : 'removeformat', noActive : true},
'indent' : {name : __('Indent Text'), command : 'indent', noActive : true},
'outdent' : {name : __('Remove Indent'), command : 'outdent', noActive : true},
'hr' : {name : __('Horizontal Rule'), command : 'insertHorizontalRule', noActive : true}
},
iconsPath : '../nicEditorIcons.gif',
buttonList : ['save','bold','italic','underline','left','center','right','justify','ol','ul','fontSize','fontFamily','fontFormat','indent','outdent','image','upload','link','unlink','forecolor','bgcolor'],
iconList : {"xhtml":1,"bgcolor":2,"forecolor":3,"bold":4,"center":5,"hr":6,"indent":7,"italic":8,"justify":9,"left":10,"ol":11,"outdent":12,"removeformat":13,"right":14,"save":25,"strikethrough":16,"subscript":17,"superscript":18,"ul":19,"underline":20,"image":21,"link":22,"unlink":23,"close":24,"arrow":26,"upload":27}
});
/* END CONFIG */
var nicEditors = {
nicPlugins : [],
editors : [],
registerPlugin : function(plugin,options) {
this.nicPlugins.push({p : plugin, o : options});
},
allTextAreas : function(nicOptions) {
var textareas = document.getElementsByTagName("textarea");
for(var i=0;i<textareas.length;i++) {
nicEditors.editors.push(new nicEditor(nicOptions).panelInstance(textareas[i]));
}
return nicEditors.editors;
},
findEditor : function(e) {
var editors = nicEditors.editors;
for(var i=0;i<editors.length;i++) {
if(editors[i].instanceById(e)) {
return editors[i].instanceById(e);
}
}
}
};
var nicEditor = bkClass.extend({
construct : function(o) {
this.options = new nicEditorConfig();
bkExtend(this.options,o);
this.nicInstances = new Array();
this.loadedPlugins = new Array();
var plugins = nicEditors.nicPlugins;
for(var i=0;i<plugins.length;i++) {
this.loadedPlugins.push(new plugins[i].p(this,plugins[i].o));
}
nicEditors.editors.push(this);
bkLib.addEvent(document.body,'mousedown', this.selectCheck.closureListener(this) );
},
panelInstance : function(e,o) {
e = this.checkReplace($BK(e));
var panelElm = new bkElement('DIV').setStyle({width : (parseInt(e.getStyle('width')) || e.clientWidth)+'px'}).appendBefore(e);
this.setPanel(panelElm);
return this.addInstance(e,o);
},
checkReplace : function(e) {
var r = nicEditors.findEditor(e);
if(r) {
r.removeInstance(e);
r.removePanel();
}
return e;
},
addInstance : function(e,o) {
e = this.checkReplace($BK(e));
if( e.contentEditable || !!window.opera ) {
var newInstance = new nicEditorInstance(e,o,this);
} else {
var newInstance = new nicEditorIFrameInstance(e,o,this);
}
this.nicInstances.push(newInstance);
return this;
},
removeInstance : function(e) {
e = $BK(e);
var instances = this.nicInstances;
for(var i=0;i<instances.length;i++) {
if(instances[i].e == e) {
instances[i].remove();
this.nicInstances.splice(i,1);
}
}
},
removePanel : function(e) {
if(this.nicPanel) {
this.nicPanel.remove();
this.nicPanel = null;
}
},
instanceById : function(e) {
e = $BK(e);
var instances = this.nicInstances;
for(var i=0;i<instances.length;i++) {
if(instances[i].e == e) {
return instances[i];
}
}
},
setPanel : function(e) {
this.nicPanel = new nicEditorPanel($BK(e),this.options,this);
this.fireEvent('panel',this.nicPanel);
return this;
},
nicCommand : function(cmd,args) {
if(this.selectedInstance) {
this.selectedInstance.nicCommand(cmd,args);
}
},
getIcon : function(iconName,options) {
var icon = this.options.iconList[iconName];
var file = (options.iconFiles) ? options.iconFiles[iconName] : '';
return {backgroundImage : "url('"+((icon) ? this.options.iconsPath : file)+"')", backgroundPosition : ((icon) ? ((icon-1)*-18) : 0)+'px 0px'};
},
selectCheck : function(e,t) {
var found = false;
do{
if(t.className && t.className.indexOf('nicEdit') != -1) {
return false;
}
} while(t = t.parentNode);
this.fireEvent('blur',this.selectedInstance,t);
this.lastSelectedInstance = this.selectedInstance;
this.selectedInstance = null;
return false;
}
});
nicEditor = nicEditor.extend(bkEvent);
var nicEditorInstance = bkClass.extend({
isSelected : false,
construct : function(e,options,nicEditor) {
this.ne = nicEditor;
this.elm = this.e = e;
this.options = options || {};
newX = parseInt(e.getStyle('width')) || e.clientWidth;
newY = parseInt(e.getStyle('height')) || e.clientHeight;
this.initialHeight = newY-8;
var isTextarea = (e.nodeName.toLowerCase() == "textarea");
if(isTextarea || this.options.hasPanel) {
var ie7s = (bkLib.isMSIE && !((typeof document.body.style.maxHeight != "undefined") && document.compatMode == "CSS1Compat"))
var s = {width: newX+'px', border : '1px solid #ccc', borderTop : 0, overflowY : 'auto', overflowX: 'hidden' };
s[(ie7s) ? 'height' : 'maxHeight'] = (this.ne.options.maxHeight) ? this.ne.options.maxHeight+'px' : null;
this.editorContain = new bkElement('DIV').setStyle(s).appendBefore(e);
var editorElm = new bkElement('DIV').setStyle({width : (newX-8)+'px', margin: '4px', minHeight : newY+'px'}).addClass('main').appendTo(this.editorContain);
e.setStyle({display : 'none'});
editorElm.innerHTML = e.innerHTML;
if(isTextarea) {
editorElm.setContent(e.value);
this.copyElm = e;
var f = e.parentTag('FORM');
if(f) { bkLib.addEvent( f, 'submit', this.saveContent.closure(this)); }
}
editorElm.setStyle((ie7s) ? {height : newY+'px'} : {overflow: 'hidden'});
this.elm = editorElm;
}
this.ne.addEvent('blur',this.blur.closure(this));
this.init();
this.blur();
},
init : function() {
this.elm.setAttribute('contentEditable','true');
if(this.getContent() == "") {
this.setContent('<br />');
}
this.instanceDoc = document.defaultView;
this.elm.addEvent('mousedown',this.selected.closureListener(this)).addEvent('keypress',this.keyDown.closureListener(this)).addEvent('focus',this.selected.closure(this)).addEvent('blur',this.blur.closure(this)).addEvent('keyup',this.selected.closure(this));
this.ne.fireEvent('add',this);
},
remove : function() {
this.saveContent();
if(this.copyElm || this.options.hasPanel) {
this.editorContain.remove();
this.e.setStyle({'display' : 'block'});
this.ne.removePanel();
}
this.disable();
this.ne.fireEvent('remove',this);
},
disable : function() {
this.elm.setAttribute('contentEditable','false');
},
getSel : function() {
return (window.getSelection) ? window.getSelection() : document.selection;
},
getRng : function() {
var s = this.getSel();
if(!s || s.rangeCount === 0) { return; }
return (s.rangeCount > 0) ? s.getRangeAt(0) : s.createRange();
},
selRng : function(rng,s) {
if(window.getSelection) {
s.removeAllRanges();
s.addRange(rng);
} else {
rng.select();
}
},
selElm : function() {
var r = this.getRng();
if(!r) { return; }
if(r.startContainer) {
var contain = r.startContainer;
if(r.cloneContents().childNodes.length == 1) {
for(var i=0;i<contain.childNodes.length;i++) {
var rng = contain.childNodes[i].ownerDocument.createRange();
rng.selectNode(contain.childNodes[i]);
if(r.compareBoundaryPoints(Range.START_TO_START,rng) != 1 &&
r.compareBoundaryPoints(Range.END_TO_END,rng) != -1) {
return $BK(contain.childNodes[i]);
}
}
}
return $BK(contain);
} else {
return $BK((this.getSel().type == "Control") ? r.item(0) : r.parentElement());
}
},
saveRng : function() {
this.savedRange = this.getRng();
this.savedSel = this.getSel();
},
restoreRng : function() {
if(this.savedRange) {
this.selRng(this.savedRange,this.savedSel);
}
},
keyDown : function(e,t) {
if(e.ctrlKey) {
this.ne.fireEvent('key',this,e);
}
},
selected : function(e,t) {
if(!t && !(t = this.selElm)) { t = this.selElm(); }
if(!e.ctrlKey) {
var selInstance = this.ne.selectedInstance;
if(selInstance != this) {
if(selInstance) {
this.ne.fireEvent('blur',selInstance,t);
}
this.ne.selectedInstance = this;
this.ne.fireEvent('focus',selInstance,t);
}
this.ne.fireEvent('selected',selInstance,t);
this.isFocused = true;
this.elm.addClass('selected');
}
return false;
},
blur : function() {
this.isFocused = false;
this.elm.removeClass('selected');
},
saveContent : function() {
if(this.copyElm || this.options.hasPanel) {
this.ne.fireEvent('save',this);
(this.copyElm) ? this.copyElm.value = this.getContent() : this.e.innerHTML = this.getContent();
}
},
getElm : function() {
return this.elm;
},
getContent : function() {
this.content = this.getElm().innerHTML;
this.ne.fireEvent('get',this);
return this.content;
},
setContent : function(e) {
this.content = e;
this.ne.fireEvent('set',this);
this.elm.innerHTML = this.content;
},
nicCommand : function(cmd,args) {
document.execCommand(cmd,false,args);
}
});
var nicEditorIFrameInstance = nicEditorInstance.extend({
savedStyles : [],
init : function() {
var c = this.elm.innerHTML.replace(/^\s+|\s+$/g, '');
this.elm.innerHTML = '';
(!c) ? c = "<br />" : c;
this.initialContent = c;
this.elmFrame = new bkElement('iframe').setAttributes({'src' : 'javascript:;', 'frameBorder' : 0, 'allowTransparency' : 'true', 'scrolling' : 'no'}).setStyle({height: '100px', width: '100%'}).addClass('frame').appendTo(this.elm);
if(this.copyElm) { this.elmFrame.setStyle({width : (this.elm.offsetWidth-4)+'px'}); }
var styleList = ['font-size','font-family','font-weight','color'];
for(itm in styleList) {
this.savedStyles[bkLib.camelize(itm)] = this.elm.getStyle(itm);
}
setTimeout(this.initFrame.closure(this),50);
},
disable : function() {
this.elm.innerHTML = this.getContent();
},
initFrame : function() {
var fd = $BK(this.elmFrame.contentWindow.document);
fd.designMode = "on";
fd.open();
var css = this.ne.options.externalCSS;
fd.write('<html><head>'+((css) ? '<link href="'+css+'" rel="stylesheet" type="text/css" />' : '')+'</head><body id="nicEditContent" style="margin: 0 !important; background-color: transparent !important;">'+this.initialContent+'</body></html>');
fd.close();
this.frameDoc = fd;
this.frameWin = $BK(this.elmFrame.contentWindow);
this.frameContent = $BK(this.frameWin.document.body).setStyle(this.savedStyles);
this.instanceDoc = this.frameWin.document.defaultView;
this.heightUpdate();
this.frameDoc.addEvent('mousedown', this.selected.closureListener(this)).addEvent('keyup',this.heightUpdate.closureListener(this)).addEvent('keydown',this.keyDown.closureListener(this)).addEvent('keyup',this.selected.closure(this));
this.ne.fireEvent('add',this);
},
getElm : function() {
return this.frameContent;
},
setContent : function(c) {
this.content = c;
this.ne.fireEvent('set',this);
this.frameContent.innerHTML = this.content;
this.heightUpdate();
},
getSel : function() {
return (this.frameWin) ? this.frameWin.getSelection() : this.frameDoc.selection;
},
heightUpdate : function() {
this.elmFrame.style.height = Math.max(this.frameContent.offsetHeight,this.initialHeight)+'px';
},
nicCommand : function(cmd,args) {
this.frameDoc.execCommand(cmd,false,args);
setTimeout(this.heightUpdate.closure(this),100);
}
});
var nicEditorPanel = bkClass.extend({
construct : function(e,options,nicEditor) {
this.elm = e;
this.options = options;
this.ne = nicEditor;
this.panelButtons = new Array();
this.buttonList = bkExtend([],this.ne.options.buttonList);
this.panelContain = new bkElement('DIV').setStyle({overflow : 'hidden', width : '100%', border : '1px solid #cccccc', backgroundColor : '#efefef'}).addClass('panelContain');
this.panelElm = new bkElement('DIV').setStyle({margin : '2px', marginTop : '0px', zoom : 1, overflow : 'hidden'}).addClass('panel').appendTo(this.panelContain);
this.panelContain.appendTo(e);
var opt = this.ne.options;
var buttons = opt.buttons;
for(button in buttons) {
this.addButton(button,opt,true);
}
this.reorder();
e.noSelect();
},
addButton : function(buttonName,options,noOrder) {
var button = options.buttons[buttonName];
var type = (button['type']) ? eval('(typeof('+button['type']+') == "undefined") ? null : '+button['type']+';') : nicEditorButton;
var hasButton = bkLib.inArray(this.buttonList,buttonName);
if(type && (hasButton || this.ne.options.fullPanel)) {
this.panelButtons.push(new type(this.panelElm,buttonName,options,this.ne));
if(!hasButton) {
this.buttonList.push(buttonName);
}
}
},
findButton : function(itm) {
for(var i=0;i<this.panelButtons.length;i++) {
if(this.panelButtons[i].name == itm)
return this.panelButtons[i];
}
},
reorder : function() {
var bl = this.buttonList;
for(var i=0;i<bl.length;i++) {
var button = this.findButton(bl[i]);
if(button) {
this.panelElm.appendChild(button.margin);
}
}
},
remove : function() {
this.elm.remove();
}
});
var nicEditorButton = bkClass.extend({
construct : function(e,buttonName,options,nicEditor) {
this.options = options.buttons[buttonName];
this.name = buttonName;
this.ne = nicEditor;
this.elm = e;
this.margin = new bkElement('DIV').setStyle({'float' : 'left', marginTop : '2px'}).appendTo(e);
this.contain = new bkElement('DIV').setStyle({width : '20px', height : '20px'}).addClass('buttonContain').appendTo(this.margin);
this.border = new bkElement('DIV').setStyle({backgroundColor : '#efefef', border : '1px solid #efefef'}).appendTo(this.contain);
this.button = new bkElement('DIV').setStyle({width : '18px', height : '18px', overflow : 'hidden', zoom : 1, cursor : 'pointer'}).addClass('button').setStyle(this.ne.getIcon(buttonName,options)).appendTo(this.border);
this.button.addEvent('mouseover', this.hoverOn.closure(this)).addEvent('mouseout',this.hoverOff.closure(this)).addEvent('mousedown',this.mouseClick.closure(this)).noSelect();
if(!window.opera) {
this.button.onmousedown = this.button.onclick = bkLib.cancelEvent;
}
nicEditor.addEvent('selected', this.enable.closure(this)).addEvent('blur', this.disable.closure(this)).addEvent('key',this.key.closure(this));
this.disable();
this.init();
},
init : function() { },
hide : function() {
this.contain.setStyle({display : 'none'});
},
updateState : function() {
if(this.isDisabled) { this.setBg(); }
else if(this.isHover) { this.setBg('hover'); }
else if(this.isActive) { this.setBg('active'); }
else { this.setBg(); }
},
setBg : function(state) {
switch(state) {
case 'hover':
var stateStyle = {border : '1px solid #666', backgroundColor : '#ddd'};
break;
case 'active':
var stateStyle = {border : '1px solid #666', backgroundColor : '#ccc'};
break;
default:
var stateStyle = {border : '1px solid #efefef', backgroundColor : '#efefef'};
}
this.border.setStyle(stateStyle).addClass('button-'+state);
},
checkNodes : function(e) {
var elm = e;
do {
if(this.options.tags && bkLib.inArray(this.options.tags,elm.nodeName)) {
this.activate();
return true;
}
} while(elm = elm.parentNode && elm.className != "nicEdit");
elm = $BK(e);
while(elm.nodeType == 3) {
elm = $BK(elm.parentNode);
}
if(this.options.css) {
for(itm in this.options.css) {
if(elm.getStyle(itm,this.ne.selectedInstance.instanceDoc) == this.options.css[itm]) {
this.activate();
return true;
}
}
}
this.deactivate();
return false;
},
activate : function() {
if(!this.isDisabled) {
this.isActive = true;
this.updateState();
this.ne.fireEvent('buttonActivate',this);
}
},
deactivate : function() {
this.isActive = false;
this.updateState();
if(!this.isDisabled) {
this.ne.fireEvent('buttonDeactivate',this);
}
},
enable : function(ins,t) {
this.isDisabled = false;
this.contain.setStyle({'opacity' : 1}).addClass('buttonEnabled');
this.updateState();
this.checkNodes(t);
},
disable : function(ins,t) {
this.isDisabled = true;
this.contain.setStyle({'opacity' : 0.6}).removeClass('buttonEnabled');
this.updateState();
},
toggleActive : function() {
(this.isActive) ? this.deactivate() : this.activate();
},
hoverOn : function() {
if(!this.isDisabled) {
this.isHover = true;
this.updateState();
this.ne.fireEvent("buttonOver",this);
}
},
hoverOff : function() {
this.isHover = false;
this.updateState();
this.ne.fireEvent("buttonOut",this);
},
mouseClick : function() {
if(this.options.command) {
this.ne.nicCommand(this.options.command,this.options.commandArgs);
if(!this.options.noActive) {
this.toggleActive();
}
}
this.ne.fireEvent("buttonClick",this);
},
key : function(nicInstance,e) {
if(this.options.key && e.ctrlKey && String.fromCharCode(e.keyCode || e.charCode).toLowerCase() == this.options.key) {
this.mouseClick();
if(e.preventDefault) e.preventDefault();
}
}
});
var nicPlugin = bkClass.extend({
construct : function(nicEditor,options) {
this.options = options;
this.ne = nicEditor;
this.ne.addEvent('panel',this.loadPanel.closure(this));
this.init();
},
loadPanel : function(np) {
var buttons = this.options.buttons;
for(var button in buttons) {
np.addButton(button,this.options);
}
np.reorder();
},
init : function() { }
});
/* START CONFIG */
var nicPaneOptions = { };
/* END CONFIG */
var nicEditorPane = bkClass.extend({
construct : function(elm,nicEditor,options,openButton) {
this.ne = nicEditor;
this.elm = elm;
this.pos = elm.pos();
this.contain = new bkElement('div').setStyle({zIndex : '99999', overflow : 'hidden', position : 'absolute', left : this.pos[0]+'px', top : this.pos[1]+'px'})
this.pane = new bkElement('div').setStyle({fontSize : '12px', border : '1px solid #ccc', 'overflow': 'hidden', padding : '4px', textAlign: 'left', backgroundColor : '#ffffc9'}).addClass('pane').setStyle(options).appendTo(this.contain);
if(openButton && !openButton.options.noClose) {
this.close = new bkElement('div').setStyle({'float' : 'right', height: '16px', width : '16px', cursor : 'pointer'}).setStyle(this.ne.getIcon('close',nicPaneOptions)).addEvent('mousedown',openButton.removePane.closure(this)).appendTo(this.pane);
}
this.contain.noSelect().appendTo(document.body);
this.position();
this.init();
},
init : function() { },
position : function() {
if(this.ne.nicPanel) {
var panelElm = this.ne.nicPanel.elm;
var panelPos = panelElm.pos();
var newLeft = panelPos[0]+parseInt(panelElm.getStyle('width'))-(parseInt(this.pane.getStyle('width'))+8);
if(newLeft < this.pos[0]) {
this.contain.setStyle({left : newLeft+'px'});
}
}
},
toggle : function() {
this.isVisible = !this.isVisible;
this.contain.setStyle({display : ((this.isVisible) ? 'block' : 'none')});
},
remove : function() {
if(this.contain) {
this.contain.remove();
this.contain = null;
}
},
append : function(c) {
c.appendTo(this.pane);
},
setContent : function(c) {
this.pane.setContent(c);
}
});
var nicEditorAdvancedButton = nicEditorButton.extend({
init : function() {
this.ne.addEvent('selected',this.removePane.closure(this)).addEvent('blur',this.removePane.closure(this));
},
mouseClick : function() {
if(!this.isDisabled) {
if(this.pane && this.pane.pane) {
this.removePane();
} else {
this.pane = new nicEditorPane(this.contain,this.ne,{width : (this.width || '270px'), backgroundColor : '#fff'},this);
this.addPane();
this.ne.selectedInstance.saveRng();
}
}
},
addForm : function(f,elm) {
this.form = new bkElement('form').addEvent('submit',this.submit.closureListener(this));
this.pane.append(this.form);
this.inputs = {};
for(itm in f) {
var field = f[itm];
var val = '';
if(elm) {
val = elm.getAttribute(itm);
}
if(!val) {
val = field['value'] || '';
}
var type = f[itm].type;
if(type == 'title') {
new bkElement('div').setContent(field.txt).setStyle({fontSize : '14px', fontWeight: 'bold', padding : '0px', margin : '2px 0'}).appendTo(this.form);
} else {
var contain = new bkElement('div').setStyle({overflow : 'hidden', clear : 'both'}).appendTo(this.form);
if(field.txt) {
new bkElement('label').setAttributes({'for' : itm}).setContent(field.txt).setStyle({margin : '2px 4px', fontSize : '13px', width: '50px', lineHeight : '20px', textAlign : 'right', 'float' : 'left'}).appendTo(contain);
}
switch(type) {
case 'text':
this.inputs[itm] = new bkElement('input').setAttributes({id : itm, 'value' : val, 'type' : 'text'}).setStyle({margin : '2px 0', fontSize : '13px', 'float' : 'left', height : '20px', border : '1px solid #ccc', overflow : 'hidden'}).setStyle(field.style).appendTo(contain);
break;
case 'select':
this.inputs[itm] = new bkElement('select').setAttributes({id : itm}).setStyle({border : '1px solid #ccc', 'float' : 'left', margin : '2px 0'}).appendTo(contain);
for(opt in field.options) {
var o = new bkElement('option').setAttributes({value : opt, selected : (opt == val) ? 'selected' : ''}).setContent(field.options[opt]).appendTo(this.inputs[itm]);
}
break;
case 'content':
this.inputs[itm] = new bkElement('textarea').setAttributes({id : itm}).setStyle({border : '1px solid #ccc', 'float' : 'left'}).setStyle(field.style).appendTo(contain);
this.inputs[itm].value = val;
}
}
}
new bkElement('input').setAttributes({'type' : 'submit'}).setStyle({backgroundColor : '#efefef',border : '1px solid #ccc', margin : '3px 0', 'float' : 'left', 'clear' : 'both'}).appendTo(this.form);
this.form.onsubmit = bkLib.cancelEvent;
},
submit : function() { },
findElm : function(tag,attr,val) {
var list = this.ne.selectedInstance.getElm().getElementsByTagName(tag);
for(var i=0;i<list.length;i++) {
if(list[i].getAttribute(attr) == val) {
return $BK(list[i]);
}
}
},
removePane : function() {
if(this.pane) {
this.pane.remove();
this.pane = null;
this.ne.selectedInstance.restoreRng();
}
}
});
var nicButtonTips = bkClass.extend({
construct : function(nicEditor) {
this.ne = nicEditor;
nicEditor.addEvent('buttonOver',this.show.closure(this)).addEvent('buttonOut',this.hide.closure(this));
},
show : function(button) {
this.timer = setTimeout(this.create.closure(this,button),400);
},
create : function(button) {
this.timer = null;
if(!this.pane) {
this.pane = new nicEditorPane(button.button,this.ne,{fontSize : '12px', marginTop : '5px'});
this.pane.setContent(button.options.name);
}
},
hide : function(button) {
if(this.timer) {
clearTimeout(this.timer);
}
if(this.pane) {
this.pane = this.pane.remove();
}
}
});
nicEditors.registerPlugin(nicButtonTips);
/* START CONFIG */
var nicSelectOptions = {
buttons : {
'fontSize' : {name : __('Select Font Size'), type : 'nicEditorFontSizeSelect', command : 'fontsize'},
'fontFamily' : {name : __('Select Font Family'), type : 'nicEditorFontFamilySelect', command : 'fontname'},
'fontFormat' : {name : __('Select Font Format'), type : 'nicEditorFontFormatSelect', command : 'formatBlock'}
}
};
/* END CONFIG */
var nicEditorSelect = bkClass.extend({
construct : function(e,buttonName,options,nicEditor) {
this.options = options.buttons[buttonName];
this.elm = e;
this.ne = nicEditor;
this.name = buttonName;
this.selOptions = new Array();
this.margin = new bkElement('div').setStyle({'float' : 'left', margin : '2px 1px 0 1px'}).appendTo(this.elm);
this.contain = new bkElement('div').setStyle({width: '90px', height : '20px', cursor : 'pointer', overflow: 'hidden'}).addClass('selectContain').addEvent('click',this.toggle.closure(this)).appendTo(this.margin);
this.items = new bkElement('div').setStyle({overflow : 'hidden', zoom : 1, border: '1px solid #ccc', paddingLeft : '3px', backgroundColor : '#fff'}).appendTo(this.contain);
this.control = new bkElement('div').setStyle({overflow : 'hidden', 'float' : 'right', height: '18px', width : '16px'}).addClass('selectControl').setStyle(this.ne.getIcon('arrow',options)).appendTo(this.items);
this.txt = new bkElement('div').setStyle({overflow : 'hidden', 'float' : 'left', width : '66px', height : '14px', marginTop : '1px', fontFamily : 'sans-serif', textAlign : 'center', fontSize : '12px'}).addClass('selectTxt').appendTo(this.items);
if(!window.opera) {
this.contain.onmousedown = this.control.onmousedown = this.txt.onmousedown = bkLib.cancelEvent;
}
this.margin.noSelect();
this.ne.addEvent('selected', this.enable.closure(this)).addEvent('blur', this.disable.closure(this));
this.disable();
this.init();
},
disable : function() {
this.isDisabled = true;
this.close();
this.contain.setStyle({opacity : 0.6});
},
enable : function(t) {
this.isDisabled = false;
this.close();
this.contain.setStyle({opacity : 1});
},
setDisplay : function(txt) {
this.txt.setContent(txt);
},
toggle : function() {
if(!this.isDisabled) {
(this.pane) ? this.close() : this.open();
}
},
open : function() {
this.pane = new nicEditorPane(this.items,this.ne,{width : '88px', padding: '0px', borderTop : 0, borderLeft : '1px solid #ccc', borderRight : '1px solid #ccc', borderBottom : '0px', backgroundColor : '#fff'});
for(var i=0;i<this.selOptions.length;i++) {
var opt = this.selOptions[i];
var itmContain = new bkElement('div').setStyle({overflow : 'hidden', borderBottom : '1px solid #ccc', width: '88px', textAlign : 'left', overflow : 'hidden', cursor : 'pointer'});
var itm = new bkElement('div').setStyle({padding : '0px 4px'}).setContent(opt[1]).appendTo(itmContain).noSelect();
itm.addEvent('click',this.update.closure(this,opt[0])).addEvent('mouseover',this.over.closure(this,itm)).addEvent('mouseout',this.out.closure(this,itm)).setAttributes('id',opt[0]);
this.pane.append(itmContain);
if(!window.opera) {
itm.onmousedown = bkLib.cancelEvent;
}
}
},
close : function() {
if(this.pane) {
this.pane = this.pane.remove();
}
},
over : function(opt) {
opt.setStyle({backgroundColor : '#ccc'});
},
out : function(opt) {
opt.setStyle({backgroundColor : '#fff'});
},
add : function(k,v) {
this.selOptions.push(new Array(k,v));
},
update : function(elm) {
this.ne.nicCommand(this.options.command,elm);
this.close();
}
});
var nicEditorFontSizeSelect = nicEditorSelect.extend({
sel : {1 : '1 (8pt)', 2 : '2 (10pt)', 3 : '3 (12pt)', 4 : '4 (14pt)', 5 : '5 (18pt)', 6 : '6 (24pt)'},
init : function() {
this.setDisplay('Font Size...');
for(itm in this.sel) {
this.add(itm,'<font size="'+itm+'">'+this.sel[itm]+'</font>');
}
}
});
var nicEditorFontFamilySelect = nicEditorSelect.extend({
sel : {'arial' : 'Arial','comic sans ms' : 'Comic Sans','courier new' : 'Courier New','georgia' : 'Georgia', 'helvetica' : 'Helvetica', 'impact' : 'Impact', 'times new roman' : 'Times', 'trebuchet ms' : 'Trebuchet', 'verdana' : 'Verdana'},
init : function() {
this.setDisplay('Font Family...');
for(itm in this.sel) {
this.add(itm,'<font face="'+itm+'">'+this.sel[itm]+'</font>');
}
}
});
var nicEditorFontFormatSelect = nicEditorSelect.extend({
sel : {'p' : 'Paragraph', 'pre' : 'Pre', 'h6' : 'Heading 6', 'h5' : 'Heading 5', 'h4' : 'Heading 4', 'h3' : 'Heading 3', 'h2' : 'Heading 2', 'h1' : 'Heading 1'},
init : function() {
this.setDisplay('Font Format...');
for(itm in this.sel) {
var tag = itm.toUpperCase();
this.add('<'+tag+'>','<'+itm+' style="padding: 0px; margin: 0px;">'+this.sel[itm]+'</'+tag+'>');
}
}
});
nicEditors.registerPlugin(nicPlugin,nicSelectOptions);
/* START CONFIG */
var nicLinkOptions = {
buttons : {
'link' : {name : 'Add Link', type : 'nicLinkButton', tags : ['A']},
'unlink' : {name : 'Remove Link', command : 'unlink', noActive : true}
}
};
/* END CONFIG */
var nicLinkButton = nicEditorAdvancedButton.extend({
addPane : function() {
this.ln = this.ne.selectedInstance.selElm().parentTag('A');
this.addForm({
'' : {type : 'title', txt : 'Add/Edit Link'},
'href' : {type : 'text', txt : 'URL', value : 'http://', style : {width: '150px'}},
'title' : {type : 'text', txt : 'Title'},
'target' : {type : 'select', txt : 'Open In', options : {'' : 'Current Window', '_blank' : 'New Window'},style : {width : '100px'}}
},this.ln);
},
submit : function(e) {
var url = this.inputs['href'].value;
if(url == "http://" || url == "") {
alert("You must enter a URL to Create a Link");
return false;
}
this.removePane();
if(!this.ln) {
var tmp = 'javascript:nicTemp();';
this.ne.nicCommand("createlink",tmp);
this.ln = this.findElm('A','href',tmp);
}
if(this.ln) {
this.ln.setAttributes({
href : this.inputs['href'].value,
title : this.inputs['title'].value,
target : this.inputs['target'].options[this.inputs['target'].selectedIndex].value
});
}
}
});
nicEditors.registerPlugin(nicPlugin,nicLinkOptions);
/* START CONFIG */
var nicColorOptions = {
buttons : {
'forecolor' : {name : __('Change Text Color'), type : 'nicEditorColorButton', noClose : true},
'bgcolor' : {name : __('Change Background Color'), type : 'nicEditorBgColorButton', noClose : true}
}
};
/* END CONFIG */
var nicEditorColorButton = nicEditorAdvancedButton.extend({
addPane : function() {
var colorList = {0 : '00',1 : '33',2 : '66',3 :'99',4 : 'CC',5 : 'FF'};
var colorItems = new bkElement('DIV').setStyle({width: '270px'});
for(var r in colorList) {
for(var b in colorList) {
for(var g in colorList) {
var colorCode = '#'+colorList[r]+colorList[g]+colorList[b];
var colorSquare = new bkElement('DIV').setStyle({'cursor' : 'pointer', 'height' : '15px', 'float' : 'left'}).appendTo(colorItems);
var colorBorder = new bkElement('DIV').setStyle({border: '2px solid '+colorCode}).appendTo(colorSquare);
var colorInner = new bkElement('DIV').setStyle({backgroundColor : colorCode, overflow : 'hidden', width : '11px', height : '11px'}).addEvent('click',this.colorSelect.closure(this,colorCode)).addEvent('mouseover',this.on.closure(this,colorBorder)).addEvent('mouseout',this.off.closure(this,colorBorder,colorCode)).appendTo(colorBorder);
if(!window.opera) {
colorSquare.onmousedown = colorInner.onmousedown = bkLib.cancelEvent;
}
}
}
}
this.pane.append(colorItems.noSelect());
},
colorSelect : function(c) {
this.ne.nicCommand('foreColor',c);
this.removePane();
},
on : function(colorBorder) {
colorBorder.setStyle({border : '2px solid #000'});
},
off : function(colorBorder,colorCode) {
colorBorder.setStyle({border : '2px solid '+colorCode});
}
});
var nicEditorBgColorButton = nicEditorColorButton.extend({
colorSelect : function(c) {
this.ne.nicCommand('hiliteColor',c);
this.removePane();
}
});
nicEditors.registerPlugin(nicPlugin,nicColorOptions);
/* START CONFIG */
var nicImageOptions = {
buttons : {
'image' : {name : 'Add Image', type : 'nicImageButton', tags : ['IMG']}
}
};
/* END CONFIG */
var nicImageButton = nicEditorAdvancedButton.extend({
addPane : function() {
this.im = this.ne.selectedInstance.selElm().parentTag('IMG');
this.addForm({
'' : {type : 'title', txt : 'Add/Edit Image'},
'src' : {type : 'text', txt : 'URL', 'value' : 'http://', style : {width: '150px'}},
'alt' : {type : 'text', txt : 'Alt Text', style : {width: '100px'}},
'align' : {type : 'select', txt : 'Align', options : {none : 'Default','left' : 'Left', 'right' : 'Right'}}
},this.im);
},
submit : function(e) {
var src = this.inputs['src'].value;
if(src == "" || src == "http://") {
alert("You must enter a Image URL to insert");
return false;
}
this.removePane();
if(!this.im) {
var tmp = 'javascript:nicImTemp();';
this.ne.nicCommand("insertImage",tmp);
this.im = this.findElm('IMG','src',tmp);
}
if(this.im) {
this.im.setAttributes({
src : this.inputs['src'].value,
alt : this.inputs['alt'].value,
align : this.inputs['align'].value
});
}
}
});
nicEditors.registerPlugin(nicPlugin,nicImageOptions);
/* START CONFIG */
var nicSaveOptions = {
buttons : {
'save' : {name : __('Save this content'), type : 'nicEditorSaveButton'}
}
};
/* END CONFIG */
var nicEditorSaveButton = nicEditorButton.extend({
init : function() {
if(!this.ne.options.onSave) {
this.margin.setStyle({'display' : 'none'});
}
},
mouseClick : function() {
var onSave = this.ne.options.onSave;
var selectedInstance = this.ne.selectedInstance;
onSave(selectedInstance.getContent(), selectedInstance.elm.id, selectedInstance);
}
});
nicEditors.registerPlugin(nicPlugin,nicSaveOptions);
/* START CONFIG */
var nicUploadOptions = {
buttons : {
'upload' : {name : 'Upload Image', type : 'nicUploadButton'}
}
};
/* END CONFIG */
var nicUploadButton = nicEditorAdvancedButton.extend({
nicURI : 'http://api.imgur.com/2/upload.json',
errorText : 'Failed to upload image',
addPane : function() {
if(typeof window.FormData === "undefined") {
return this.onError("Image uploads are not supported in this browser, use Chrome, Firefox, or Safari instead.");
}
this.im = this.ne.selectedInstance.selElm().parentTag('IMG');
var container = new bkElement('div')
.setStyle({ padding: '10px' })
.appendTo(this.pane.pane);
new bkElement('div')
.setStyle({ fontSize: '14px', fontWeight : 'bold', paddingBottom: '5px' })
.setContent('Insert an Image')
.appendTo(container);
this.fileInput = new bkElement('input')
.setAttributes({ 'type' : 'file' })
.appendTo(container);
this.progress = new bkElement('progress')
.setStyle({ width : '100%', display: 'none' })
.setAttributes('max', 100)
.appendTo(container);
this.fileInput.onchange = this.uploadFile.closure(this);
},
onError : function(msg) {
this.removePane();
alert(msg || "Failed to upload image");
},
uploadFile : function() {
var file = this.fileInput.files[0];
if (!file || !file.type.match(/image.*/)) {
this.onError("Only image files can be uploaded");
return;
}
this.fileInput.setStyle({ display: 'none' });
this.setProgress(0);
var fd = new FormData(); // https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/
fd.append("image", file);
fd.append("key", "b7ea18a4ecbda8e92203fa4968d10660");
var xhr = new XMLHttpRequest();
xhr.open("POST", this.ne.options.uploadURI || this.nicURI);
xhr.onload = function() {
try {
var res = JSON.parse(xhr.responseText);
} catch(e) {
return this.onError();
}
this.onUploaded(res.upload);
}.closure(this);
xhr.onerror = this.onError.closure(this);
xhr.upload.onprogress = function(e) {
this.setProgress(e.loaded / e.total);
}.closure(this);
xhr.send(fd);
},
setProgress : function(percent) {
this.progress.setStyle({ display: 'block' });
if(percent < .98) {
this.progress.value = percent;
} else {
this.progress.removeAttribute('value');
}
},
onUploaded : function(options) {
this.removePane();
var src = options.links.original;
if(!this.im) {
this.ne.selectedInstance.restoreRng();
var tmp = 'javascript:nicImTemp();';
this.ne.nicCommand("insertImage", src);
this.im = this.findElm('IMG','src', src);
}
var w = parseInt(this.ne.selectedInstance.elm.getStyle('width'));
if(this.im) {
this.im.setAttributes({
src : src,
width : (w && options.image.width) ? Math.min(w, options.image.width) : ''
});
}
}
});
nicEditors.registerPlugin(nicPlugin,nicUploadOptions);
var nicXHTML = bkClass.extend({
stripAttributes : ['_moz_dirty','_moz_resizing','_extended'],
noShort : ['style','title','script','textarea','a'],
cssReplace : {'font-weight:bold;' : 'strong', 'font-style:italic;' : 'em'},
sizes : {1 : 'xx-small', 2 : 'x-small', 3 : 'small', 4 : 'medium', 5 : 'large', 6 : 'x-large'},
construct : function(nicEditor) {
this.ne = nicEditor;
if(this.ne.options.xhtml) {
nicEditor.addEvent('get',this.cleanup.closure(this));
}
},
cleanup : function(ni) {
var node = ni.getElm();
var xhtml = this.toXHTML(node);
ni.content = xhtml;
},
toXHTML : function(n,r,d) {
var txt = '';
var attrTxt = '';
var cssTxt = '';
var nType = n.nodeType;
var nName = n.nodeName.toLowerCase();
var nChild = n.hasChildNodes && n.hasChildNodes();
var extraNodes = new Array();
switch(nType) {
case 1:
var nAttributes = n.attributes;
switch(nName) {
case 'b':
nName = 'strong';
break;
case 'i':
nName = 'em';
break;
case 'font':
nName = 'span';
break;
}
if(r) {
for(var i=0;i<nAttributes.length;i++) {
var attr = nAttributes[i];
var attributeName = attr.nodeName.toLowerCase();
var attributeValue = attr.nodeValue;
if(!attr.specified || !attributeValue || bkLib.inArray(this.stripAttributes,attributeName) || typeof(attributeValue) == "function") {
continue;
}
switch(attributeName) {
case 'style':
var css = attributeValue.replace(/ /g,"");
for(itm in this.cssReplace) {
if(css.indexOf(itm) != -1) {
extraNodes.push(this.cssReplace[itm]);
css = css.replace(itm,'');
}
}
cssTxt += css;
attributeValue = "";
break;
case 'class':
attributeValue = attributeValue.replace("Apple-style-span","");
break;
case 'size':
cssTxt += "font-size:"+this.sizes[attributeValue]+';';
attributeValue = "";
break;
}
if(attributeValue) {
attrTxt += ' '+attributeName+'="'+attributeValue+'"';
}
}
if(cssTxt) {
attrTxt += ' style="'+cssTxt+'"';
}
for(var i=0;i<extraNodes.length;i++) {
txt += '<'+extraNodes[i]+'>';
}
if(attrTxt == "" && nName == "span") {
r = false;
}
if(r) {
txt += '<'+nName;
if(nName != 'br') {
txt += attrTxt;
}
}
}
if(!nChild && !bkLib.inArray(this.noShort,attributeName)) {
if(r) {
txt += ' />';
}
} else {
if(r) {
txt += '>';
}
for(var i=0;i<n.childNodes.length;i++) {
var results = this.toXHTML(n.childNodes[i],true,true);
if(results) {
txt += results;
}
}
}
if(r && nChild) {
txt += '</'+nName+'>';
}
for(var i=0;i<extraNodes.length;i++) {
txt += '</'+extraNodes[i]+'>';
}
break;
case 3:
//if(n.nodeValue != '\n') {
txt += n.nodeValue;
//}
break;
}
return txt;
}
});
nicEditors.registerPlugin(nicXHTML);
var nicBBCode = bkClass.extend({
construct : function(nicEditor) {
this.ne = nicEditor;
if(this.ne.options.bbCode) {
nicEditor.addEvent('get',this.bbGet.closure(this));
nicEditor.addEvent('set',this.bbSet.closure(this));
var loadedPlugins = this.ne.loadedPlugins;
for(itm in loadedPlugins) {
if(loadedPlugins[itm].toXHTML) {
this.xhtml = loadedPlugins[itm];
}
}
}
},
bbGet : function(ni) {
var xhtml = this.xhtml.toXHTML(ni.getElm());
ni.content = this.toBBCode(xhtml);
},
bbSet : function(ni) {
ni.content = this.fromBBCode(ni.content);
},
toBBCode : function(xhtml) {
function rp(r,m) {
xhtml = xhtml.replace(r,m);
}
rp(/\n/gi,"");
rp(/<strong>(.*?)<\/strong>/gi,"[b]$1[/b]");
rp(/<em>(.*?)<\/em>/gi,"[i]$1[/i]");
rp(/<span.*?style="text-decoration:underline;">(.*?)<\/span>/gi,"[u]$1[/u]");
rp(/<ul>(.*?)<\/ul>/gi,"[list]$1[/list]");
rp(/<li>(.*?)<\/li>/gi,"[*]$1[/*]");
rp(/<ol>(.*?)<\/ol>/gi,"[list=1]$1[/list]");
rp(/<img.*?src="(.*?)".*?>/gi,"[img]$1[/img]");
rp(/<a.*?href="(.*?)".*?>(.*?)<\/a>/gi,"[url=$1]$2[/url]");
rp(/<br.*?>/gi,"\n");
rp(/<.*?>.*?<\/.*?>/gi,"");
return xhtml;
},
fromBBCode : function(bbCode) {
function rp(r,m) {
bbCode = bbCode.replace(r,m);
}
rp(/\[b\](.*?)\[\/b\]/gi,"<strong>$1</strong>");
rp(/\[i\](.*?)\[\/i\]/gi,"<em>$1</em>");
rp(/\[u\](.*?)\[\/u\]/gi,"<span style=\"text-decoration:underline;\">$1</span>");
rp(/\[list\](.*?)\[\/list\]/gi,"<ul>$1</ul>");
rp(/\[list=1\](.*?)\[\/list\]/gi,"<ol>$1</ol>");
rp(/\[\*\](.*?)\[\/\*\]/gi,"<li>$1</li>");
rp(/\[img\](.*?)\[\/img\]/gi,"<img src=\"$1\" />");
rp(/\[url=(.*?)\](.*?)\[\/url\]/gi,"<a href=\"$1\">$2</a>");
rp(/\n/gi,"<br />");
//rp(/\[.*?\](.*?)\[\/.*?\]/gi,"$1");
return bbCode;
}
});
nicEditors.registerPlugin(nicBBCode);
nicEditor = nicEditor.extend({
floatingPanel : function() {
this.floating = new bkElement('DIV').setStyle({position: 'absolute', top : '-1000px'}).appendTo(document.body);
this.addEvent('focus', this.reposition.closure(this)).addEvent('blur', this.hide.closure(this));
this.setPanel(this.floating);
},
reposition : function() {
var e = this.selectedInstance.e;
this.floating.setStyle({ width : (parseInt(e.getStyle('width')) || e.clientWidth)+'px' });
var top = e.offsetTop-this.floating.offsetHeight;
if(top < 0) {
top = e.offsetTop+e.offsetHeight;
}
this.floating.setStyle({ top : top+'px', left : e.offsetLeft+'px', display : 'block' });
},
hide : function() {
this.floating.setStyle({ top : '-1000px'});
}
});
/* START CONFIG */
var nicCodeOptions = {
buttons : {
'xhtml' : {name : 'Edit HTML', type : 'nicCodeButton'}
}
};
/* END CONFIG */
var nicCodeButton = nicEditorAdvancedButton.extend({
width : '350px',
addPane : function() {
this.addForm({
'' : {type : 'title', txt : 'Edit HTML'},
'code' : {type : 'content', 'value' : this.ne.selectedInstance.getContent(), style : {width: '340px', height : '200px'}}
});
},
submit : function(e) {
var code = this.inputs['code'].value;
this.ne.selectedInstance.setContent(code);
this.removePane();
}
});
nicEditors.registerPlugin(nicPlugin,nicCodeOptions);
| drupaals/demo.com | d7/sites/all/libraries/nicedit/nicEdit.js | JavaScript | gpl-2.0 | 50,796 |
/* ====================================================================
* 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.jcc;
public class PythonVM {
static protected PythonVM vm;
static {
System.loadLibrary("jcc");
}
static public PythonVM start(String programName, String[] args)
{
if (vm == null)
{
vm = new PythonVM();
vm.init(programName, args);
}
return vm;
}
static public PythonVM start(String programName)
{
return start(programName, null);
}
static public PythonVM get()
{
return vm;
}
protected PythonVM()
{
}
protected native void init(String programName, String[] args);
public native Object instantiate(String moduleName, String className)
throws PythonException;
}
| adamdoupe/enemy-of-the-state | jcc/java/org/apache/jcc/PythonVM.java | Java | gpl-2.0 | 1,466 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math.analysis.interpolation;
import org.apache.commons.math.MathException;
import org.apache.commons.math.exception.NonMonotonousSequenceException;
import org.apache.commons.math.exception.DimensionMismatchException;
import org.apache.commons.math.exception.NumberIsTooSmallException;
import org.apache.commons.math.TestUtils;
import org.apache.commons.math.analysis.UnivariateRealFunction;
import org.apache.commons.math.analysis.polynomials.PolynomialFunction;
import org.apache.commons.math.analysis.polynomials.PolynomialSplineFunction;
import org.junit.Assert;
import org.junit.Test;
/**
* Test the LinearInterpolator.
*/
public class LinearInterpolatorTest {
/** error tolerance for spline interpolator value at knot points */
protected double knotTolerance = 1E-12;
/** error tolerance for interpolating polynomial coefficients */
protected double coefficientTolerance = 1E-6;
/** error tolerance for interpolated values */
protected double interpolationTolerance = 1E-12;
@Test
public void testInterpolateLinearDegenerateTwoSegment()
throws Exception {
double x[] = { 0.0, 0.5, 1.0 };
double y[] = { 0.0, 0.5, 1.0 };
UnivariateRealInterpolator i = new LinearInterpolator();
UnivariateRealFunction f = i.interpolate(x, y);
verifyInterpolation(f, x, y);
// Verify coefficients using analytical values
PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials();
double target[] = {y[0], 1d};
TestUtils.assertEquals(polynomials[0].getCoefficients(), target, coefficientTolerance);
target = new double[]{y[1], 1d};
TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance);
// Check interpolation
Assert.assertEquals(0.0,f.value(0.0), interpolationTolerance);
Assert.assertEquals(0.4,f.value(0.4), interpolationTolerance);
Assert.assertEquals(1.0,f.value(1.0), interpolationTolerance);
}
@Test
public void testInterpolateLinearDegenerateThreeSegment()
throws Exception {
double x[] = { 0.0, 0.5, 1.0, 1.5 };
double y[] = { 0.0, 0.5, 1.0, 1.5 };
UnivariateRealInterpolator i = new LinearInterpolator();
UnivariateRealFunction f = i.interpolate(x, y);
verifyInterpolation(f, x, y);
// Verify coefficients using analytical values
PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials();
double target[] = {y[0], 1d};
TestUtils.assertEquals(polynomials[0].getCoefficients(), target, coefficientTolerance);
target = new double[]{y[1], 1d};
TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance);
target = new double[]{y[2], 1d};
TestUtils.assertEquals(polynomials[2].getCoefficients(), target, coefficientTolerance);
// Check interpolation
Assert.assertEquals(0,f.value(0), interpolationTolerance);
Assert.assertEquals(1.4,f.value(1.4), interpolationTolerance);
Assert.assertEquals(1.5,f.value(1.5), interpolationTolerance);
}
@Test
public void testInterpolateLinear() throws Exception {
double x[] = { 0.0, 0.5, 1.0 };
double y[] = { 0.0, 0.5, 0.0 };
UnivariateRealInterpolator i = new LinearInterpolator();
UnivariateRealFunction f = i.interpolate(x, y);
verifyInterpolation(f, x, y);
// Verify coefficients using analytical values
PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials();
double target[] = {y[0], 1d};
TestUtils.assertEquals(polynomials[0].getCoefficients(), target, coefficientTolerance);
target = new double[]{y[1], -1d};
TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance);
}
@Test
public void testIllegalArguments() throws MathException {
// Data set arrays of different size.
UnivariateRealInterpolator i = new LinearInterpolator();
try {
double xval[] = { 0.0, 1.0 };
double yval[] = { 0.0, 1.0, 2.0 };
i.interpolate(xval, yval);
Assert.fail("Failed to detect data set array with different sizes.");
} catch (DimensionMismatchException iae) {
// Expected.
}
// X values not sorted.
try {
double xval[] = { 0.0, 1.0, 0.5 };
double yval[] = { 0.0, 1.0, 2.0 };
i.interpolate(xval, yval);
Assert.fail("Failed to detect unsorted arguments.");
} catch (NonMonotonousSequenceException iae) {
// Expected.
}
// Not enough data to interpolate.
try {
double xval[] = { 0.0 };
double yval[] = { 0.0 };
i.interpolate(xval, yval);
Assert.fail("Failed to detect unsorted arguments.");
} catch (NumberIsTooSmallException iae) {
// Expected.
}
}
/**
* verifies that f(x[i]) = y[i] for i = 0..n-1 where n is common length.
*/
protected void verifyInterpolation(UnivariateRealFunction f, double x[], double y[])
throws Exception{
for (int i = 0; i < x.length; i++) {
Assert.assertEquals(f.value(x[i]), y[i], knotTolerance);
}
}
}
| SpoonLabs/astor | examples/math_63/src/test/java/org/apache/commons/math/analysis/interpolation/LinearInterpolatorTest.java | Java | gpl-2.0 | 6,231 |
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2014 CoNWeT Lab., Universidad Politécnica de Madrid
# This file is part of Wirecloud.
# Wirecloud is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Wirecloud is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with Wirecloud. If not, see <http://www.gnu.org/licenses/>.
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.translation import ugettext as _
class Application(models.Model):
client_id = models.CharField(_('Client ID'), max_length=40, blank=False, primary_key=True)
client_secret = models.CharField(_('Client secret'), max_length=40, blank=False)
name = models.CharField(_('Application Name'), max_length=40, blank=False)
home_url = models.CharField(_('URL'), max_length=255, blank=False)
redirect_uri = models.CharField(_('Redirect URI'), max_length=255, blank=True)
def __unicode__(self):
return unicode(self.client_id)
class Code(models.Model):
client = models.ForeignKey(Application)
user = models.ForeignKey(User)
scope = models.CharField(_('Scope'), max_length=255, blank=True)
code = models.CharField(_('Code'), max_length=255, blank=False)
creation_timestamp = models.CharField(_('Creation timestamp'), max_length=40, blank=False)
expires_in = models.CharField(_('Expires in'), max_length=40, blank=True)
class Meta:
unique_together = ('client', 'code')
def __unicode__(self):
return unicode(self.code)
class Token(models.Model):
token = models.CharField(_('Token'), max_length=40, blank=False, primary_key=True)
client = models.ForeignKey(Application)
user = models.ForeignKey(User)
scope = models.CharField(_('Scope'), max_length=255, blank=True)
token_type = models.CharField(_('Token type'), max_length=10, blank=False)
refresh_token = models.CharField(_('Refresh token'), max_length=40, blank=True)
creation_timestamp = models.CharField(_('Creation timestamp'), max_length=40, blank=False)
expires_in = models.CharField(_('Expires in'), max_length=40, blank=True)
def __unicode__(self):
return unicode(self.token)
@receiver(post_save, sender=Application)
def invalidate_tokens_on_change(sender, instance, created, raw, **kwargs):
if created is False:
instance.token_set.all().update(creation_timestamp='0')
| sixuanwang/SAMSaaS | wirecloud-develop/src/wirecloud/oauth2provider/models.py | Python | gpl-2.0 | 2,919 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace TtNum1.team_buying
{
public partial class goods : System.Web.UI.Page
{
TtNum1.BLL.GoodsInfo bllgoodsinfo = new TtNum1.BLL.GoodsInfo();
TtNum1.Model.GoodsInfo modgoodsinfo = new TtNum1.Model.GoodsInfo();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["Goods_ID"] == null)
{
Response.Write("<script>window.alert('您没有选择公告,无法传值');window.location=index.aspx;</script>");
}
else
{
ViewState["BackUrl"] = Request.UrlReferrer.ToString();
string a = Request.QueryString["Goods_ID"].ToString();
modgoodsinfo = bllgoodsinfo.GetModel(Convert.ToInt16(a));
Goods_ID.Text = modgoodsinfo.Goods_ID.ToString();
DataTable dt = bllgoodsinfo.GetList1(a).Tables[0];
if (dt.Rows.Count > 0)
{
Goods_ID.Text = dt.Rows[0]["Goods_ID"].ToString();
Goods_name.Text = dt.Rows[0]["Goods_name"].ToString();
Market_price.Text = dt.Rows[0]["Market_price"].ToString();
In_store_price.Text = dt.Rows[0]["In_store_price"].ToString();
Stock.Text = dt.Rows[0]["Stock"].ToString();
Image1.ImageUrl = dt.Rows[0]["Goods_pic"].ToString();
Image2.ImageUrl = dt.Rows[0]["Goods_pic"].ToString();
Goods_info.Text = dt.Rows[0]["Goods_info"].ToString();
Good_Brand.Text = dt.Rows[0]["Good_Brand"].ToString();
Qqp.Text = dt.Rows[0]["Qqp"].ToString();
TextBox12.Text = dt.Rows[0]["Qqp"].ToString();
if (dt.Rows[0]["IN_group_buying"].ToString() == "1")
{
IN_group_buying.Text = "是";
}
else
{
IN_group_buying.Text = "否";
}
Sales_volume.Text = dt.Rows[0]["Sales_volume"].ToString();
TextBox9.Text = dt.Rows[0]["Sales_volume"].ToString();
if (dt.Rows[0]["Group_Buying_Price"].ToString() == "" || dt.Rows[0]["Group_Buying_Price"].ToString() == null)
{
Group_Buying_Price.Text = "该商品未设置团购信息";
}
else
{
Group_Buying_Price.Text = dt.Rows[0]["Group_Buying_Price"].ToString();
}
TextBox10.Text = dt.Rows[0]["Group_Buying_Price"].ToString();
GS1.Text = dt.Rows[0]["Sort_name"].ToString();
GS2.Text = dt.Rows[0]["GS_name1"].ToString();
Image3.ImageUrl = dt.Rows[0]["Img_1"].ToString();
Image4.ImageUrl = dt.Rows[0]["Img_1"].ToString();
Image5.ImageUrl = dt.Rows[0]["Img_2"].ToString();
Image6.ImageUrl = dt.Rows[0]["Img_2"].ToString();
uptime.Text = dt.Rows[0]["uptime"].ToString();
}
}
}
}
protected void RadButton2_Click1(object sender, EventArgs e)
{
// Response.Write("<script>history.back(-1)</script>");
Response.Redirect(ViewState["BackUrl"].ToString());
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TtNum"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("select * from GoodSort2 where GoodSort2.GS_ID='" + DropDownList1.SelectedValue + "'", conn);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "GoodSort2");
conn.Close();
}
catch (SqlException e2)
{
Response.Write(e2.ToString());
}
PagedDataSource obj = new PagedDataSource();
obj.DataSource = ds.Tables["GoodSort2"].DefaultView;
DropDownList2.DataSource = obj;
this.DropDownList2.DataTextField = "Sort_name";
this.DropDownList2.DataValueField = "Sort_ID";
DropDownList2.DataBind();
}
}
} | JJDJJ/TtNum | TtNum/TtNum/team_buying/goods.aspx.cs | C# | gpl-2.0 | 5,347 |
/*
* This file is part of NWFramework.
* Copyright (c) InCrew Software and Others.
* (See the AUTHORS file in the root of this distribution.)
*
* NWFramework 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.
*
* NWFramework 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 NWFramework; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "PchNWStream.h"
#include "NWStreamBlockVideo.h"
#include <memory.h>
//********************************************************************
//
//********************************************************************
//--------------------------------------------------------------------
//
//--------------------------------------------------------------------
NWStreamBlockVideo::NWStreamBlockVideo() : Inherited(),
mFrameBuffer(0),
mWidth(0),
mHeight(0),
mStride(0)
{
}
//********************************************************************
//
//********************************************************************
//--------------------------------------------------------------------
//
//--------------------------------------------------------------------
bool NWStreamBlockVideo::init()
{
bool bOK = true;
if (!isOk())
{
mFrameBuffer = 0;
mWidth = 0;
mHeight = 0;
mStride = 0;
bOK = Inherited::init(NWSTREAM_SUBTYPE_MEDIA_VIDEO);
}
return bOK;
}
//--------------------------------------------------------------------
//
//--------------------------------------------------------------------
void NWStreamBlockVideo::done()
{
if (isOk())
{
DISPOSE_ARRAY(mFrameBuffer);
Inherited::done();
}
}
//--------------------------------------------------------------------
//
//--------------------------------------------------------------------
void NWStreamBlockVideo::setFrameBufferData(int _width, int _height, int _stride, unsigned char* _frameBuffer, bool _copy)
{
if ( _frameBuffer && _copy )
{
int frameBufferSize = _height*_stride;
ASSERT(_stride >= (_height*3));
mFrameBuffer = NEW unsigned char[frameBufferSize];
memcpy(mFrameBuffer,_frameBuffer,frameBufferSize);
}
else
{
mFrameBuffer = _frameBuffer;
}
mWidth = _width;
mHeight = _height;
mStride = _stride;
}
| cryptonome/nwframework | Framework/NWStream/NWStreamBlockVideo.cpp | C++ | gpl-2.0 | 3,001 |
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :organization
t.string :department
t.string :name
t.string :role
t.string :email
t.string :password
t.binary :picture
t.integer :given_chips
t.integer :received_chips
t.integer :avail_chips
t.timestamps
end
end
end
| kostaskoufou/Innovation_credits | vendor/db/migrate/20130618120305_create_users.rb | Ruby | gpl-2.0 | 385 |
<?php
/**
* WordPress Roles and Capabilities.
*
* @package WordPress
* @subpackage User
*/
/**
* WordPress User Roles.
*
* The role option is simple, the structure is organized by role name that store
* the name in value of the 'name' key. The capabilities are stored as an array
* in the value of the 'capability' key.
*
* <code>
* array (
* 'rolename' => array (
* 'name' => 'rolename',
* 'capabilities' => array()
* )
* )
* </code>
*
* @since 2.0.0
* @package WordPress
* @subpackage User
*/
class WP_Roles {
/**
* List of roles and capabilities.
*
* @since 2.0.0
* @access public
* @var array
*/
var $roles;
/**
* List of the role objects.
*
* @since 2.0.0
* @access public
* @var array
*/
var $role_objects = array();
/**
* List of role names.
*
* @since 2.0.0
* @access public
* @var array
*/
var $role_names = array();
/**
* Option name for storing role list.
*
* @since 2.0.0
* @access public
* @var string
*/
var $role_key;
/**
* Whether to use the database for retrieval and storage.
*
* @since 2.1.0
* @access public
* @var bool
*/
var $use_db = true;
/**
* PHP4 Constructor - Call {@link WP_Roles::_init()} method.
*
* @since 2.0.0
* @access public
*
* @return WP_Roles
*/
function WP_Roles() {
$this->_init();
}
/**
* Setup the object properties.
*
* The role key is set to the current prefix for the $wpdb object with
* 'user_roles' appended. If the $wp_user_roles global is set, then it will
* be used and the role option will not be updated or used.
*
* @since 2.1.0
* @access protected
* @uses $wpdb Used to get the database prefix.
* @global array $wp_user_roles Used to set the 'roles' property value.
*/
function _init () {
global $wpdb;
global $wp_user_roles;
$this->role_key = $wpdb->prefix . 'user_roles';
if ( ! empty( $wp_user_roles ) ) {
$this->roles = $wp_user_roles;
$this->use_db = false;
} else {
$this->roles = get_option( $this->role_key );
}
if ( empty( $this->roles ) )
return;
$this->role_objects = array();
$this->role_names = array();
foreach ( (array) $this->roles as $role => $data ) {
$this->role_objects[$role] = new WP_Role( $role, $this->roles[$role]['capabilities'] );
$this->role_names[$role] = $this->roles[$role]['name'];
}
}
/**
* Add role name with capabilities to list.
*
* Updates the list of roles, if the role doesn't already exist.
*
* @since 2.0.0
* @access public
*
* @param string $role Role name.
* @param string $display_name Role display name.
* @param array $capabilities List of role capabilities.
* @return null|WP_Role WP_Role object if role is added, null if already exists.
*/
function add_role( $role, $display_name, $capabilities = array() ) {
if ( isset( $this->roles[$role] ) )
return;
$this->roles[$role] = array(
'name' => $display_name,
'capabilities' => $capabilities
);
if ( $this->use_db )
update_option( $this->role_key, $this->roles );
$this->role_objects[$role] = new WP_Role( $role, $capabilities );
$this->role_names[$role] = $display_name;
return $this->role_objects[$role];
}
/**
* Remove role by name.
*
* @since 2.0.0
* @access public
*
* @param string $role Role name.
*/
function remove_role( $role ) {
if ( ! isset( $this->role_objects[$role] ) )
return;
unset( $this->role_objects[$role] );
unset( $this->role_names[$role] );
unset( $this->roles[$role] );
if ( $this->use_db )
update_option( $this->role_key, $this->roles );
}
/**
* Add capability to role.
*
* @since 2.0.0
* @access public
*
* @param string $role Role name.
* @param string $cap Capability name.
* @param bool $grant Optional, default is true. Whether role is capable of preforming capability.
*/
function add_cap( $role, $cap, $grant = true ) {
$this->roles[$role]['capabilities'][$cap] = $grant;
if ( $this->use_db )
update_option( $this->role_key, $this->roles );
}
/**
* Remove capability from role.
*
* @since 2.0.0
* @access public
*
* @param string $role Role name.
* @param string $cap Capability name.
*/
function remove_cap( $role, $cap ) {
unset( $this->roles[$role]['capabilities'][$cap] );
if ( $this->use_db )
update_option( $this->role_key, $this->roles );
}
/**
* Retrieve role object by name.
*
* @since 2.0.0
* @access public
*
* @param string $role Role name.
* @return object|null Null, if role does not exist. WP_Role object, if found.
*/
function &get_role( $role ) {
if ( isset( $this->role_objects[$role] ) )
return $this->role_objects[$role];
else
return null;
}
/**
* Retrieve list of role names.
*
* @since 2.0.0
* @access public
*
* @return array List of role names.
*/
function get_names() {
return $this->role_names;
}
/**
* Whether role name is currently in the list of available roles.
*
* @since 2.0.0
* @access public
*
* @param string $role Role name to look up.
* @return bool
*/
function is_role( $role )
{
return isset( $this->role_names[$role] );
}
}
/**
* WordPress Role class.
*
* @since 2.0.0
* @package WordPress
* @subpackage User
*/
class WP_Role {
/**
* Role name.
*
* @since 2.0.0
* @access public
* @var string
*/
var $name;
/**
* List of capabilities the role contains.
*
* @since 2.0.0
* @access public
* @var array
*/
var $capabilities;
/**
* PHP4 Constructor - Setup object properties.
*
* The list of capabilities, must have the key as the name of the capability
* and the value a boolean of whether it is granted to the role or not.
*
* @since 2.0.0
* @access public
*
* @param string $role Role name.
* @param array $capabilities List of capabilities.
* @return WP_Role
*/
function WP_Role( $role, $capabilities ) {
$this->name = $role;
$this->capabilities = $capabilities;
}
/**
* Assign role a capability.
*
* @see WP_Roles::add_cap() Method uses implementation for role.
* @since 2.0.0
* @access public
*
* @param string $cap Capability name.
* @param bool $grant Whether role has capability privilege.
*/
function add_cap( $cap, $grant = true ) {
global $wp_roles;
if ( ! isset( $wp_roles ) )
$wp_roles = new WP_Roles();
$this->capabilities[$cap] = $grant;
$wp_roles->add_cap( $this->name, $cap, $grant );
}
/**
* Remove capability from role.
*
* This is a container for {@link WP_Roles::remove_cap()} to remove the
* capability from the role. That is to say, that {@link
* WP_Roles::remove_cap()} implements the functionality, but it also makes
* sense to use this class, because you don't need to enter the role name.
*
* @since 2.0.0
* @access public
*
* @param string $cap Capability name.
*/
function remove_cap( $cap ) {
global $wp_roles;
if ( ! isset( $wp_roles ) )
$wp_roles = new WP_Roles();
unset( $this->capabilities[$cap] );
$wp_roles->remove_cap( $this->name, $cap );
}
/**
* Whether role has capability.
*
* The capabilities is passed through the 'role_has_cap' filter. The first
* parameter for the hook is the list of capabilities the class has
* assigned. The second parameter is the capability name to look for. The
* third and final parameter for the hook is the role name.
*
* @since 2.0.0
* @access public
*
* @param string $cap Capability name.
* @return bool True, if user has capability. False, if doesn't have capability.
*/
function has_cap( $cap ) {
$capabilities = apply_filters( 'role_has_cap', $this->capabilities, $cap, $this->name );
if ( !empty( $capabilities[$cap] ) )
return $capabilities[$cap];
else
return false;
}
}
/**
* WordPress User class.
*
* @since 2.0.0
* @package WordPress
* @subpackage User
*/
class WP_User {
/**
* User data container.
*
* This will be set as properties of the object.
*
* @since 2.0.0
* @access private
* @var array
*/
var $data;
/**
* The user's ID.
*
* @since 2.1.0
* @access public
* @var int
*/
var $ID = 0;
/**
* The deprecated user's ID.
*
* @since 2.0.0
* @access public
* @deprecated Use WP_User::$ID
* @see WP_User::$ID
* @var int
*/
var $id = 0;
/**
* The individual capabilities the user has been given.
*
* @since 2.0.0
* @access public
* @var array
*/
var $caps = array();
/**
* User metadata option name.
*
* @since 2.0.0
* @access public
* @var string
*/
var $cap_key;
/**
* The roles the user is part of.
*
* @since 2.0.0
* @access public
* @var array
*/
var $roles = array();
/**
* All capabilities the user has, including individual and role based.
*
* @since 2.0.0
* @access public
* @var array
*/
var $allcaps = array();
/**
* First name of the user.
*
* Created to prevent notices.
*
* @since 2.7.0
* @access public
* @var string
*/
var $first_name = '';
/**
* Last name of the user.
*
* Created to prevent notices.
*
* @since 2.7.0
* @access public
* @var string
*/
var $last_name = '';
/**
* PHP4 Constructor - Sets up the object properties.
*
* Retrieves the userdata and then assigns all of the data keys to direct
* properties of the object. Calls {@link WP_User::_init_caps()} after
* setting up the object's user data properties.
*
* @since 2.0.0
* @access public
*
* @param int|string $id User's ID or username
* @param int $name Optional. User's username
* @return WP_User
*/
function WP_User( $id, $name = '' ) {
if ( empty( $id ) && empty( $name ) )
return;
if ( ! is_numeric( $id ) ) {
$name = $id;
$id = 0;
}
if ( ! empty( $id ) )
$this->data = get_userdata( $id );
else
$this->data = get_userdatabylogin( $name );
if ( empty( $this->data->ID ) )
return;
foreach ( get_object_vars( $this->data ) as $key => $value ) {
$this->{$key} = $value;
}
$this->id = $this->ID;
$this->_init_caps();
}
/**
* Setup capability object properties.
*
* Will set the value for the 'cap_key' property to current database table
* prefix, followed by 'capabilities'. Will then check to see if the
* property matching the 'cap_key' exists and is an array. If so, it will be
* used.
*
* @since 2.1.0
* @access protected
*/
function _init_caps() {
global $wpdb;
$this->cap_key = $wpdb->prefix . 'capabilities';
$this->caps = &$this->{$this->cap_key};
if ( ! is_array( $this->caps ) )
$this->caps = array();
$this->get_role_caps();
}
/**
* Retrieve all of the role capabilities and merge with individual capabilities.
*
* All of the capabilities of the roles the user belongs to are merged with
* the users individual roles. This also means that the user can be denied
* specific roles that their role might have, but the specific user isn't
* granted permission to.
*
* @since 2.0.0
* @uses $wp_roles
* @access public
*/
function get_role_caps() {
global $wp_roles;
if ( ! isset( $wp_roles ) )
$wp_roles = new WP_Roles();
//Filter out caps that are not role names and assign to $this->roles
if ( is_array( $this->caps ) )
$this->roles = array_filter( array_keys( $this->caps ), array( &$wp_roles, 'is_role' ) );
//Build $allcaps from role caps, overlay user's $caps
$this->allcaps = array();
foreach ( (array) $this->roles as $role ) {
$role = $wp_roles->get_role( $role );
$this->allcaps = array_merge( $this->allcaps, $role->capabilities );
}
$this->allcaps = array_merge( $this->allcaps, $this->caps );
}
/**
* Add role to user.
*
* Updates the user's meta data option with capabilities and roles.
*
* @since 2.0.0
* @access public
*
* @param string $role Role name.
*/
function add_role( $role ) {
$this->caps[$role] = true;
update_usermeta( $this->ID, $this->cap_key, $this->caps );
$this->get_role_caps();
$this->update_user_level_from_caps();
}
/**
* Remove role from user.
*
* @since 2.0.0
* @access public
*
* @param string $role Role name.
*/
function remove_role( $role ) {
if ( empty( $this->roles[$role] ) || ( count( $this->roles ) <= 1 ) )
return;
unset( $this->caps[$role] );
update_usermeta( $this->ID, $this->cap_key, $this->caps );
$this->get_role_caps();
}
/**
* Set the role of the user.
*
* This will remove the previous roles of the user and assign the user the
* new one. You can set the role to an empty string and it will remove all
* of the roles from the user.
*
* @since 2.0.0
* @access public
*
* @param string $role Role name.
*/
function set_role( $role ) {
foreach ( (array) $this->roles as $oldrole )
unset( $this->caps[$oldrole] );
if ( !empty( $role ) ) {
$this->caps[$role] = true;
$this->roles = array( $role => true );
} else {
$this->roles = false;
}
update_usermeta( $this->ID, $this->cap_key, $this->caps );
$this->get_role_caps();
$this->update_user_level_from_caps();
}
/**
* Choose the maximum level the user has.
*
* Will compare the level from the $item parameter against the $max
* parameter. If the item is incorrect, then just the $max parameter value
* will be returned.
*
* Used to get the max level based on the capabilities the user has. This
* is also based on roles, so if the user is assigned the Administrator role
* then the capability 'level_10' will exist and the user will get that
* value.
*
* @since 2.0.0
* @access public
*
* @param int $max Max level of user.
* @param string $item Level capability name.
* @return int Max Level.
*/
function level_reduction( $max, $item ) {
if ( preg_match( '/^level_(10|[0-9])$/i', $item, $matches ) ) {
$level = intval( $matches[1] );
return max( $max, $level );
} else {
return $max;
}
}
/**
* Update the maximum user level for the user.
*
* Updates the 'user_level' user metadata (includes prefix that is the
* database table prefix) with the maximum user level. Gets the value from
* the all of the capabilities that the user has.
*
* @since 2.0.0
* @access public
*/
function update_user_level_from_caps() {
global $wpdb;
$this->user_level = array_reduce( array_keys( $this->allcaps ), array( &$this, 'level_reduction' ), 0 );
update_usermeta( $this->ID, $wpdb->prefix.'user_level', $this->user_level );
}
/**
* Add capability and grant or deny access to capability.
*
* @since 2.0.0
* @access public
*
* @param string $cap Capability name.
* @param bool $grant Whether to grant capability to user.
*/
function add_cap( $cap, $grant = true ) {
$this->caps[$cap] = $grant;
update_usermeta( $this->ID, $this->cap_key, $this->caps );
}
/**
* Remove capability from user.
*
* @since 2.0.0
* @access public
*
* @param string $cap Capability name.
*/
function remove_cap( $cap ) {
if ( empty( $this->caps[$cap] ) ) return;
unset( $this->caps[$cap] );
update_usermeta( $this->ID, $this->cap_key, $this->caps );
}
/**
* Remove all of the capabilities of the user.
*
* @since 2.1.0
* @access public
*/
function remove_all_caps() {
global $wpdb;
$this->caps = array();
update_usermeta( $this->ID, $this->cap_key, '' );
update_usermeta( $this->ID, $wpdb->prefix.'user_level', '' );
$this->get_role_caps();
}
/**
* Whether user has capability or role name.
*
* This is useful for looking up whether the user has a specific role
* assigned to the user. The second optional parameter can also be used to
* check for capabilities against a specfic post.
*
* @since 2.0.0
* @access public
*
* @param string|int $cap Capability or role name to search.
* @param int $post_id Optional. Post ID to check capability against specific post.
* @return bool True, if user has capability; false, if user does not have capability.
*/
function has_cap( $cap ) {
if ( is_numeric( $cap ) )
$cap = $this->translate_level_to_cap( $cap );
$args = array_slice( func_get_args(), 1 );
$args = array_merge( array( $cap, $this->ID ), $args );
$caps = call_user_func_array( 'map_meta_cap', $args );
// Must have ALL requested caps
$capabilities = apply_filters( 'user_has_cap', $this->allcaps, $caps, $args );
foreach ( (array) $caps as $cap ) {
//echo "Checking cap $cap<br />";
if ( empty( $capabilities[$cap] ) || !$capabilities[$cap] )
return false;
}
return true;
}
/**
* Convert numeric level to level capability name.
*
* Prepends 'level_' to level number.
*
* @since 2.0.0
* @access public
*
* @param int $level Level number, 1 to 10.
* @return string
*/
function translate_level_to_cap( $level ) {
return 'level_' . $level;
}
}
/**
* Map meta capabilities to primitive capabilities.
*
* This does not actually compare whether the user ID has the actual capability,
* just what the capability or capabilities are. Meta capability list value can
* be 'delete_user', 'edit_user', 'delete_post', 'delete_page', 'edit_post',
* 'edit_page', 'read_post', or 'read_page'.
*
* @since 2.0.0
*
* @param string $cap Capability name.
* @param int $user_id User ID.
* @return array Actual capabilities for meta capability.
*/
function map_meta_cap( $cap, $user_id ) {
$args = array_slice( func_get_args(), 2 );
$caps = array();
switch ( $cap ) {
case 'delete_user':
$caps[] = 'delete_users';
break;
case 'edit_user':
if ( !isset( $args[0] ) || $user_id != $args[0] ) {
$caps[] = 'edit_users';
}
break;
case 'delete_post':
$author_data = get_userdata( $user_id );
//echo "post ID: {$args[0]}<br />";
$post = get_post( $args[0] );
if ( 'page' == $post->post_type ) {
$args = array_merge( array( 'delete_page', $user_id ), $args );
return call_user_func_array( 'map_meta_cap', $args );
}
$post_author_data = get_userdata( $post->post_author );
//echo "current user id : $user_id, post author id: " . $post_author_data->ID . "<br />";
// If the user is the author...
if ( $user_id == $post_author_data->ID ) {
// If the post is published...
if ( 'publish' == $post->post_status )
$caps[] = 'delete_published_posts';
else
// If the post is draft...
$caps[] = 'delete_posts';
} else {
// The user is trying to edit someone else's post.
$caps[] = 'delete_others_posts';
// The post is published, extra cap required.
if ( 'publish' == $post->post_status )
$caps[] = 'delete_published_posts';
elseif ( 'private' == $post->post_status )
$caps[] = 'delete_private_posts';
}
break;
case 'delete_page':
$author_data = get_userdata( $user_id );
//echo "post ID: {$args[0]}<br />";
$page = get_page( $args[0] );
$page_author_data = get_userdata( $page->post_author );
//echo "current user id : $user_id, page author id: " . $page_author_data->ID . "<br />";
// If the user is the author...
if ( $user_id == $page_author_data->ID ) {
// If the page is published...
if ( $page->post_status == 'publish' )
$caps[] = 'delete_published_pages';
else
// If the page is draft...
$caps[] = 'delete_pages';
} else {
// The user is trying to edit someone else's page.
$caps[] = 'delete_others_pages';
// The page is published, extra cap required.
if ( $page->post_status == 'publish' )
$caps[] = 'delete_published_pages';
elseif ( $page->post_status == 'private' )
$caps[] = 'delete_private_pages';
}
break;
// edit_post breaks down to edit_posts, edit_published_posts, or
// edit_others_posts
case 'edit_post':
$author_data = get_userdata( $user_id );
//echo "post ID: {$args[0]}<br />";
$post = get_post( $args[0] );
if ( 'page' == $post->post_type ) {
$args = array_merge( array( 'edit_page', $user_id ), $args );
return call_user_func_array( 'map_meta_cap', $args );
}
$post_author_data = get_userdata( $post->post_author );
//echo "current user id : $user_id, post author id: " . $post_author_data->ID . "<br />";
// If the user is the author...
if ( $user_id == $post_author_data->ID ) {
// If the post is published...
if ( 'publish' == $post->post_status )
$caps[] = 'edit_published_posts';
else
// If the post is draft...
$caps[] = 'edit_posts';
} else {
// The user is trying to edit someone else's post.
$caps[] = 'edit_others_posts';
// The post is published, extra cap required.
if ( 'publish' == $post->post_status )
$caps[] = 'edit_published_posts';
elseif ( 'private' == $post->post_status )
$caps[] = 'edit_private_posts';
}
break;
case 'edit_page':
$author_data = get_userdata( $user_id );
//echo "post ID: {$args[0]}<br />";
$page = get_page( $args[0] );
$page_author_data = get_userdata( $page->post_author );
//echo "current user id : $user_id, page author id: " . $page_author_data->ID . "<br />";
// If the user is the author...
if ( $user_id == $page_author_data->ID ) {
// If the page is published...
if ( 'publish' == $page->post_status )
$caps[] = 'edit_published_pages';
else
// If the page is draft...
$caps[] = 'edit_pages';
} else {
// The user is trying to edit someone else's page.
$caps[] = 'edit_others_pages';
// The page is published, extra cap required.
if ( 'publish' == $page->post_status )
$caps[] = 'edit_published_pages';
elseif ( 'private' == $page->post_status )
$caps[] = 'edit_private_pages';
}
break;
case 'read_post':
$post = get_post( $args[0] );
if ( 'page' == $post->post_type ) {
$args = array_merge( array( 'read_page', $user_id ), $args );
return call_user_func_array( 'map_meta_cap', $args );
}
if ( 'private' != $post->post_status ) {
$caps[] = 'read';
break;
}
$author_data = get_userdata( $user_id );
$post_author_data = get_userdata( $post->post_author );
if ( $user_id == $post_author_data->ID )
$caps[] = 'read';
else
$caps[] = 'read_private_posts';
break;
case 'read_page':
$page = get_page( $args[0] );
if ( 'private' != $page->post_status ) {
$caps[] = 'read';
break;
}
$author_data = get_userdata( $user_id );
$page_author_data = get_userdata( $page->post_author );
if ( $user_id == $page_author_data->ID )
$caps[] = 'read';
else
$caps[] = 'read_private_pages';
break;
default:
// If no meta caps match, return the original cap.
$caps[] = $cap;
}
return $caps;
}
/**
* Whether current user has capability or role.
*
* @since 2.0.0
*
* @param string $capability Capability or role name.
* @return bool
*/
function current_user_can( $capability ) {
$current_user = wp_get_current_user();
if ( empty( $current_user ) )
return false;
$args = array_slice( func_get_args(), 1 );
$args = array_merge( array( $capability ), $args );
return call_user_func_array( array( &$current_user, 'has_cap' ), $args );
}
/**
* Retrieve role object.
*
* @see WP_Roles::get_role() Uses method to retrieve role object.
* @since 2.0.0
*
* @param string $role Role name.
* @return object
*/
function get_role( $role ) {
global $wp_roles;
if ( ! isset( $wp_roles ) )
$wp_roles = new WP_Roles();
return $wp_roles->get_role( $role );
}
/**
* Add role, if it does not exist.
*
* @see WP_Roles::add_role() Uses method to add role.
* @since 2.0.0
*
* @param string $role Role name.
* @param string $display_name Display name for role.
* @param array $capabilities List of capabilities.
* @return null|WP_Role WP_Role object if role is added, null if already exists.
*/
function add_role( $role, $display_name, $capabilities = array() ) {
global $wp_roles;
if ( ! isset( $wp_roles ) )
$wp_roles = new WP_Roles();
return $wp_roles->add_role( $role, $display_name, $capabilities );
}
/**
* Remove role, if it exists.
*
* @see WP_Roles::remove_role() Uses method to remove role.
* @since 2.0.0
*
* @param string $role Role name.
* @return null
*/
function remove_role( $role ) {
global $wp_roles;
if ( ! isset( $wp_roles ) )
$wp_roles = new WP_Roles();
return $wp_roles->remove_role( $role );
}
?>
| stulentsev/mafiaoffline | wp-includes/capabilities.php | PHP | gpl-2.0 | 24,111 |
class BitStruct
# Class for floats (single and double precision) in network order.
# Declared with BitStruct.float.
class FloatField < Field
# Used in describe.
def self.class_name
@class_name ||= "float"
end
def add_accessors_to(cl, attr = name) # :nodoc:
unless offset % 8 == 0
raise ArgumentError,
"Bad offset, #{offset}, for #{self.class} #{name}." +
" Must be multiple of 8."
end
unless length == 32 or length == 64
raise ArgumentError,
"Bad length, #{length}, for #{self.class} #{name}." +
" Must be 32 or 64."
end
offset_byte = offset / 8
length_byte = length / 8
last_byte = offset_byte + length_byte - 1
byte_range = offset_byte..last_byte
endian = (options[:endian] || options["endian"]).to_s
case endian
when "native"
ctl = case length
when 32; "f"
when 64; "d"
end
when "little"
ctl = case length
when 32; "e"
when 64; "E"
end
when "network", "big", ""
ctl = case length
when 32; "g"
when 64; "G"
end
else
raise ArgumentError,
"Unrecognized endian option: #{endian.inspect}"
end
cl.class_eval do
define_method attr do ||
self[byte_range].unpack(ctl).first
end
define_method "#{attr}=" do |val|
self[byte_range] = [val].pack(ctl)
end
end
end
end
end
| ausarbluhd/EternalLLC | scripts/pentbox/lib/bit-struct/bit-struct/float-field.rb | Ruby | gpl-2.0 | 1,559 |
<?php
/**
* Core Class to enable hooks and actions for Fonts
* @version 1.0
*/
if(!class_exists('IOAFont'))
{
class IOAFont
{
private $fonts;
function __construct()
{
$fonts = array( );
}
/**
* Retrives all registered fonts.
*/
public function getFonts()
{
return $this->fonts;
}
public function setFont($font,$key)
{
global $super_options;
$this->fonts[$key] = $font;
if(!isset($super_options[SN.$key])) $super_options[SN.$key] = $font['default_font'];
}
}
}
$fonts = new IOAFont();
function register_font_class($default='',$defined='',$default_font,$label,$addWeight,$subset)
{
global $fonts;
$fonts->setFont(array(
'default_class' => $default ,
'defined_class' => $defined ,
'default_font' => $default_font,
'label' => $label,
'fontWeight' => $addWeight,
'subset' => $subset
),trim(str_replace(' ','',$default)));
}
?> | HSrcWrld/DKWP | wp-content/themes/limitless/backend/classes/class_font_support.php | PHP | gpl-2.0 | 936 |
/**
* Client UI Javascript for the Calendar plugin
*
* @version @package_version@
* @author Lazlo Westerhof <hello@lazlo.me>
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2010, Lazlo Westerhof <hello@lazlo.me>
* Copyright (C) 2012, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Roundcube calendar UI client class
function rcube_calendar_ui(settings)
{
// extend base class
rcube_calendar.call(this, settings);
/*** member vars ***/
this.is_loading = false;
this.selected_event = null;
this.selected_calendar = null;
this.search_request = null;
this.saving_lock;
/*** private vars ***/
var DAY_MS = 86400000;
var HOUR_MS = 3600000;
var me = this;
var gmt_offset = (new Date().getTimezoneOffset() / -60) - (settings.timezone || 0) - (settings.dst || 0);
var client_timezone = new Date().getTimezoneOffset();
var day_clicked = day_clicked_ts = 0;
var ignore_click = false;
var event_defaults = { free_busy:'busy', alarms:'' };
var event_attendees = [];
var attendees_list;
var freebusy_ui = { workinhoursonly:false, needsupdate:false };
var freebusy_data = {};
var current_view = null;
var exec_deferred = bw.ie6 ? 5 : 1;
var sensitivitylabels = { 'public':rcmail.gettext('public','calendar'), 'private':rcmail.gettext('private','calendar'), 'confidential':rcmail.gettext('confidential','calendar') };
var ui_loading = rcmail.set_busy(true, 'loading');
// general datepicker settings
var datepicker_settings = {
// translate from fullcalendar format to datepicker format
dateFormat: settings['date_format'].replace(/M/g, 'm').replace(/mmmmm/, 'MM').replace(/mmm/, 'M').replace(/dddd/, 'DD').replace(/ddd/, 'D').replace(/yy/g, 'y'),
firstDay : settings['first_day'],
dayNamesMin: settings['days_short'],
monthNames: settings['months'],
monthNamesShort: settings['months'],
changeMonth: false,
showOtherMonths: true,
selectOtherMonths: true
};
/*** imports ***/
var Q = this.quote_html;
var text2html = this.text2html;
var event_date_text = this.event_date_text;
var parse_datetime = this.parse_datetime;
var date2unixtime = this.date2unixtime;
var fromunixtime = this.fromunixtime;
var parseISO8601 = this.parseISO8601;
var init_alarms_edit = this.init_alarms_edit;
/*** private methods ***/
// same as str.split(delimiter) but it ignores delimiters within quoted strings
var explode_quoted_string = function(str, delimiter)
{
var result = [],
strlen = str.length,
q, p, i, char, last;
for (q = p = i = 0; i < strlen; i++) {
char = str.charAt(i);
if (char == '"' && last != '\\') {
q = !q;
}
else if (!q && char == delimiter) {
result.push(str.substring(p, i));
p = i + 1;
}
last = char;
}
result.push(str.substr(p));
return result;
};
// clone the given date object and optionally adjust time
var clone_date = function(date, adjust)
{
var d = new Date(date.getTime());
// set time to 00:00
if (adjust == 1) {
d.setHours(0);
d.setMinutes(0);
}
// set time to 23:59
else if (adjust == 2) {
d.setHours(23);
d.setMinutes(59);
}
return d;
};
// fix date if jumped over a DST change
var fix_date = function(date)
{
if (date.getHours() == 23)
date.setTime(date.getTime() + HOUR_MS);
else if (date.getHours() > 0)
date.setHours(0);
};
// turn the given date into an ISO 8601 date string understandable by PHPs strtotime()
var date2servertime = function(date)
{
return date.getFullYear()+'-'+zeropad(date.getMonth()+1)+'-'+zeropad(date.getDate())
+ 'T'+zeropad(date.getHours())+':'+zeropad(date.getMinutes())+':'+zeropad(date.getSeconds());
}
var date2timestring = function(date, dateonly)
{
return date2servertime(date).replace(/[^0-9]/g, '').substr(0, (dateonly ? 8 : 14));
}
var zeropad = function(num)
{
return (num < 10 ? '0' : '') + num;
}
var render_link = function(url)
{
var islink = false, href = url;
if (url.match(/^[fhtpsmailo]+?:\/\//i)) {
islink = true;
}
else if (url.match(/^[a-z0-9.-:]+(\/|$)/i)) {
islink = true;
href = 'http://' + url;
}
return islink ? '<a href="' + Q(href) + '" target="_blank">' + Q(url) + '</a>' : Q(url);
}
// determine whether the given date is on a weekend
var is_weekend = function(date)
{
return date.getDay() == 0 || date.getDay() == 6;
};
var is_workinghour = function(date)
{
if (settings['work_start'] > settings['work_end'])
return date.getHours() >= settings['work_start'] || date.getHours() < settings['work_end'];
else
return date.getHours() >= settings['work_start'] && date.getHours() < settings['work_end'];
};
// check if the event has 'real' attendees, excluding the current user
var has_attendees = function(event)
{
return (event.attendees && event.attendees.length && (event.attendees.length > 1 || String(event.attendees[0].email).toLowerCase() != settings.identity.email));
};
// check if the current user is an attendee of this event
var is_attendee = function(event, role, email)
{
var emails = email ? ';'+email.toLowerCase() : settings.identity.emails;
for (var i=0; event.attendees && i < event.attendees.length; i++) {
if ((!role || event.attendees[i].role == role) && event.attendees[i].email && emails.indexOf(';'+event.attendees[i].email.toLowerCase()) >= 0)
return event.attendees[i];
}
return false;
};
// check if the current user is the organizer
var is_organizer = function(event, email)
{
return is_attendee(event, 'ORGANIZER', email) || !event.id;
};
var load_attachment = function(event, att)
{
var qstring = '_id='+urlencode(att.id)+'&_event='+urlencode(event.recurrence_id||event.id)+'&_cal='+urlencode(event.calendar);
// open attachment in frame if it's of a supported mimetype
if (id && att.mimetype && $.inArray(att.mimetype, settings.mimetypes)>=0) {
if (rcmail.open_window(rcmail.env.comm_path+'&_action=get-attachment&'+qstring+'&_frame=1', true, true)) {
return;
}
}
rcmail.goto_url('get-attachment', qstring+'&_download=1', false);
};
// build event attachments list
var event_show_attachments = function(list, container, event, edit)
{
var i, id, len, img, content, li, elem,
ul = document.createElement('UL');
ul.className = 'attachmentslist';
for (i=0, len=list.length; i<len; i++) {
elem = list[i];
li = document.createElement('LI');
li.className = elem.classname;
if (edit) {
rcmail.env.attachments[elem.id] = elem;
// delete icon
content = document.createElement('A');
content.href = '#delete';
content.title = rcmail.gettext('delete');
content.className = 'delete';
$(content).click({id: elem.id}, function(e) { remove_attachment(this, e.data.id); return false; });
if (!rcmail.env.deleteicon)
content.innerHTML = rcmail.gettext('delete');
else {
img = document.createElement('IMG');
img.src = rcmail.env.deleteicon;
img.alt = rcmail.gettext('delete');
content.appendChild(img);
}
li.appendChild(content);
}
// name/link
content = document.createElement('A');
content.innerHTML = elem.name;
content.className = 'file';
content.href = '#load';
$(content).click({event: event, att: elem}, function(e) {
load_attachment(e.data.event, e.data.att); return false; });
li.appendChild(content);
ul.appendChild(li);
}
if (edit && rcmail.gui_objects.attachmentlist) {
ul.id = rcmail.gui_objects.attachmentlist.id;
rcmail.gui_objects.attachmentlist = ul;
}
container.empty().append(ul);
};
var remove_attachment = function(elem, id)
{
$(elem.parentNode).hide();
rcmail.env.deleted_attachments.push(id);
delete rcmail.env.attachments[id];
};
// event details dialog (show only)
var event_show_dialog = function(event)
{
var $dialog = $("#eventshow").removeClass().addClass('uidialog');
var calendar = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar] : { editable:false };
me.selected_event = event;
// allow other plugins to do actions when event form is opened
rcmail.triggerEvent('calendar-event-init', {o: event});
$dialog.find('div.event-section, div.event-line').hide();
$('#event-title').html(Q(event.title)).show();
if (event.location)
$('#event-location').html('@ ' + text2html(event.location)).show();
if (event.description)
$('#event-description').show().children('.event-text').html(text2html(event.description, 300, 6));
if (event.vurl)
$('#event-url').show().children('.event-text').html(render_link(event.vurl));
// render from-to in a nice human-readable way
// -> now shown in dialog title
// $('#event-date').html(Q(me.event_date_text(event))).show();
if (event.recurrence && event.recurrence_text)
$('#event-repeat').show().children('.event-text').html(Q(event.recurrence_text));
if (event.alarms && event.alarms_text)
$('#event-alarm').show().children('.event-text').html(Q(event.alarms_text));
if (calendar.name)
$('#event-calendar').show().children('.event-text').html(Q(calendar.name)).removeClass().addClass('event-text').addClass('cal-'+calendar.id);
if (event.categories)
$('#event-category').show().children('.event-text').html(Q(event.categories)).removeClass().addClass('event-text cat-'+String(event.categories).replace(rcmail.identifier_expr, ''));
if (event.free_busy)
$('#event-free-busy').show().children('.event-text').html(Q(rcmail.gettext(event.free_busy, 'calendar')));
if (event.priority > 0) {
var priolabels = [ '', rcmail.gettext('highest'), rcmail.gettext('high'), '', '', rcmail.gettext('normal'), '', '', rcmail.gettext('low'), rcmail.gettext('lowest') ];
$('#event-priority').show().children('.event-text').html(Q(event.priority+' '+priolabels[event.priority]));
}
if (event.sensitivity && event.sensitivity != 'public') {
$('#event-sensitivity').show().children('.event-text').html(Q(sensitivitylabels[event.sensitivity]));
$dialog.addClass('sensitivity-'+event.sensitivity);
}
// create attachments list
if ($.isArray(event.attachments)) {
event_show_attachments(event.attachments, $('#event-attachments').children('.event-text'), event);
if (event.attachments.length > 0) {
$('#event-attachments').show();
}
}
else if (calendar.attachments) {
// fetch attachments, some drivers doesn't set 'attachments' prop of the event?
}
// list event attendees
if (calendar.attendees && event.attendees) {
var data, dispname, organizer = false, rsvp = false, line, morelink, html = '',overflow = '';
for (var j=0; j < event.attendees.length; j++) {
data = event.attendees[j];
dispname = Q(data.name || data.email);
if (data.email) {
dispname = '<a href="mailto:' + data.email + '" title="' + Q(data.email) + '" class="mailtolink">' + dispname + '</a>';
if (data.role == 'ORGANIZER')
organizer = true;
else if ((data.status == 'NEEDS-ACTION' || data.status == 'TENTATIVE') && settings.identity.emails.indexOf(';'+data.email) >= 0)
rsvp = data.status.toLowerCase();
}
line = '<span class="attendee ' + String(data.role == 'ORGANIZER' ? 'organizer' : data.status).toLowerCase() + '">' + dispname + '</span> ';
if (morelink)
overflow += line;
else
html += line;
// stop listing attendees
if (j == 7 && event.attendees.length >= 7) {
morelink = $('<a href="#more" class="morelink"></a>').html(rcmail.gettext('andnmore', 'calendar').replace('$nr', event.attendees.length - j - 1));
}
}
if (html && (event.attendees.length > 1 || !organizer)) {
$('#event-attendees').show()
.children('.event-text')
.html(html)
.find('a.mailtolink').click(function(e) { rcmail.redirect(rcmail.url('mail/compose', { _to:this.href.substr(7) })); return false; });
// display all attendees in a popup when clicking the "more" link
if (morelink) {
$('#event-attendees .event-text').append(morelink);
morelink.click(function(e){
rcmail.show_popup_dialog(
'<div id="all-event-attendees" class="event-attendees">' + html + overflow + '</div>',
rcmail.gettext('tabattendees','calendar'),
null,
{ width:450, modal:false });
$('#all-event-attendees a.mailtolink').click(function(e) { rcmail.redirect(rcmail.url('mail/compose', { _to:this.href.substr(7) })); return false; });
return false;
})
}
}
$('#event-rsvp')[(rsvp&&!organizer?'show':'hide')]();
$('#event-rsvp .rsvp-buttons input').prop('disabled', false).filter('input[rel='+rsvp+']').prop('disabled', true);
}
var buttons = {};
if (calendar.editable && event.editable !== false) {
buttons[rcmail.gettext('edit', 'calendar')] = function() {
event_edit_dialog('edit', event);
};
buttons[rcmail.gettext('remove', 'calendar')] = function() {
me.delete_event(event);
$dialog.dialog('close');
};
}
else {
buttons[rcmail.gettext('close', 'calendar')] = function(){
$dialog.dialog('close');
};
}
// open jquery UI dialog
$dialog.dialog({
modal: false,
resizable: !bw.ie6,
closeOnEscape: (!bw.ie6 && !bw.ie7), // disable for performance reasons
title: Q(me.event_date_text(event)),
open: function() {
$dialog.parent().find('.ui-button').first().focus();
},
close: function() {
$dialog.dialog('destroy').hide();
},
buttons: buttons,
minWidth: 320,
width: 420
}).show();
// set dialog size according to content
me.dialog_resize($dialog.get(0), $dialog.height(), 420);
/*
// add link for "more options" drop-down
$('<a>')
.attr('href', '#')
.html('More Options')
.addClass('dropdown-link')
.click(function(){ return false; })
.insertBefore($dialog.parent().find('.ui-dialog-buttonset').children().first());
*/
};
// bring up the event dialog (jquery-ui popup)
var event_edit_dialog = function(action, event)
{
// close show dialog first
$("#eventshow:ui-dialog").dialog('close');
var $dialog = $('<div>');
var calendar = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar] : { editable:action=='new' };
me.selected_event = $.extend($.extend({}, event_defaults), event); // clone event object (with defaults)
event = me.selected_event; // change reference to clone
freebusy_ui.needsupdate = false;
// reset dialog first
$('#eventtabs').get(0).reset();
// allow other plugins to do actions when event form is opened
rcmail.triggerEvent('calendar-event-init', {o: event});
// event details
var title = $('#edit-title').val(event.title || '');
var location = $('#edit-location').val(event.location || '');
var description = $('#edit-description').html(event.description || '');
var vurl = $('#edit-url').val(event.vurl || '');
var categories = $('#edit-categories').val(event.categories);
var calendars = $('#edit-calendar').val(event.calendar);
var freebusy = $('#edit-free-busy').val(event.free_busy);
var priority = $('#edit-priority').val(event.priority);
var sensitivity = $('#edit-sensitivity').val(event.sensitivity);
var duration = Math.round((event.end.getTime() - event.start.getTime()) / 1000);
var startdate = $('#edit-startdate').val($.fullCalendar.formatDate(event.start, settings['date_format'])).data('duration', duration);
var starttime = $('#edit-starttime').val($.fullCalendar.formatDate(event.start, settings['time_format'])).show();
var enddate = $('#edit-enddate').val($.fullCalendar.formatDate(event.end, settings['date_format']));
var endtime = $('#edit-endtime').val($.fullCalendar.formatDate(event.end, settings['time_format'])).show();
var allday = $('#edit-allday').get(0);
var notify = $('#edit-attendees-donotify').get(0);
var invite = $('#edit-attendees-invite').get(0);
notify.checked = has_attendees(event), invite.checked = true;
if (event.allDay) {
starttime.val("12:00").hide();
endtime.val("13:00").hide();
allday.checked = true;
}
else {
allday.checked = false;
}
// set alarm(s)
// TODO: support multiple alarm entries
if (event.alarms || action != 'new') {
if (typeof event.alarms == 'string')
event.alarms = event.alarms.split(';');
var valarms = event.alarms || [''];
for (var alarm, i=0; i < valarms.length; i++) {
alarm = String(valarms[i]).split(':');
if (!alarm[1] && alarm[0]) alarm[1] = 'DISPLAY';
$('#eventedit select.edit-alarm-type').val(alarm[1]);
if (alarm[0].match(/@(\d+)/)) {
var ondate = fromunixtime(parseInt(RegExp.$1));
$('#eventedit select.edit-alarm-offset').val('@');
$('#eventedit input.edit-alarm-date').val($.fullCalendar.formatDate(ondate, settings['date_format']));
$('#eventedit input.edit-alarm-time').val($.fullCalendar.formatDate(ondate, settings['time_format']));
}
else if (alarm[0].match(/([-+])(\d+)([MHD])/)) {
$('#eventedit input.edit-alarm-value').val(RegExp.$2);
$('#eventedit select.edit-alarm-offset').val(''+RegExp.$1+RegExp.$3);
}
}
}
// set correct visibility by triggering onchange handlers
$('#eventedit select.edit-alarm-type, #eventedit select.edit-alarm-offset').change();
// enable/disable alarm property according to backend support
$('#edit-alarms')[(calendar.alarms ? 'show' : 'hide')]();
// check categories drop-down: add value if not exists
if (event.categories && !categories.find("option[value='"+event.categories+"']").length) {
$('<option>').attr('value', event.categories).text(event.categories).appendTo(categories).prop('selected', true);
}
// set recurrence form
var recurrence, interval, rrtimes, rrenddate;
var load_recurrence_tab = function()
{
recurrence = $('#edit-recurrence-frequency').val(event.recurrence ? event.recurrence.FREQ : '').change();
interval = $('#eventedit select.edit-recurrence-interval').val(event.recurrence ? event.recurrence.INTERVAL : 1);
rrtimes = $('#edit-recurrence-repeat-times').val(event.recurrence ? event.recurrence.COUNT : 1);
rrenddate = $('#edit-recurrence-enddate').val(event.recurrence && event.recurrence.UNTIL ? $.fullCalendar.formatDate(parseISO8601(event.recurrence.UNTIL), settings['date_format']) : '');
$('#eventedit input.edit-recurrence-until:checked').prop('checked', false);
var weekdays = ['SU','MO','TU','WE','TH','FR','SA'];
var rrepeat_id = '#edit-recurrence-repeat-forever';
if (event.recurrence && event.recurrence.COUNT) rrepeat_id = '#edit-recurrence-repeat-count';
else if (event.recurrence && event.recurrence.UNTIL) rrepeat_id = '#edit-recurrence-repeat-until';
$(rrepeat_id).prop('checked', true);
if (event.recurrence && event.recurrence.BYDAY && event.recurrence.FREQ == 'WEEKLY') {
var wdays = event.recurrence.BYDAY.split(',');
$('input.edit-recurrence-weekly-byday').val(wdays);
}
if (event.recurrence && event.recurrence.BYMONTHDAY) {
$('input.edit-recurrence-monthly-bymonthday').val(String(event.recurrence.BYMONTHDAY).split(','));
$('input.edit-recurrence-monthly-mode').val(['BYMONTHDAY']);
}
if (event.recurrence && event.recurrence.BYDAY && (event.recurrence.FREQ == 'MONTHLY' || event.recurrence.FREQ == 'YEARLY')) {
var byday, section = event.recurrence.FREQ.toLowerCase();
if ((byday = String(event.recurrence.BYDAY).match(/(-?[1-4])([A-Z]+)/))) {
$('#edit-recurrence-'+section+'-prefix').val(byday[1]);
$('#edit-recurrence-'+section+'-byday').val(byday[2]);
}
$('input.edit-recurrence-'+section+'-mode').val(['BYDAY']);
}
else if (event.start) {
$('#edit-recurrence-monthly-byday').val(weekdays[event.start.getDay()]);
}
if (event.recurrence && event.recurrence.BYMONTH) {
$('input.edit-recurrence-yearly-bymonth').val(String(event.recurrence.BYMONTH).split(','));
}
else if (event.start) {
$('input.edit-recurrence-yearly-bymonth').val([String(event.start.getMonth()+1)]);
}
};
// show warning if editing a recurring event
if (event.id && event.recurrence) {
var sel = event.thisandfuture ? 'future' : (event.isexception ? 'current' : 'all');
$('#edit-recurring-warning').show();
$('input.edit-recurring-savemode[value="'+sel+'"]').prop('checked', true);
}
else
$('#edit-recurring-warning').hide();
// init attendees tab
var organizer = !event.attendees || is_organizer(event),
allow_invitations = organizer || (calendar.owner && calendar.owner == 'anonymous') || settings.invite_shared;
event_attendees = [];
attendees_list = $('#edit-attendees-table > tbody').html('');
$('#edit-attendees-notify')[(notify.checked && allow_invitations ? 'show' : 'hide')]();
$('#edit-localchanges-warning')[(has_attendees(event) && !(allow_invitations || (calendar.owner && is_organizer(event, calendar.owner))) ? 'show' : 'hide')]();
var load_attendees_tab = function()
{
if (event.attendees) {
for (var j=0; j < event.attendees.length; j++)
add_attendee(event.attendees[j], !allow_invitations);
}
// select the correct organizer identity
var identity_id = 0;
$.each(settings.identities, function(i,v){
if (organizer && v == organizer.email) {
identity_id = i;
return false;
}
});
$('#edit-identities-list').val(identity_id);
$('#edit-attendees-form')[(allow_invitations?'show':'hide')]();
$('#edit-attendee-schedule')[(calendar.freebusy?'show':'hide')]();
};
// attachments
var load_attachments_tab = function()
{
rcmail.enable_command('remove-attachment', !calendar.readonly);
rcmail.env.deleted_attachments = [];
// we're sharing some code for uploads handling with app.js
rcmail.env.attachments = [];
rcmail.env.compose_id = event.id; // for rcmail.async_upload_form()
if ($.isArray(event.attachments)) {
event_show_attachments(event.attachments, $('#edit-attachments'), event, true);
}
else {
$('#edit-attachments > ul').empty();
// fetch attachments, some drivers doesn't set 'attachments' array for event?
}
};
// init dialog buttons
var buttons = {};
// save action
buttons[rcmail.gettext('save', 'calendar')] = function() {
var start = parse_datetime(allday.checked ? '12:00' : starttime.val(), startdate.val());
var end = parse_datetime(allday.checked ? '13:00' : endtime.val(), enddate.val());
// basic input validatetion
if (start.getTime() > end.getTime()) {
alert(rcmail.gettext('invalideventdates', 'calendar'));
return false;
}
// post data to server
var data = {
calendar: event.calendar,
start: date2servertime(start),
end: date2servertime(end),
allday: allday.checked?1:0,
title: title.val(),
description: description.val(),
location: location.val(),
categories: categories.val(),
vurl: vurl.val(),
free_busy: freebusy.val(),
priority: priority.val(),
sensitivity: sensitivity.val(),
recurrence: '',
alarms: '',
attendees: event_attendees,
deleted_attachments: rcmail.env.deleted_attachments,
attachments: []
};
// serialize alarm settings
// TODO: support multiple alarm entries
var alarm = $('#eventedit select.edit-alarm-type').val();
if (alarm) {
var val, offset = $('#eventedit select.edit-alarm-offset').val();
if (offset == '@')
data.alarms = '@' + date2unixtime(parse_datetime($('#eventedit input.edit-alarm-time').val(), $('#eventedit input.edit-alarm-date').val())) + ':' + alarm;
else if ((val = parseInt($('#eventedit input.edit-alarm-value').val())) && !isNaN(val) && val >= 0)
data.alarms = offset[0] + val + offset[1] + ':' + alarm;
}
// uploaded attachments list
for (var i in rcmail.env.attachments)
if (i.match(/^rcmfile(.+)/))
data.attachments.push(RegExp.$1);
// read attendee roles
$('select.edit-attendee-role').each(function(i, elem){
if (data.attendees[i])
data.attendees[i].role = $(elem).val();
});
if (organizer)
data._identity = $('#edit-identities-list option:selected').val();
// don't submit attendees if only myself is added as organizer
if (data.attendees.length == 1 && data.attendees[0].role == 'ORGANIZER' && String(data.attendees[0].email).toLowerCase() == settings.identity.email)
data.attendees = [];
// tell server to send notifications
if ((data.attendees.length || (event.id && event.attendees.length)) && allow_invitations && (notify.checked || invite.checked)) {
data._notify = 1;
}
// gather recurrence settings
var freq;
if ((freq = recurrence.val()) != '') {
data.recurrence = {
FREQ: freq,
INTERVAL: $('#edit-recurrence-interval-'+freq.toLowerCase()).val()
};
var until = $('input.edit-recurrence-until:checked').val();
if (until == 'count')
data.recurrence.COUNT = rrtimes.val();
else if (until == 'until')
data.recurrence.UNTIL = date2servertime(parse_datetime(endtime.val(), rrenddate.val()));
if (freq == 'WEEKLY') {
var byday = [];
$('input.edit-recurrence-weekly-byday:checked').each(function(){ byday.push(this.value); });
if (byday.length)
data.recurrence.BYDAY = byday.join(',');
}
else if (freq == 'MONTHLY') {
var mode = $('input.edit-recurrence-monthly-mode:checked').val(), bymonday = [];
if (mode == 'BYMONTHDAY') {
$('input.edit-recurrence-monthly-bymonthday:checked').each(function(){ bymonday.push(this.value); });
if (bymonday.length)
data.recurrence.BYMONTHDAY = bymonday.join(',');
}
else
data.recurrence.BYDAY = $('#edit-recurrence-monthly-prefix').val() + $('#edit-recurrence-monthly-byday').val();
}
else if (freq == 'YEARLY') {
var byday, bymonth = [];
$('input.edit-recurrence-yearly-bymonth:checked').each(function(){ bymonth.push(this.value); });
if (bymonth.length)
data.recurrence.BYMONTH = bymonth.join(',');
if ((byday = $('#edit-recurrence-yearly-byday').val()))
data.recurrence.BYDAY = $('#edit-recurrence-yearly-prefix').val() + byday;
}
}
data.calendar = calendars.val();
if (event.id) {
data.id = event.id;
if (event.recurrence)
data._savemode = $('input.edit-recurring-savemode:checked').val();
if (data.calendar && data.calendar != event.calendar)
data._fromcalendar = event.calendar;
}
update_event(action, data);
$dialog.dialog("close");
};
if (event.id) {
buttons[rcmail.gettext('remove', 'calendar')] = function() {
me.delete_event(event);
$dialog.dialog('close');
};
}
buttons[rcmail.gettext('cancel', 'calendar')] = function() {
$dialog.dialog("close");
};
// show/hide tabs according to calendar's feature support
$('#edit-tab-attendees')[(calendar.attendees?'show':'hide')]();
$('#edit-tab-attachments')[(calendar.attachments?'show':'hide')]();
// activate the first tab
$('#eventtabs').tabs('select', 0);
// hack: set task to 'calendar' to make all dialog actions work correctly
var comm_path_before = rcmail.env.comm_path;
rcmail.env.comm_path = comm_path_before.replace(/_task=[a-z]+/, '_task=calendar');
var editform = $("#eventedit");
// open jquery UI dialog
$dialog.dialog({
modal: true,
resizable: (!bw.ie6 && !bw.ie7), // disable for performance reasons
closeOnEscape: false,
title: rcmail.gettext((action == 'edit' ? 'edit_event' : 'new_event'), 'calendar'),
close: function() {
editform.hide().appendTo(document.body);
$dialog.dialog("destroy").remove();
rcmail.ksearch_blur();
rcmail.ksearch_destroy();
freebusy_data = {};
rcmail.env.comm_path = comm_path_before; // restore comm_path
},
buttons: buttons,
minWidth: 500,
width: 580
}).append(editform.show()); // adding form content AFTERWARDS massively speeds up opening on IE6
// set dialog size according to form content
me.dialog_resize($dialog.get(0), editform.height() + (bw.ie ? 20 : 0), 530);
title.select();
// init other tabs asynchronously
window.setTimeout(load_recurrence_tab, exec_deferred);
if (calendar.attendees)
window.setTimeout(load_attendees_tab, exec_deferred);
if (calendar.attachments)
window.setTimeout(load_attachments_tab, exec_deferred);
};
// open a dialog to display detailed free-busy information and to find free slots
var event_freebusy_dialog = function()
{
var $dialog = $('#eventfreebusy'),
event = me.selected_event;
if ($dialog.is(':ui-dialog'))
$dialog.dialog('close');
if (!event_attendees.length)
return false;
// set form elements
var allday = $('#edit-allday').get(0);
var duration = Math.round((event.end.getTime() - event.start.getTime()) / 1000);
freebusy_ui.startdate = $('#schedule-startdate').val($.fullCalendar.formatDate(event.start, settings['date_format'])).data('duration', duration);
freebusy_ui.starttime = $('#schedule-starttime').val($.fullCalendar.formatDate(event.start, settings['time_format'])).show();
freebusy_ui.enddate = $('#schedule-enddate').val($.fullCalendar.formatDate(event.end, settings['date_format']));
freebusy_ui.endtime = $('#schedule-endtime').val($.fullCalendar.formatDate(event.end, settings['time_format'])).show();
if (allday.checked) {
freebusy_ui.starttime.val("12:00").hide();
freebusy_ui.endtime.val("13:00").hide();
event.allDay = true;
}
// read attendee roles from drop-downs
$('select.edit-attendee-role').each(function(i, elem){
if (event_attendees[i])
event_attendees[i].role = $(elem).val();
});
// render time slots
var now = new Date(), fb_start = new Date(), fb_end = new Date();
fb_start.setTime(event.start);
fb_start.setHours(0); fb_start.setMinutes(0); fb_start.setSeconds(0); fb_start.setMilliseconds(0);
fb_end.setTime(fb_start.getTime() + DAY_MS);
freebusy_data = { required:{}, all:{} };
freebusy_ui.loading = 1; // prevent render_freebusy_grid() to load data yet
freebusy_ui.numdays = Math.max(allday.checked ? 14 : 1, Math.ceil(duration * 2 / 86400));
freebusy_ui.interval = allday.checked ? 1440 : 60;
freebusy_ui.start = fb_start;
freebusy_ui.end = new Date(freebusy_ui.start.getTime() + DAY_MS * freebusy_ui.numdays);
render_freebusy_grid(0);
// render list of attendees
freebusy_ui.attendees = {};
var domid, dispname, data, role_html, list_html = '';
for (var i=0; i < event_attendees.length; i++) {
data = event_attendees[i];
dispname = Q(data.name || data.email);
domid = String(data.email).replace(rcmail.identifier_expr, '');
role_html = '<a class="attendee-role-toggle" id="rcmlia' + domid + '" title="' + Q(rcmail.gettext('togglerole', 'calendar')) + '"> </a>';
list_html += '<div class="attendee ' + String(data.role).toLowerCase() + '" id="rcmli' + domid + '">' + role_html + dispname + '</div>';
// clone attendees data for local modifications
freebusy_ui.attendees[i] = freebusy_ui.attendees[domid] = $.extend({}, data);
}
// add total row
list_html += '<div class="attendee spacer"> </div>';
list_html += '<div class="attendee total">' + rcmail.gettext('reqallattendees','calendar') + '</div>';
$('#schedule-attendees-list').html(list_html)
.unbind('click.roleicons')
.bind('click.roleicons', function(e){
// toggle attendee status upon click on icon
if (e.target.id && e.target.id.match(/rcmlia(.+)/)) {
var attendee, domid = RegExp.$1, roles = [ 'REQ-PARTICIPANT', 'OPT-PARTICIPANT', 'CHAIR' ];
if ((attendee = freebusy_ui.attendees[domid]) && attendee.role != 'ORGANIZER') {
var req = attendee.role != 'OPT-PARTICIPANT';
var j = $.inArray(attendee.role, roles);
j = (j+1) % roles.length;
attendee.role = roles[j];
$(e.target).parent().removeClass().addClass('attendee '+String(attendee.role).toLowerCase());
// update total display if required-status changed
if (req != (roles[j] != 'OPT-PARTICIPANT')) {
compute_freebusy_totals();
update_freebusy_display(attendee.email);
}
}
}
return false;
});
// enable/disable buttons
$('#shedule-find-prev').button('option', 'disabled', (fb_start.getTime() < now.getTime()));
// dialog buttons
var buttons = {};
buttons[rcmail.gettext('select', 'calendar')] = function() {
$('#edit-startdate').val(freebusy_ui.startdate.val());
$('#edit-starttime').val(freebusy_ui.starttime.val());
$('#edit-enddate').val(freebusy_ui.enddate.val());
$('#edit-endtime').val(freebusy_ui.endtime.val());
// write role changes back to main dialog
$('select.edit-attendee-role').each(function(i, elem){
if (event_attendees[i] && freebusy_ui.attendees[i]) {
event_attendees[i].role = freebusy_ui.attendees[i].role;
$(elem).val(event_attendees[i].role);
}
});
if (freebusy_ui.needsupdate)
update_freebusy_status(me.selected_event);
freebusy_ui.needsupdate = false;
$dialog.dialog("close");
};
buttons[rcmail.gettext('cancel', 'calendar')] = function() {
$dialog.dialog("close");
};
$dialog.dialog({
modal: true,
resizable: true,
closeOnEscape: (!bw.ie6 && !bw.ie7),
title: rcmail.gettext('scheduletime', 'calendar'),
open: function() {
$dialog.parent().find('.ui-dialog-buttonset .ui-button').first().focus();
},
close: function() {
if (bw.ie6)
$("#edit-attendees-table").css('visibility','visible');
$dialog.dialog("destroy").hide();
},
resizeStop: function() {
render_freebusy_overlay();
},
buttons: buttons,
minWidth: 640,
width: 850
}).show();
// hide edit dialog on IE6 because of drop-down elements
if (bw.ie6)
$("#edit-attendees-table").css('visibility','hidden');
// adjust dialog size to fit grid without scrolling
var gridw = $('#schedule-freebusy-times').width();
var overflow = gridw - $('#attendees-freebusy-table td.times').width() + 1;
me.dialog_resize($dialog.get(0), $dialog.height() + (bw.ie ? 20 : 0), 800 + Math.max(0, overflow));
// fetch data from server
freebusy_ui.loading = 0;
load_freebusy_data(freebusy_ui.start, freebusy_ui.interval);
};
// render an HTML table showing free-busy status for all the event attendees
var render_freebusy_grid = function(delta)
{
if (delta) {
freebusy_ui.start.setTime(freebusy_ui.start.getTime() + DAY_MS * delta);
fix_date(freebusy_ui.start);
// skip weekends if in workinhoursonly-mode
if (Math.abs(delta) == 1 && freebusy_ui.workinhoursonly) {
while (is_weekend(freebusy_ui.start))
freebusy_ui.start.setTime(freebusy_ui.start.getTime() + DAY_MS * delta);
fix_date(freebusy_ui.start);
}
freebusy_ui.end = new Date(freebusy_ui.start.getTime() + DAY_MS * freebusy_ui.numdays);
}
var dayslots = Math.floor(1440 / freebusy_ui.interval);
var date_format = 'ddd '+ (dayslots <= 2 ? settings.date_short : settings.date_format);
var lastdate, datestr, css,
curdate = new Date(),
allday = (freebusy_ui.interval == 1440),
times_css = (allday ? 'allday ' : ''),
dates_row = '<tr class="dates">',
times_row = '<tr class="times">',
slots_row = '';
for (var s = 0, t = freebusy_ui.start.getTime(); t < freebusy_ui.end.getTime(); s++) {
curdate.setTime(t);
datestr = fc.fullCalendar('formatDate', curdate, date_format);
if (datestr != lastdate) {
if (lastdate && !allday) break;
dates_row += '<th colspan="' + dayslots + '" class="boxtitle date' + $.fullCalendar.formatDate(curdate, 'ddMMyyyy') + '">' + Q(datestr) + '</th>';
lastdate = datestr;
}
// set css class according to working hours
css = is_weekend(curdate) || (freebusy_ui.interval <= 60 && !is_workinghour(curdate)) ? 'offhours' : 'workinghours';
times_row += '<td class="' + times_css + css + '" id="t-' + Math.floor(t/1000) + '">' + Q(allday ? rcmail.gettext('all-day','calendar') : $.fullCalendar.formatDate(curdate, settings['time_format'])) + '</td>';
slots_row += '<td class="' + css + ' unknown"> </td>';
t += freebusy_ui.interval * 60000;
}
dates_row += '</tr>';
times_row += '</tr>';
// render list of attendees
var domid, data, list_html = '', times_html = '';
for (var i=0; i < event_attendees.length; i++) {
data = event_attendees[i];
domid = String(data.email).replace(rcmail.identifier_expr, '');
times_html += '<tr id="fbrow' + domid + '">' + slots_row + '</tr>';
}
// add line for all/required attendees
times_html += '<tr class="spacer"><td colspan="' + (dayslots * freebusy_ui.numdays) + '"> </td>';
times_html += '<tr id="fbrowall">' + slots_row + '</tr>';
var table = $('#schedule-freebusy-times');
table.children('thead').html(dates_row + times_row);
table.children('tbody').html(times_html);
// initialize event handlers on grid
if (!freebusy_ui.grid_events) {
freebusy_ui.grid_events = true;
table.children('thead').click(function(e){
// move event to the clicked date/time
if (e.target.id && e.target.id.match(/t-(\d+)/)) {
var newstart = new Date(RegExp.$1 * 1000);
// set time to 00:00
if (me.selected_event.allDay) {
newstart.setMinutes(0);
newstart.setHours(0);
}
update_freebusy_dates(newstart, new Date(newstart.getTime() + freebusy_ui.startdate.data('duration') * 1000));
render_freebusy_overlay();
}
})
}
// if we have loaded free-busy data, show it
if (!freebusy_ui.loading) {
if (freebusy_ui.start < freebusy_data.start || freebusy_ui.end > freebusy_data.end || freebusy_ui.interval != freebusy_data.interval) {
load_freebusy_data(freebusy_ui.start, freebusy_ui.interval);
}
else {
for (var email, i=0; i < event_attendees.length; i++) {
if ((email = event_attendees[i].email))
update_freebusy_display(email);
}
}
}
// render current event date/time selection over grid table
// use timeout to let the dom attributes (width/height/offset) be set first
window.setTimeout(function(){ render_freebusy_overlay(); }, 10);
};
// render overlay element over the grid to visiualize the current event date/time
var render_freebusy_overlay = function()
{
var overlay = $('#schedule-event-time');
if (me.selected_event.end.getTime() <= freebusy_ui.start.getTime() || me.selected_event.start.getTime() >= freebusy_ui.end.getTime()) {
overlay.hide();
if (overlay.data('isdraggable'))
overlay.draggable('disable');
}
else {
var table = $('#schedule-freebusy-times'),
width = 0,
pos = { top:table.children('thead').height(), left:0 },
eventstart = date2unixtime(clone_date(me.selected_event.start, me.selected_event.allDay?1:0)),
eventend = date2unixtime(clone_date(me.selected_event.end, me.selected_event.allDay?2:0)) - 60,
slotstart = date2unixtime(freebusy_ui.start),
slotsize = freebusy_ui.interval * 60,
slotend, fraction, $cell;
// iterate through slots to determine position and size of the overlay
table.children('thead').find('td').each(function(i, cell){
slotend = slotstart + slotsize - 1;
// event starts in this slot: compute left
if (eventstart >= slotstart && eventstart <= slotend) {
fraction = 1 - (slotend - eventstart) / slotsize;
pos.left = Math.round(cell.offsetLeft + cell.offsetWidth * fraction);
}
// event ends in this slot: compute width
if (eventend >= slotstart && eventend <= slotend) {
fraction = 1 - (slotend - eventend) / slotsize;
width = Math.round(cell.offsetLeft + cell.offsetWidth * fraction) - pos.left;
}
slotstart = slotstart + slotsize;
});
if (!width)
width = table.width() - pos.left;
// overlay is visible
if (width > 0) {
overlay.css({ width: (width-5)+'px', height:(table.children('tbody').height() - 4)+'px', left:pos.left+'px', top:pos.top+'px' }).show();
// configure draggable
if (!overlay.data('isdraggable')) {
overlay.draggable({
axis: 'x',
scroll: true,
stop: function(e, ui){
// convert pixels to time
var px = ui.position.left;
var range_p = $('#schedule-freebusy-times').width();
var range_t = freebusy_ui.end.getTime() - freebusy_ui.start.getTime();
var newstart = new Date(freebusy_ui.start.getTime() + px * (range_t / range_p));
newstart.setSeconds(0); newstart.setMilliseconds(0);
// snap to day boundaries
if (me.selected_event.allDay) {
if (newstart.getHours() >= 12) // snap to next day
newstart.setTime(newstart.getTime() + DAY_MS);
newstart.setMinutes(0);
newstart.setHours(0);
}
else {
// round to 5 minutes
var round = newstart.getMinutes() % 5;
if (round > 2.5) newstart.setTime(newstart.getTime() + (5 - round) * 60000);
else if (round > 0) newstart.setTime(newstart.getTime() - round * 60000);
}
// update event times and display
update_freebusy_dates(newstart, new Date(newstart.getTime() + freebusy_ui.startdate.data('duration') * 1000));
if (me.selected_event.allDay)
render_freebusy_overlay();
}
}).data('isdraggable', true);
}
else
overlay.draggable('enable');
}
else
overlay.draggable('disable').hide();
}
};
// fetch free-busy information for each attendee from server
var load_freebusy_data = function(from, interval)
{
var start = new Date(from.getTime() - DAY_MS * 2); // start 2 days before event
fix_date(start);
var end = new Date(start.getTime() + DAY_MS * Math.max(14, freebusy_ui.numdays + 7)); // load min. 14 days
freebusy_ui.numrequired = 0;
freebusy_data.all = [];
freebusy_data.required = [];
// load free-busy information for every attendee
var domid, email;
for (var i=0; i < event_attendees.length; i++) {
if ((email = event_attendees[i].email)) {
domid = String(email).replace(rcmail.identifier_expr, '');
$('#rcmli' + domid).addClass('loading');
freebusy_ui.loading++;
$.ajax({
type: 'GET',
dataType: 'json',
url: rcmail.url('freebusy-times'),
data: { email:email, start:date2servertime(clone_date(start, 1)), end:date2servertime(clone_date(end, 2)), interval:interval, _remote:1 },
success: function(data) {
freebusy_ui.loading--;
// find attendee
var attendee = null;
for (var i=0; i < event_attendees.length; i++) {
if (freebusy_ui.attendees[i].email == data.email) {
attendee = freebusy_ui.attendees[i];
break;
}
}
// copy data to member var
var ts, req = attendee.role != 'OPT-PARTICIPANT';
freebusy_data.start = parseISO8601(data.start);
freebusy_data[data.email] = {};
for (var i=0; i < data.slots.length; i++) {
ts = data.times[i] + '';
freebusy_data[data.email][ts] = data.slots[i];
// set totals
if (!freebusy_data.required[ts])
freebusy_data.required[ts] = [0,0,0,0];
if (req)
freebusy_data.required[ts][data.slots[i]]++;
if (!freebusy_data.all[ts])
freebusy_data.all[ts] = [0,0,0,0];
freebusy_data.all[ts][data.slots[i]]++;
}
freebusy_data.end = parseISO8601(data.end);
freebusy_data.interval = data.interval;
// hide loading indicator
var domid = String(data.email).replace(rcmail.identifier_expr, '');
$('#rcmli' + domid).removeClass('loading');
// update display
update_freebusy_display(data.email);
}
});
// count required attendees
if (freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT')
freebusy_ui.numrequired++;
}
}
};
// re-calculate total status after role change
var compute_freebusy_totals = function()
{
freebusy_ui.numrequired = 0;
freebusy_data.all = [];
freebusy_data.required = [];
var email, req, status;
for (var i=0; i < event_attendees.length; i++) {
if (!(email = event_attendees[i].email))
continue;
req = freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT';
if (req)
freebusy_ui.numrequired++;
for (var ts in freebusy_data[email]) {
if (!freebusy_data.required[ts])
freebusy_data.required[ts] = [0,0,0,0];
if (!freebusy_data.all[ts])
freebusy_data.all[ts] = [0,0,0,0];
status = freebusy_data[email][ts];
freebusy_data.all[ts][status]++;
if (req)
freebusy_data.required[ts][status]++;
}
}
};
// update free-busy grid with status loaded from server
var update_freebusy_display = function(email)
{
var status_classes = ['unknown','free','busy','tentative','out-of-office'];
var domid = String(email).replace(rcmail.identifier_expr, '');
var row = $('#fbrow' + domid);
var rowall = $('#fbrowall').children();
var dateonly = freebusy_ui.interval > 60,
t, ts = date2timestring(freebusy_ui.start, dateonly),
curdate = new Date(),
fbdata = freebusy_data[email];
if (fbdata && fbdata[ts] !== undefined && row.length) {
t = freebusy_ui.start.getTime();
row.children().each(function(i, cell){
curdate.setTime(t);
ts = date2timestring(curdate, dateonly);
cell.className = cell.className.replace('unknown', fbdata[ts] ? status_classes[fbdata[ts]] : 'unknown');
// also update total row if all data was loaded
if (freebusy_ui.loading == 0 && freebusy_data.all[ts] && (cell = rowall.get(i))) {
var workinghours = cell.className.indexOf('workinghours') >= 0;
var all_status = freebusy_data.all[ts][2] ? 'busy' : 'unknown';
req_status = freebusy_data.required[ts][2] ? 'busy' : 'free';
for (var j=1; j < status_classes.length; j++) {
if (freebusy_ui.numrequired && freebusy_data.required[ts][j] >= freebusy_ui.numrequired)
req_status = status_classes[j];
if (freebusy_data.all[ts][j] == event_attendees.length)
all_status = status_classes[j];
}
cell.className = (workinghours ? 'workinghours ' : 'offhours ') + req_status + ' all-' + all_status;
}
t += freebusy_ui.interval * 60000;
});
}
};
// write changed event date/times back to form fields
var update_freebusy_dates = function(start, end)
{
// fix all-day evebt times
if (me.selected_event.allDay) {
var numdays = Math.floor((me.selected_event.end.getTime() - me.selected_event.start.getTime()) / DAY_MS);
start.setHours(12);
start.setMinutes(0);
end.setTime(start.getTime() + numdays * DAY_MS);
end.setHours(13);
end.setMinutes(0);
}
me.selected_event.start = start;
me.selected_event.end = end;
freebusy_ui.startdate.val($.fullCalendar.formatDate(start, settings['date_format']));
freebusy_ui.starttime.val($.fullCalendar.formatDate(start, settings['time_format']));
freebusy_ui.enddate.val($.fullCalendar.formatDate(end, settings['date_format']));
freebusy_ui.endtime.val($.fullCalendar.formatDate(end, settings['time_format']));
freebusy_ui.needsupdate = true;
};
// attempt to find a time slot where all attemdees are available
var freebusy_find_slot = function(dir)
{
// exit if free-busy data isn't available yet
if (!freebusy_data || !freebusy_data.start)
return false;
var event = me.selected_event,
eventstart = clone_date(event.start, event.allDay ? 1 : 0).getTime(), // calculate with integers
eventend = clone_date(event.end, event.allDay ? 2 : 0).getTime(),
duration = eventend - eventstart - (event.allDay ? HOUR_MS : 0), // make sure we don't cross day borders on DST change
sinterval = freebusy_data.interval * 60000,
intvlslots = 1,
numslots = Math.ceil(duration / sinterval),
checkdate, slotend, email, ts, slot, slotdate = new Date();
// shift event times to next possible slot
eventstart += sinterval * intvlslots * dir;
eventend += sinterval * intvlslots * dir;
// iterate through free-busy slots and find candidates
var candidatecount = 0, candidatestart = candidateend = success = false;
for (slot = dir > 0 ? freebusy_data.start.getTime() : freebusy_data.end.getTime() - sinterval;
(dir > 0 && slot < freebusy_data.end.getTime()) || (dir < 0 && slot >= freebusy_data.start.getTime());
slot += sinterval * dir) {
slotdate.setTime(slot);
// fix slot if just crossed a DST change
if (event.allDay) {
fix_date(slotdate);
slot = slotdate.getTime();
}
slotend = slot + sinterval;
if ((dir > 0 && slotend <= eventstart) || (dir < 0 && slot >= eventend)) // skip
continue;
// respect workingours setting
if (freebusy_ui.workinhoursonly) {
if (is_weekend(slotdate) || (freebusy_data.interval <= 60 && !is_workinghour(slotdate))) { // skip off-hours
candidatestart = candidateend = false;
candidatecount = 0;
continue;
}
}
if (!candidatestart)
candidatestart = slot;
// check freebusy data for all attendees
ts = date2timestring(slotdate, freebusy_data.interval > 60);
for (var i=0; i < event_attendees.length; i++) {
if (freebusy_ui.attendees[i].role != 'OPT-PARTICIPANT' && (email = freebusy_ui.attendees[i].email) && freebusy_data[email] && freebusy_data[email][ts] > 1) {
candidatestart = candidateend = false;
break;
}
}
// occupied slot
if (!candidatestart) {
slot += Math.max(0, intvlslots - candidatecount - 1) * sinterval * dir;
candidatecount = 0;
continue;
}
// set candidate end to slot end time
candidatecount++;
if (dir < 0 && !candidateend)
candidateend = slotend;
// if candidate is big enough, this is it!
if (candidatecount == numslots) {
if (dir > 0) {
event.start.setTime(candidatestart);
event.end.setTime(candidatestart + duration);
}
else {
event.end.setTime(candidateend);
event.start.setTime(candidateend - duration);
}
success = true;
break;
}
}
// update event date/time display
if (success) {
update_freebusy_dates(event.start, event.end);
// move freebusy grid if necessary
var offset = Math.ceil((event.start.getTime() - freebusy_ui.end.getTime()) / DAY_MS);
if (event.start.getTime() >= freebusy_ui.end.getTime())
render_freebusy_grid(Math.max(1, offset));
else if (event.end.getTime() <= freebusy_ui.start.getTime())
render_freebusy_grid(Math.min(-1, offset));
else
render_freebusy_overlay();
var now = new Date();
$('#shedule-find-prev').button('option', 'disabled', (event.start.getTime() < now.getTime()));
}
else {
alert(rcmail.gettext('noslotfound','calendar'));
}
};
// update event properties and attendees availability if event times have changed
var event_times_changed = function()
{
if (me.selected_event) {
var allday = $('#edit-allday').get(0);
me.selected_event.allDay = allday.checked;
me.selected_event.start = parse_datetime(allday.checked ? '12:00' : $('#edit-starttime').val(), $('#edit-startdate').val());
me.selected_event.end = parse_datetime(allday.checked ? '13:00' : $('#edit-endtime').val(), $('#edit-enddate').val());
if (event_attendees)
freebusy_ui.needsupdate = true;
$('#edit-startdate').data('duration', Math.round((me.selected_event.end.getTime() - me.selected_event.start.getTime()) / 1000));
}
};
// add the given list of participants
var add_attendees = function(names)
{
names = explode_quoted_string(names.replace(/,\s*$/, ''), ',');
// parse name/email pairs
var item, email, name, success = false;
for (var i=0; i < names.length; i++) {
email = name = '';
item = $.trim(names[i]);
if (!item.length) {
continue;
} // address in brackets without name (do nothing)
else if (item.match(/^<[^@]+@[^>]+>$/)) {
email = item.replace(/[<>]/g, '');
} // address without brackets and without name (add brackets)
else if (rcube_check_email(item)) {
email = item;
} // address with name
else if (item.match(/([^\s<@]+@[^>]+)>*$/)) {
email = RegExp.$1;
name = item.replace(email, '').replace(/^["\s<>]+/, '').replace(/["\s<>]+$/, '');
}
if (email) {
add_attendee({ email:email, name:name, role:'REQ-PARTICIPANT', status:'NEEDS-ACTION' });
success = true;
}
else {
alert(rcmail.gettext('noemailwarning'));
}
}
return success;
};
// add the given attendee to the list
var add_attendee = function(data, readonly)
{
// check for dupes...
var exists = false;
$.each(event_attendees, function(i, v){ exists |= (v.email == data.email); });
if (exists)
return false;
var dispname = Q(data.name || data.email);
if (data.email)
dispname = '<a href="mailto:' + data.email + '" title="' + Q(data.email) + '" class="mailtolink">' + dispname + '</a>';
// role selection
var organizer = data.role == 'ORGANIZER';
var opts = {};
if (organizer)
opts.ORGANIZER = rcmail.gettext('calendar.roleorganizer');
opts['REQ-PARTICIPANT'] = rcmail.gettext('calendar.rolerequired');
opts['OPT-PARTICIPANT'] = rcmail.gettext('calendar.roleoptional');
opts['CHAIR'] = rcmail.gettext('calendar.rolechair');
if (organizer && !readonly)
dispname = rcmail.env['identities-selector'];
var select = '<select class="edit-attendee-role"' + (organizer || readonly ? ' disabled="true"' : '') + '>';
for (var r in opts)
select += '<option value="'+ r +'" class="' + r.toLowerCase() + '"' + (data.role == r ? ' selected="selected"' : '') +'>' + Q(opts[r]) + '</option>';
select += '</select>';
// availability
var avail = data.email ? 'loading' : 'unknown';
// delete icon
var icon = rcmail.env.deleteicon ? '<img src="' + rcmail.env.deleteicon + '" alt="" />' : rcmail.gettext('delete');
var dellink = '<a href="#delete" class="iconlink delete deletelink" title="' + Q(rcmail.gettext('delete')) + '">' + icon + '</a>';
var html = '<td class="role">' + select + '</td>' +
'<td class="name">' + dispname + '</td>' +
'<td class="availability"><img src="./program/resources/blank.gif" class="availabilityicon ' + avail + '" /></td>' +
'<td class="confirmstate"><span class="' + String(data.status).toLowerCase() + '">' + Q(data.status) + '</span></td>' +
'<td class="options">' + (organizer || readonly ? '' : dellink) + '</td>';
var tr = $('<tr>')
.addClass(String(data.role).toLowerCase())
.html(html)
.appendTo(attendees_list);
tr.find('a.deletelink').click({ id:(data.email || data.name) }, function(e) { remove_attendee(this, e.data.id); return false; });
tr.find('a.mailtolink').click(function(e) { rcmail.redirect(rcmail.url('mail/compose', { _to:this.href.substr(7) })); return false; });
// select organizer identity
if (data.identity_id)
$('#edit-identities-list').val(data.identity_id);
// check free-busy status
if (avail == 'loading') {
check_freebusy_status(tr.find('img.availabilityicon'), data.email, me.selected_event);
}
event_attendees.push(data);
};
// iterate over all attendees and update their free-busy status display
var update_freebusy_status = function(event)
{
var icons = attendees_list.find('img.availabilityicon');
for (var i=0; i < event_attendees.length; i++) {
if (icons.get(i) && event_attendees[i].email)
check_freebusy_status(icons.get(i), event_attendees[i].email, event);
}
freebusy_ui.needsupdate = false;
};
// load free-busy status from server and update icon accordingly
var check_freebusy_status = function(icon, email, event)
{
var calendar = event.calendar && me.calendars[event.calendar] ? me.calendars[event.calendar] : { freebusy:false };
if (!calendar.freebusy) {
$(icon).removeClass().addClass('availabilityicon unknown');
return;
}
icon = $(icon).removeClass().addClass('availabilityicon loading');
$.ajax({
type: 'GET',
dataType: 'html',
url: rcmail.url('freebusy-status'),
data: { email:email, start:date2servertime(clone_date(event.start, event.allDay?1:0)), end:date2servertime(clone_date(event.end, event.allDay?2:0)), _remote: 1 },
success: function(status){
icon.removeClass('loading').addClass(String(status).toLowerCase());
},
error: function(){
icon.removeClass('loading').addClass('unknown');
}
});
};
// remove an attendee from the list
var remove_attendee = function(elem, id)
{
$(elem).closest('tr').remove();
event_attendees = $.grep(event_attendees, function(data){ return (data.name != id && data.email != id) });
};
// when the user accepts or declines an event invitation
var event_rsvp = function(response)
{
if (me.selected_event && me.selected_event.attendees && response) {
// update attendee status
for (var data, i=0; i < me.selected_event.attendees.length; i++) {
data = me.selected_event.attendees[i];
if (settings.identity.emails.indexOf(';'+String(data.email).toLowerCase()) >= 0)
data.status = response.toUpperCase();
}
event_show_dialog(me.selected_event);
// submit status change to server
me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata');
rcmail.http_post('event', { action:'rsvp', e:me.selected_event, status:response });
}
}
// post the given event data to server
var update_event = function(action, data)
{
me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata');
rcmail.http_post('calendar/event', { action:action, e:data });
// render event temporarily into the calendar
if ((data.start && data.end) || data.id) {
var event = data.id ? $.extend(fc.fullCalendar('clientEvents', function(e){ return e.id == data.id; })[0], data) : data;
if (data.start)
event.start = data.start;
if (data.end)
event.end = data.end;
if (data.allday !== undefined)
event.allDay = data.allday;
event.editable = false;
event.temp = true;
event.className = 'fc-event-cal-'+data.calendar+' fc-event-temp';
fc.fullCalendar(data.id ? 'updateEvent' : 'renderEvent', event);
}
};
// mouse-click handler to check if the show dialog is still open and prevent default action
var dialog_check = function(e)
{
var showd = $("#eventshow");
if (showd.is(':visible') && !$(e.target).closest('.ui-dialog').length) {
showd.dialog('close');
e.stopImmediatePropagation();
ignore_click = true;
return false;
}
else if (ignore_click) {
window.setTimeout(function(){ ignore_click = false; }, 20);
return false;
}
return true;
};
// display confirm dialog when modifying/deleting an event
var update_event_confirm = function(action, event, data)
{
if (!data) data = event;
var decline = false, notify = false, html = '', cal = me.calendars[event.calendar];
// event has attendees, ask whether to notify them
if (has_attendees(event)) {
if (is_organizer(event)) {
notify = true;
html += '<div class="message">' +
'<label><input class="confirm-attendees-donotify" type="checkbox" checked="checked" value="1" name="notify" /> ' +
rcmail.gettext((action == 'remove' ? 'sendcancellation' : 'sendnotifications'), 'calendar') +
'</label></div>';
}
else if (action == 'remove' && is_attendee(event)) {
decline = true;
html += '<div class="message">' +
'<label><input class="confirm-attendees-decline" type="checkbox" checked="checked" value="1" name="decline" /> ' +
rcmail.gettext('itipdeclineevent', 'calendar') +
'</label></div>';
}
else {
html += '<div class="message">' + rcmail.gettext('localchangeswarning', 'calendar') + '</div>';
}
}
// recurring event: user needs to select the savemode
if (event.recurrence) {
html += '<div class="message"><span class="ui-icon ui-icon-alert"></span>' +
rcmail.gettext((action == 'remove' ? 'removerecurringeventwarning' : 'changerecurringeventwarning'), 'calendar') + '</div>' +
'<div class="savemode">' +
'<a href="#current" class="button">' + rcmail.gettext('currentevent', 'calendar') + '</a>' +
'<a href="#future" class="button">' + rcmail.gettext('futurevents', 'calendar') + '</a>' +
'<a href="#all" class="button">' + rcmail.gettext('allevents', 'calendar') + '</a>' +
(action != 'remove' ? '<a href="#new" class="button">' + rcmail.gettext('saveasnew', 'calendar') + '</a>' : '') +
'</div>';
}
// show dialog
if (html) {
var $dialog = $('<div>').html(html);
$dialog.find('a.button').button().click(function(e){
data._savemode = String(this.href).replace(/.+#/, '');
if ($dialog.find('input.confirm-attendees-donotify').get(0))
data._notify = notify && $dialog.find('input.confirm-attendees-donotify').get(0).checked ? 1 : 0;
if (decline && $dialog.find('input.confirm-attendees-decline:checked'))
data.decline = 1;
update_event(action, data);
$dialog.dialog("destroy").hide();
return false;
});
var buttons = [{
text: rcmail.gettext('cancel', 'calendar'),
click: function() {
$(this).dialog("close");
}
}];
if (!event.recurrence) {
buttons.push({
text: rcmail.gettext((action == 'remove' ? 'remove' : 'save'), 'calendar'),
click: function() {
data._notify = notify && $dialog.find('input.confirm-attendees-donotify').get(0).checked ? 1 : 0;
data.decline = decline && $dialog.find('input.confirm-attendees-decline:checked').length ? 1 : 0;
update_event(action, data);
$(this).dialog("close");
}
});
}
$dialog.dialog({
modal: true,
width: 460,
dialogClass: 'warning',
title: rcmail.gettext((action == 'remove' ? 'removeeventconfirm' : 'changeeventconfirm'), 'calendar'),
buttons: buttons,
close: function(){
$dialog.dialog("destroy").hide();
if (!rcmail.busy)
fc.fullCalendar('refetchEvents');
}
}).addClass('event-update-confirm').show();
return false;
}
// show regular confirm box when deleting
else if (action == 'remove' && !cal.undelete) {
if (!confirm(rcmail.gettext('deleteventconfirm', 'calendar')))
return false;
}
// do update
update_event(action, data);
return true;
};
var update_agenda_toolbar = function()
{
$('#agenda-listrange').val(fc.fullCalendar('option', 'listRange'));
$('#agenda-listsections').val(fc.fullCalendar('option', 'listSections'));
}
/*** fullcalendar event handlers ***/
var fc_event_render = function(event, element, view) {
if (view.name != 'list' && view.name != 'table') {
var prefix = event.sensitivity && event.sensitivity != 'public' ? String(sensitivitylabels[event.sensitivity]).toUpperCase()+': ' : '';
element.attr('title', prefix + event.title);
}
if (view.name != 'month') {
if (event.location) {
element.find('div.fc-event-title').after('<div class="fc-event-location">@ ' + Q(event.location) + '</div>');
}
if (event.sensitivity && event.sensitivity != 'public')
element.find('div.fc-event-time').append('<i class="fc-icon-sensitive"></i>');
if (event.recurrence)
element.find('div.fc-event-time').append('<i class="fc-icon-recurring"></i>');
if (event.alarms)
element.find('div.fc-event-time').append('<i class="fc-icon-alarms"></i>');
}
};
/*** public methods ***/
/**
* Remove saving lock and free the UI for new input
*/
this.unlock_saving = function()
{
if (me.saving_lock)
rcmail.set_busy(false, null, me.saving_lock);
};
// opens calendar day-view in a popup
this.fisheye_view = function(date)
{
$('#fish-eye-view:ui-dialog').dialog('close');
// create list of active event sources
var src, cals = {}, sources = [];
for (var id in this.calendars) {
src = $.extend({}, this.calendars[id]);
src.editable = false;
src.url = null;
src.events = [];
if (src.active) {
cals[id] = src;
sources.push(src);
}
}
// copy events already loaded
var events = fc.fullCalendar('clientEvents');
for (var event, i=0; i< events.length; i++) {
event = events[i];
if (event.source && (src = cals[event.source.id])) {
src.events.push(event);
}
}
var h = $(window).height() - 50;
var dialog = $('<div>')
.attr('id', 'fish-eye-view')
.dialog({
modal: true,
width: 680,
height: h,
title: $.fullCalendar.formatDate(date, 'dddd ' + settings['date_long']),
close: function(){
dialog.dialog("destroy");
me.fisheye_date = null;
}
})
.fullCalendar({
header: { left: '', center: '', right: '' },
height: h - 50,
defaultView: 'agendaDay',
date: date.getDate(),
month: date.getMonth(),
year: date.getFullYear(),
ignoreTimezone: true, // will treat the given date strings as in local (browser's) timezone
eventSources: sources,
monthNames : settings['months'],
monthNamesShort : settings['months_short'],
dayNames : settings['days'],
dayNamesShort : settings['days_short'],
firstDay : settings['first_day'],
firstHour : settings['first_hour'],
slotMinutes : 60/settings['timeslots'],
timeFormat: { '': settings['time_format'] },
axisFormat : settings['time_format'],
columnFormat: { day: 'dddd ' + settings['date_short'] },
titleFormat: { day: 'dddd ' + settings['date_long'] },
allDayText: rcmail.gettext('all-day', 'calendar'),
currentTimeIndicator: settings.time_indicator,
eventRender: fc_event_render,
eventClick: function(event) {
event_show_dialog(event);
}
});
this.fisheye_date = date;
};
//public method to show the print dialog.
this.print_calendars = function(view)
{
if (!view) view = fc.fullCalendar('getView').name;
var date = fc.fullCalendar('getDate') || new Date();
var range = fc.fullCalendar('option', 'listRange');
var sections = fc.fullCalendar('option', 'listSections');
rcmail.open_window(rcmail.url('print', { view: view, date: date2unixtime(date), range: range, sections: sections, search: this.search_query }), true, true);
};
// public method to bring up the new event dialog
this.add_event = function(templ) {
if (this.selected_calendar) {
var now = new Date();
var date = fc.fullCalendar('getDate');
if (typeof date != 'Date')
date = now;
date.setHours(now.getHours()+1);
date.setMinutes(0);
var end = new Date(date.getTime());
end.setHours(date.getHours()+1);
event_edit_dialog('new', $.extend({ start:date, end:end, allDay:false, calendar:this.selected_calendar }, templ || {}));
}
};
// delete the given event after showing a confirmation dialog
this.delete_event = function(event) {
// show confirm dialog for recurring events, use jquery UI dialog
return update_event_confirm('remove', event, { id:event.id, calendar:event.calendar, attendees:event.attendees });
};
// opens a jquery UI dialog with event properties (or empty for creating a new calendar)
this.calendar_edit_dialog = function(calendar)
{
// close show dialog first
var $dialog = $("#calendarform");
if ($dialog.is(':ui-dialog'))
$dialog.dialog('close');
if (!calendar)
calendar = { name:'', color:'cc0000', editable:true, showalarms:true };
var form, name, color, alarms;
$dialog.html(rcmail.get_label('loading'));
$.ajax({
type: 'GET',
dataType: 'html',
url: rcmail.url('calendar'),
data: { action:(calendar.id ? 'form-edit' : 'form-new'), c:{ id:calendar.id } },
success: function(data) {
$dialog.html(data);
// resize and reposition dialog window
form = $('#calendarpropform');
me.dialog_resize('#calendarform', form.height(), form.width());
name = $('#calendar-name').prop('disabled', !calendar.editable).val(calendar.editname || calendar.name);
color = $('#calendar-color').val(calendar.color).miniColors({ value: calendar.color, colorValues:rcmail.env.mscolors });
alarms = $('#calendar-showalarms').prop('checked', calendar.showalarms).get(0);
name.select();
}
});
// dialog buttons
var buttons = {};
buttons[rcmail.gettext('save', 'calendar')] = function() {
// form is not loaded
if (!form || !form.length)
return;
// TODO: do some input validation
if (!name.val() || name.val().length < 2) {
alert(rcmail.gettext('invalidcalendarproperties', 'calendar'));
name.select();
return;
}
// post data to server
var data = form.serializeJSON();
if (data.color)
data.color = data.color.replace(/^#/, '');
if (calendar.id)
data.id = calendar.id;
if (alarms)
data.showalarms = alarms.checked ? 1 : 0;
me.saving_lock = rcmail.set_busy(true, 'calendar.savingdata');
rcmail.http_post('calendar', { action:(calendar.id ? 'edit' : 'new'), c:data });
$dialog.dialog("close");
};
buttons[rcmail.gettext('cancel', 'calendar')] = function() {
$dialog.dialog("close");
};
// open jquery UI dialog
$dialog.dialog({
modal: true,
resizable: true,
closeOnEscape: false,
title: rcmail.gettext((calendar.id ? 'editcalendar' : 'createcalendar'), 'calendar'),
close: function() {
$dialog.html('').dialog("destroy").hide();
},
buttons: buttons,
minWidth: 400,
width: 420
}).show();
};
this.calendar_remove = function(calendar)
{
if (confirm(rcmail.gettext(calendar.children ? 'deletecalendarconfirmrecursive' : 'deletecalendarconfirm', 'calendar'))) {
rcmail.http_post('calendar', { action:'remove', c:{ id:calendar.id } });
return true;
}
return false;
};
this.calendar_destroy_source = function(id)
{
var delete_ids = [];
if (this.calendars[id]) {
// find sub-calendars
if (this.calendars[id].children) {
for (var child_id in this.calendars) {
if (String(child_id).indexOf(id) == 0)
delete_ids.push(child_id);
}
}
else {
delete_ids.push(id);
}
}
// delete all calendars in the list
for (var i=0; i < delete_ids.length; i++) {
id = delete_ids[i];
fc.fullCalendar('removeEventSource', this.calendars[id]);
$(rcmail.get_folder_li(id, 'rcmlical')).remove();
$('#edit-calendar option[value="'+id+'"]').remove();
delete this.calendars[id];
}
};
// open a dialog to upload an .ics file with events to be imported
this.import_events = function(calendar)
{
// close show dialog first
var $dialog = $("#eventsimport"),
form = rcmail.gui_objects.importform;
if ($dialog.is(':ui-dialog'))
$dialog.dialog('close');
if (calendar)
$('#event-import-calendar').val(calendar.id);
var buttons = {};
buttons[rcmail.gettext('import', 'calendar')] = function() {
if (form && form.elements._data.value) {
rcmail.async_upload_form(form, 'import_events', function(e) {
rcmail.set_busy(false, null, me.saving_lock);
$('.ui-dialog-buttonpane button', $dialog.parent()).button('enable');
// display error message if no sophisticated response from server arrived (e.g. iframe load error)
if (me.import_succeeded === null)
rcmail.display_message(rcmail.get_label('importerror', 'calendar'), 'error');
});
// display upload indicator (with extended timeout)
var timeout = rcmail.env.request_timeout;
rcmail.env.request_timeout = 600;
me.import_succeeded = null;
me.saving_lock = rcmail.set_busy(true, 'uploading');
$('.ui-dialog-buttonpane button', $dialog.parent()).button('disable');
// restore settings
rcmail.env.request_timeout = timeout;
}
};
buttons[rcmail.gettext('cancel', 'calendar')] = function() {
$dialog.dialog("close");
};
// open jquery UI dialog
$dialog.dialog({
modal: true,
resizable: false,
closeOnEscape: false,
title: rcmail.gettext('importevents', 'calendar'),
close: function() {
$('.ui-dialog-buttonpane button', $dialog.parent()).button('enable');
$dialog.dialog("destroy").hide();
},
buttons: buttons,
width: 520
}).show();
};
// callback from server if import succeeded
this.import_success = function(p)
{
this.import_succeeded = true;
$("#eventsimport:ui-dialog").dialog('close');
rcmail.set_busy(false, null, me.saving_lock);
rcmail.gui_objects.importform.reset();
if (p.refetch)
this.refresh(p);
};
// callback from server to report errors on import
this.import_error = function(p)
{
this.import_succeeded = false;
rcmail.display_message(p.message || rcmail.get_label('importerror', 'calendar'), 'error');
}
// show URL of the given calendar in a dialog box
this.showurl = function(calendar)
{
var $dialog = $('#calendarurlbox');
if ($dialog.is(':ui-dialog'))
$dialog.dialog('close');
if (calendar.feedurl) {
if (calendar.caldavurl) {
$('#caldavurl').val(calendar.caldavurl);
$('#calendarcaldavurl').show();
}
else {
$('#calendarcaldavurl').hide();
}
$dialog.dialog({
resizable: true,
closeOnEscape: true,
title: rcmail.gettext('showurl', 'calendar'),
close: function() {
$dialog.dialog("destroy").hide();
},
width: 520
}).show();
$('#calfeedurl').val(calendar.feedurl).select();
}
};
// refresh the calendar view after saving event data
this.refresh = function(p)
{
var source = me.calendars[p.source];
if (source && (p.refetch || (p.update && !source.active))) {
// activate event source if new event was added to an invisible calendar
if (!source.active) {
source.active = true;
fc.fullCalendar('addEventSource', source);
$('#' + rcmail.get_folder_li(source.id, 'rcmlical').id + ' input').prop('checked', true);
}
else
fc.fullCalendar('refetchEvents', source);
}
// add/update single event object
else if (source && p.update) {
var event = p.update;
event.temp = false;
event.editable = source.editable;
var existing = fc.fullCalendar('clientEvents', event._id);
if (existing.length) {
$.extend(existing[0], event);
fc.fullCalendar('updateEvent', existing[0]);
}
else {
event.source = source; // link with source
fc.fullCalendar('renderEvent', event);
}
// refresh fish-eye view
if (me.fisheye_date)
me.fisheye_view(me.fisheye_date);
}
// remove temp events
fc.fullCalendar('removeEvents', function(e){ return e.temp; });
};
// modify query parameters for refresh requests
this.before_refresh = function(query)
{
var view = fc.fullCalendar('getView');
query.start = date2unixtime(view.visStart);
query.end = date2unixtime(view.visEnd);
if (this.search_query)
query.q = this.search_query;
return query;
};
/*** event searching ***/
// execute search
this.quicksearch = function()
{
if (rcmail.gui_objects.qsearchbox) {
var q = rcmail.gui_objects.qsearchbox.value;
if (q != '') {
var id = 'search-'+q;
var sources = [];
if (this._search_message)
rcmail.hide_message(this._search_message);
for (var sid in this.calendars) {
if (this.calendars[sid]) {
this.calendars[sid].url = this.calendars[sid].url.replace(/&q=.+/, '') + '&q='+escape(q);
sources.push(sid);
}
}
id += '@'+sources.join(',');
// ignore if query didn't change
if (this.search_request == id) {
return;
}
// remember current view
else if (!this.search_request) {
this.default_view = fc.fullCalendar('getView').name;
}
this.search_request = id;
this.search_query = q;
// change to list view
fc.fullCalendar('option', 'listSections', 'month')
.fullCalendar('option', 'listRange', Math.max(60, settings['agenda_range']))
.fullCalendar('changeView', 'table');
update_agenda_toolbar();
// refetch events with new url (if not already triggered by changeView)
if (!this.is_loading)
fc.fullCalendar('refetchEvents');
}
else // empty search input equals reset
this.reset_quicksearch();
}
};
// reset search and get back to normal event listing
this.reset_quicksearch = function()
{
$(rcmail.gui_objects.qsearchbox).val('');
if (this._search_message)
rcmail.hide_message(this._search_message);
if (this.search_request) {
// hide bottom links of agenda view
fc.find('.fc-list-content > .fc-listappend').hide();
// restore original event sources and view mode from fullcalendar
fc.fullCalendar('option', 'listSections', settings['agenda_sections'])
.fullCalendar('option', 'listRange', settings['agenda_range']);
update_agenda_toolbar();
for (var sid in this.calendars) {
if (this.calendars[sid])
this.calendars[sid].url = this.calendars[sid].url.replace(/&q=.+/, '');
}
if (this.default_view)
fc.fullCalendar('changeView', this.default_view);
if (!this.is_loading)
fc.fullCalendar('refetchEvents');
this.search_request = this.search_query = null;
}
};
// callback if all sources have been fetched from server
this.events_loaded = function(count)
{
var addlinks, append = '';
// enhance list view when searching
if (this.search_request) {
if (!count) {
this._search_message = rcmail.display_message(rcmail.gettext('searchnoresults', 'calendar'), 'notice');
append = '<div class="message">' + rcmail.gettext('searchnoresults', 'calendar') + '</div>';
}
append += '<div class="fc-bottomlinks formlinks"></div>';
addlinks = true;
}
if (fc.fullCalendar('getView').name == 'table') {
var container = fc.find('.fc-list-content > .fc-listappend');
if (append) {
if (!container.length)
container = $('<div class="fc-listappend"></div>').appendTo(fc.find('.fc-list-content'));
container.html(append).show();
}
else if (container.length)
container.hide();
// add links to adjust search date range
if (addlinks) {
var lc = container.find('.fc-bottomlinks');
$('<a>').attr('href', '#').html(rcmail.gettext('searchearlierdates', 'calendar')).appendTo(lc).click(function(){
fc.fullCalendar('incrementDate', 0, -1, 0);
});
lc.append(" ");
$('<a>').attr('href', '#').html(rcmail.gettext('searchlaterdates', 'calendar')).appendTo(lc).click(function(){
var range = fc.fullCalendar('option', 'listRange');
if (range < 90) {
fc.fullCalendar('option', 'listRange', fc.fullCalendar('option', 'listRange') + 30).fullCalendar('render');
update_agenda_toolbar();
}
else
fc.fullCalendar('incrementDate', 0, 1, 0);
});
}
}
if (this.fisheye_date)
this.fisheye_view(this.fisheye_date);
};
// resize and reposition (center) the dialog window
this.dialog_resize = function(id, height, width)
{
var win = $(window), w = win.width(), h = win.height();
$(id).dialog('option', { height: Math.min(h-20, height+130), width: Math.min(w-20, width+50) })
.dialog('option', 'position', ['center', 'center']); // only works in a separate call (!?)
};
// adjust calendar view size
this.view_resize = function()
{
var footer = fc.fullCalendar('getView').name == 'table' ? $('#agendaoptions').outerHeight() : 0;
fc.fullCalendar('option', 'height', $('#calendar').height() - footer);
};
/*** startup code ***/
// create list of event sources AKA calendars
this.calendars = {};
var li, cal, active, event_sources = [];
for (var id in rcmail.env.calendars) {
cal = rcmail.env.calendars[id];
this.calendars[id] = $.extend({
url: "./?_task=calendar&_action=load_events&source="+escape(id),
editable: !cal.readonly,
className: 'fc-event-cal-'+id,
id: id
}, cal);
this.calendars[id].color = settings.event_coloring % 2 ? '' : '#' + cal.color;
if ((active = cal.active || false)) {
event_sources.push(this.calendars[id]);
}
// init event handler on calendar list checkbox
if ((li = rcmail.get_folder_li(id, 'rcmlical'))) {
$('#'+li.id+' input').click(function(e){
var id = $(this).data('id');
if (me.calendars[id]) { // add or remove event source on click
var action;
if (this.checked) {
action = 'addEventSource';
me.calendars[id].active = true;
}
else {
action = 'removeEventSource';
me.calendars[id].active = false;
}
// add/remove event source
fc.fullCalendar(action, me.calendars[id]);
rcmail.http_post('calendar', { action:'subscribe', c:{ id:id, active:me.calendars[id].active?1:0 } });
}
}).data('id', id).get(0).checked = active;
$(li).click(function(e){
var id = $(this).data('id');
rcmail.select_folder(id, 'rcmlical');
rcmail.enable_command('calendar-edit', true);
rcmail.enable_command('calendar-remove', 'calendar-showurl', true);
me.selected_calendar = id;
})
.dblclick(function(){ me.calendar_edit_dialog(me.calendars[me.selected_calendar]); })
.data('id', id);
}
if (!cal.readonly && !this.selected_calendar) {
this.selected_calendar = id;
rcmail.enable_command('addevent', true);
}
}
// select default calendar
if (settings.default_calendar && this.calendars[settings.default_calendar] && !this.calendars[settings.default_calendar].readonly)
this.selected_calendar = settings.default_calendar;
var viewdate = new Date();
if (rcmail.env.date)
viewdate.setTime(fromunixtime(rcmail.env.date));
// initalize the fullCalendar plugin
var fc = $('#calendar').fullCalendar({
header: {
right: 'prev,next today',
center: 'title',
left: 'agendaDay,agendaWeek,month,table'
},
aspectRatio: 1,
date: viewdate.getDate(),
month: viewdate.getMonth(),
year: viewdate.getFullYear(),
ignoreTimezone: true, // will treat the given date strings as in local (browser's) timezone
height: $('#calendar').height(),
eventSources: event_sources,
monthNames : settings['months'],
monthNamesShort : settings['months_short'],
dayNames : settings['days'],
dayNamesShort : settings['days_short'],
firstDay : settings['first_day'],
firstHour : settings['first_hour'],
slotMinutes : 60/settings['timeslots'],
timeFormat: {
'': settings['time_format'],
agenda: settings['time_format'] + '{ - ' + settings['time_format'] + '}',
list: settings['time_format'] + '{ - ' + settings['time_format'] + '}',
table: settings['time_format'] + '{ - ' + settings['time_format'] + '}'
},
axisFormat : settings['time_format'],
columnFormat: {
month: 'ddd', // Mon
week: 'ddd ' + settings['date_short'], // Mon 9/7
day: 'dddd ' + settings['date_short'], // Monday 9/7
table: settings['date_agenda']
},
titleFormat: {
month: 'MMMM yyyy',
week: settings['dates_long'],
day: 'dddd ' + settings['date_long'],
table: settings['dates_long']
},
listPage: 1, // advance one day in agenda view
listRange: settings['agenda_range'],
listSections: settings['agenda_sections'],
tableCols: ['handle', 'date', 'time', 'title', 'location'],
defaultView: rcmail.env.view || settings['default_view'],
allDayText: rcmail.gettext('all-day', 'calendar'),
buttonText: {
prev: (bw.ie6 ? ' << ' : ' ◄ '),
next: (bw.ie6 ? ' >> ' : ' ► '),
today: settings['today'],
day: rcmail.gettext('day', 'calendar'),
week: rcmail.gettext('week', 'calendar'),
month: rcmail.gettext('month', 'calendar'),
table: rcmail.gettext('agenda', 'calendar')
},
listTexts: {
until: rcmail.gettext('until', 'calendar'),
past: rcmail.gettext('pastevents', 'calendar'),
today: rcmail.gettext('today', 'calendar'),
tomorrow: rcmail.gettext('tomorrow', 'calendar'),
thisWeek: rcmail.gettext('thisweek', 'calendar'),
nextWeek: rcmail.gettext('nextweek', 'calendar'),
thisMonth: rcmail.gettext('thismonth', 'calendar'),
nextMonth: rcmail.gettext('nextmonth', 'calendar'),
future: rcmail.gettext('futureevents', 'calendar'),
week: rcmail.gettext('weekofyear', 'calendar')
},
selectable: true,
selectHelper: false,
currentTimeIndicator: settings.time_indicator,
loading: function(isLoading) {
me.is_loading = isLoading;
this._rc_loading = rcmail.set_busy(isLoading, 'loading', this._rc_loading);
// trigger callback
if (!isLoading)
me.events_loaded($(this).fullCalendar('clientEvents').length);
},
// event rendering
eventRender: fc_event_render,
// render element indicating more (invisible) events
overflowRender: function(data, element) {
element.html(rcmail.gettext('andnmore', 'calendar').replace('$nr', data.count))
.click(function(e){ me.fisheye_view(data.date); });
},
// callback for date range selection
select: function(start, end, allDay, e, view) {
var range_select = (!allDay || start.getDate() != end.getDate())
if (dialog_check(e) && range_select)
event_edit_dialog('new', { start:start, end:end, allDay:allDay, calendar:me.selected_calendar });
if (range_select || ignore_click)
view.calendar.unselect();
},
// callback for clicks in all-day box
dayClick: function(date, allDay, e, view) {
var now = new Date().getTime();
if (now - day_clicked_ts < 400 && day_clicked == date.getTime()) { // emulate double-click on day
var enddate = new Date(); enddate.setTime(date.getTime() + DAY_MS - 60000);
return event_edit_dialog('new', { start:date, end:enddate, allDay:allDay, calendar:me.selected_calendar });
}
if (!ignore_click) {
view.calendar.gotoDate(date);
if (day_clicked && new Date(day_clicked).getMonth() != date.getMonth())
view.calendar.select(date, date, allDay);
}
day_clicked = date.getTime();
day_clicked_ts = now;
},
// callback when a specific event is clicked
eventClick: function(event) {
if (!event.temp)
event_show_dialog(event);
},
// callback when an event was dragged and finally dropped
eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc) {
if (event.end == null || event.end.getTime() < event.start.getTime()) {
event.end = new Date(event.start.getTime() + (allDay ? DAY_MS : HOUR_MS));
}
// moved to all-day section: set times to 12:00 - 13:00
if (allDay && !event.allDay) {
event.start.setHours(12);
event.start.setMinutes(0);
event.start.setSeconds(0);
event.end.setHours(13);
event.end.setMinutes(0);
event.end.setSeconds(0);
}
// moved from all-day section: set times to working hours
else if (event.allDay && !allDay) {
var newstart = event.start.getTime();
revertFunc(); // revert to get original duration
var numdays = Math.max(1, Math.round((event.end.getTime() - event.start.getTime()) / DAY_MS)) - 1;
event.start = new Date(newstart);
event.end = new Date(newstart + numdays * DAY_MS);
event.end.setHours(settings['work_end'] || 18);
event.end.setMinutes(0);
if (event.end.getTime() < event.start.getTime())
event.end = new Date(newstart + HOUR_MS);
}
// send move request to server
var data = {
id: event.id,
calendar: event.calendar,
start: date2servertime(event.start),
end: date2servertime(event.end),
allday: allDay?1:0
};
update_event_confirm('move', event, data);
},
// callback for event resizing
eventResize: function(event, delta) {
// sanitize event dates
if (event.allDay)
event.start.setHours(12);
if (!event.end || event.end.getTime() < event.start.getTime())
event.end = new Date(event.start.getTime() + HOUR_MS);
// send resize request to server
var data = {
id: event.id,
calendar: event.calendar,
start: date2servertime(event.start),
end: date2servertime(event.end)
};
update_event_confirm('resize', event, data);
},
viewDisplay: function(view) {
$('#agendaoptions')[view.name == 'table' ? 'show' : 'hide']();
if (minical) {
window.setTimeout(function(){ minical.datepicker('setDate', fc.fullCalendar('getDate')); }, exec_deferred);
if (view.name != current_view)
me.view_resize();
current_view = view.name;
}
},
viewRender: function(view) {
if (fc && view.name == 'month')
fc.fullCalendar('option', 'maxHeight', Math.floor((view.element.parent().height()-18) / 6) - 35);
}
});
// format time string
var formattime = function(hour, minutes, start) {
var time, diff, unit, duration = '', d = new Date();
d.setHours(hour);
d.setMinutes(minutes);
time = $.fullCalendar.formatDate(d, settings['time_format']);
if (start) {
diff = Math.floor((d.getTime() - start.getTime()) / 60000);
if (diff > 0) {
unit = 'm';
if (diff >= 60) {
unit = 'h';
diff = Math.round(diff / 3) / 20;
}
duration = ' (' + diff + unit + ')';
}
}
return [time, duration];
};
var autocomplete_times = function(p, callback) {
/* Time completions */
var result = [];
var now = new Date();
var st, start = (String(this.element.attr('id')).indexOf('endtime') > 0
&& (st = $('#edit-starttime').val())
&& $('#edit-startdate').val() == $('#edit-enddate').val())
? parse_datetime(st, '') : null;
var full = p.term - 1 > 0 || p.term.length > 1;
var hours = start ? start.getHours() :
(full ? parse_datetime(p.term, '') : now).getHours();
var step = 15;
var minutes = hours * 60 + (full ? 0 : now.getMinutes());
var min = Math.ceil(minutes / step) * step % 60;
var hour = Math.floor(Math.ceil(minutes / step) * step / 60);
// list hours from 0:00 till now
for (var h = start ? start.getHours() : 0; h < hours; h++)
result.push(formattime(h, 0, start));
// list 15min steps for the next two hours
for (; h < hour + 2 && h < 24; h++) {
while (min < 60) {
result.push(formattime(h, min, start));
min += step;
}
min = 0;
}
// list the remaining hours till 23:00
while (h < 24)
result.push(formattime((h++), 0, start));
return callback(result);
};
var autocomplete_open = function(event, ui) {
// scroll to current time
var $this = $(this);
var widget = $this.autocomplete('widget');
var menu = $this.data('autocomplete').menu;
var amregex = /^(.+)(a[.m]*)/i;
var pmregex = /^(.+)(a[.m]*)/i;
var val = $(this).val().replace(amregex, '0:$1').replace(pmregex, '1:$1');
var li, html;
widget.css('width', '10em');
widget.children().each(function(){
li = $(this);
html = li.children().first().html().replace(/\s+\(.+\)$/, '').replace(amregex, '0:$1').replace(pmregex, '1:$1');
if (html.indexOf(val) == 0)
menu._scrollIntoView(li);
});
};
// if start date is changed, shift end date according to initial duration
var shift_enddate = function(dateText) {
var newstart = parse_datetime('0', dateText);
var newend = new Date(newstart.getTime() + $('#edit-startdate').data('duration') * 1000);
$('#edit-enddate').val($.fullCalendar.formatDate(newend, me.settings['date_format']));
event_times_changed();
};
// Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
// Uses the default $.datepicker.iso8601Week() function but takes firstDay setting into account.
// This is a temporary fix until http://bugs.jqueryui.com/ticket/8420 is resolved.
var iso8601Week = datepicker_settings.calculateWeek = function(date) {
var mondayOffset = Math.abs(1 - datepicker_settings.firstDay);
return $.datepicker.iso8601Week(new Date(date.getTime() + mondayOffset * 86400000));
};
var minical;
var init_calendar_ui = function()
{
// initialize small calendar widget using jQuery UI datepicker
minical = $('#datepicker').datepicker($.extend(datepicker_settings, {
inline: true,
showWeek: true,
changeMonth: false, // maybe enable?
changeYear: false, // maybe enable?
onSelect: function(dateText, inst) {
ignore_click = true;
var d = minical.datepicker('getDate'); //parse_datetime('0:0', dateText);
fc.fullCalendar('gotoDate', d).fullCalendar('select', d, d, true);
},
onChangeMonthYear: function(year, month, inst) {
minical.data('year', year).data('month', month);
},
beforeShowDay: function(date) {
var view = fc.fullCalendar('getView');
var active = view.visStart && date.getTime() >= view.visStart.getTime() && date.getTime() < view.visEnd.getTime();
return [ true, (active ? 'ui-datepicker-activerange ui-datepicker-active-' + view.name : ''), ''];
}
})) // set event handler for clicks on calendar week cell of the datepicker widget
.click(function(e) {
var cell = $(e.target);
if (e.target.tagName == 'TD' && cell.hasClass('ui-datepicker-week-col')) {
var base_date = minical.datepicker('getDate');
if (minical.data('month'))
base_date.setMonth(minical.data('month')-1);
if (minical.data('year'))
base_date.setYear(minical.data('year'));
base_date.setHours(12);
base_date.setDate(base_date.getDate() - ((base_date.getDay() + 6) % 7) + datepicker_settings.firstDay);
var day_off = base_date.getDay() - datepicker_settings.firstDay;
var base_kw = iso8601Week(base_date);
var target_kw = parseInt(cell.html());
var diff = (target_kw - base_kw) * 7 * DAY_MS;
// select monday of the chosen calendar week
var date = new Date(base_date.getTime() - day_off * DAY_MS + diff);
fc.fullCalendar('gotoDate', date).fullCalendar('setDate', date).fullCalendar('changeView', 'agendaWeek');
minical.datepicker('setDate', date);
}
});
// init event dialog
$('#eventtabs').tabs({
show: function(event, ui) {
if (ui.panel.id == 'event-tab-3') {
$('#edit-attendee-name').select();
// update free-busy status if needed
if (freebusy_ui.needsupdate && me.selected_event)
update_freebusy_status(me.selected_event);
// add current user as organizer if non added yet
if (!event_attendees.length) {
add_attendee($.extend({ role:'ORGANIZER' }, settings.identity));
$('#edit-attendees-form .attendees-invitebox').show();
}
}
}
});
$('#edit-enddate').datepicker(datepicker_settings);
$('#edit-startdate').datepicker(datepicker_settings).datepicker('option', 'onSelect', shift_enddate).change(function(){ shift_enddate(this.value); });
$('#edit-enddate').datepicker('option', 'onSelect', event_times_changed).change(event_times_changed);
$('#edit-allday').click(function(){ $('#edit-starttime, #edit-endtime')[(this.checked?'hide':'show')](); event_times_changed(); });
// configure drop-down menu on time input fields based on jquery UI autocomplete
$('#edit-starttime, #edit-endtime, #eventedit input.edit-alarm-time')
.attr('autocomplete', "off")
.autocomplete({
delay: 100,
minLength: 1,
source: autocomplete_times,
open: autocomplete_open,
change: event_times_changed,
select: function(event, ui) {
$(this).val(ui.item[0]);
return false;
}
})
.click(function() { // show drop-down upon clicks
$(this).autocomplete('search', $(this).val() ? $(this).val().replace(/\D.*/, "") : " ");
}).each(function(){
$(this).data('autocomplete')._renderItem = function(ul, item) {
return $('<li>')
.data('item.autocomplete', item)
.append('<a>' + item[0] + item[1] + '</a>')
.appendTo(ul);
};
});
// register events on alarm fields
init_alarms_edit('#eventedit');
// toggle recurrence frequency forms
$('#edit-recurrence-frequency').change(function(e){
var freq = $(this).val().toLowerCase();
$('.recurrence-form').hide();
if (freq)
$('#recurrence-form-'+freq+', #recurrence-form-until').show();
});
$('#edit-recurrence-enddate').datepicker(datepicker_settings).click(function(){ $("#edit-recurrence-repeat-until").prop('checked', true) });
$('#edit-recurrence-repeat-times').change(function(e){ $('#edit-recurrence-repeat-count').prop('checked', true); });
// init attendees autocompletion
var ac_props;
// parallel autocompletion
if (rcmail.env.autocomplete_threads > 0) {
ac_props = {
threads: rcmail.env.autocomplete_threads,
sources: rcmail.env.autocomplete_sources
};
}
rcmail.init_address_input_events($('#edit-attendee-name'), ac_props);
rcmail.addEventListener('autocomplete_insert', function(e){ $('#edit-attendee-add').click(); });
$('#edit-attendee-add').click(function(){
var input = $('#edit-attendee-name');
rcmail.ksearch_blur();
if (add_attendees(input.val())) {
input.val('');
}
});
// keep these two checkboxes in sync
$('#edit-attendees-donotify, #edit-attendees-invite').click(function(){
$('#edit-attendees-donotify, #edit-attendees-invite').prop('checked', this.checked);
});
$('#edit-attendee-schedule').click(function(){
event_freebusy_dialog();
});
$('#shedule-freebusy-prev').html(bw.ie6 ? '<<' : '◄').button().click(function(){ render_freebusy_grid(-1); });
$('#shedule-freebusy-next').html(bw.ie6 ? '>>' : '►').button().click(function(){ render_freebusy_grid(1); }).parent().buttonset();
$('#shedule-find-prev').button().click(function(){ freebusy_find_slot(-1); });
$('#shedule-find-next').button().click(function(){ freebusy_find_slot(1); });
$('#schedule-freebusy-workinghours').click(function(){
freebusy_ui.workinhoursonly = this.checked;
$('#workinghourscss').remove();
if (this.checked)
$('<style type="text/css" id="workinghourscss"> td.offhours { opacity:0.3; filter:alpha(opacity=30) } </style>').appendTo('head');
});
$('#event-rsvp input.button').click(function(){
event_rsvp($(this).attr('rel'))
});
$('#agenda-listrange').change(function(e){
settings['agenda_range'] = parseInt($(this).val());
fc.fullCalendar('option', 'listRange', settings['agenda_range']).fullCalendar('render');
// TODO: save new settings in prefs
}).val(settings['agenda_range']);
$('#agenda-listsections').change(function(e){
settings['agenda_sections'] = $(this).val();
fc.fullCalendar('option', 'listSections', settings['agenda_sections']).fullCalendar('render');
// TODO: save new settings in prefs
}).val(fc.fullCalendar('option', 'listSections'));
// hide event dialog when clicking somewhere into document
$(document).bind('mousedown', dialog_check);
rcmail.set_busy(false, 'loading', ui_loading);
}
// initialize more UI elements (deferred)
window.setTimeout(init_calendar_ui, exec_deferred);
// add proprietary css styles if not IE
if (!bw.ie)
$('div.fc-content').addClass('rcube-fc-content');
// IE supresses 2nd click event when double-clicking
if (bw.ie && bw.vendver < 9) {
$('div.fc-content').bind('dblclick', function(e){
if (!$(this).hasClass('fc-widget-header') && fc.fullCalendar('getView').name != 'table') {
var date = fc.fullCalendar('getDate');
var enddate = new Date(); enddate.setTime(date.getTime() + DAY_MS - 60000);
event_edit_dialog('new', { start:date, end:enddate, allDay:true, calendar:me.selected_calendar });
}
});
}
} // end rcube_calendar class
/* calendar plugin initialization */
window.rcmail && rcmail.addEventListener('init', function(evt) {
// configure toolbar buttons
rcmail.register_command('addevent', function(){ cal.add_event(); }, true);
rcmail.register_command('print', function(){ cal.print_calendars(); }, true);
// configure list operations
rcmail.register_command('calendar-create', function(){ cal.calendar_edit_dialog(null); }, true);
rcmail.register_command('calendar-edit', function(){ cal.calendar_edit_dialog(cal.calendars[cal.selected_calendar]); }, false);
rcmail.register_command('calendar-remove', function(){ cal.calendar_remove(cal.calendars[cal.selected_calendar]); }, false);
rcmail.register_command('events-import', function(){ cal.import_events(cal.calendars[cal.selected_calendar]); }, true);
rcmail.register_command('calendar-showurl', function(){ cal.showurl(cal.calendars[cal.selected_calendar]); }, false);
// search and export events
rcmail.register_command('export', function(){ rcmail.goto_url('export_events', { source:cal.selected_calendar }); }, true);
rcmail.register_command('search', function(){ cal.quicksearch(); }, true);
rcmail.register_command('reset-search', function(){ cal.reset_quicksearch(); }, true);
// register callback commands
rcmail.addEventListener('plugin.destroy_source', function(p){ cal.calendar_destroy_source(p.id); });
rcmail.addEventListener('plugin.unlock_saving', function(p){ cal.unlock_saving(); });
rcmail.addEventListener('plugin.refresh_calendar', function(p){ cal.refresh(p); });
rcmail.addEventListener('plugin.import_success', function(p){ cal.import_success(p); });
rcmail.addEventListener('plugin.import_error', function(p){ cal.import_error(p); });
rcmail.addEventListener('requestrefresh', function(q){ return cal.before_refresh(q); });
// let's go
var cal = new rcube_calendar_ui($.extend(rcmail.env.calendar_settings, rcmail.env.libcal_settings));
$(window).resize(function(e) {
// check target due to bugs in jquery
// http://bugs.jqueryui.com/ticket/7514
// http://bugs.jquery.com/ticket/9841
if (e.target == window) {
cal.view_resize();
}
}).resize();
// show calendars list when ready
$('#calendars').css('visibility', 'inherit');
// show toolbar
$('#toolbar').show();
});
| stephdl/roundcubemail_plugins | root/usr/share/roundcubemail/plugins/calendar/calendar_ui.js | JavaScript | gpl-2.0 | 114,423 |
<?php
/**
* @package sauto
* @subpackage Views
* @author Dacian Strain {@link http://shop.elbase.eu}
* @author Created on 17-Nov-2013
* @license GNU/GPL
*/
//-- No direct access
defined('_JEXEC') || die('=;)');
$time = time();
$app =& JFactory::getApplication();
$db = JFactory::getDbo();
$request_v =& JRequest::getVar( 'request', '', 'post', 'string' );
$app->setUserState('request', $request_v);
$titlu_anunt =& JRequest::getVar( 'titlu_anunt', '', 'post', 'string' );
$app->setUserState('titlu_anunt', $titlu_anunt);
$marca =& JRequest::getVar( 'marca', '', 'post', 'string' );
$model_auto =& JRequest::getVar( 'model_auto', '', 'post', 'string' );
$app->setUserState('model_auto', $model_auto);
$an_fabricatie =& JRequest::getVar( 'an_fabricatie', '', 'post', 'string' );
$app->setUserState('an_fabricatie', $an_fabricatie);
$cilindree =& JRequest::getVar( 'cilindree', '', 'post', 'string' );
$app->setUserState('cilindree', $cilindree);
$carburant =& JRequest::getVar( 'carburant', '', 'post', 'string' );
$app->setUserState('carburant', $carburant);
$caroserie =& JRequest::getVar( 'caroserie', '', 'post', 'string' );
$app->setUserState('caroserie', $caroserie);
$serie_caroserie =& JRequest::getVar( 'serie_caroserie', '', 'post', 'string' );
$app->setUserState('serie_caroserie', $serie_caroserie);
$anunt =& JRequest::getVar( 'anunt8', '', 'post', 'string', JREQUEST_ALLOWHTML );
$app->setUserState('anunt', $anunt);
$judet =& JRequest::getVar( 'judet', '', 'post', 'string' );
$city =& JRequest::getVar( 'localitate', '', 'post', 'string' );
$query = "SELECT `id` FROM #__sa_judete WHERE `judet` = '".$judet."'";
$db->setQuery($query);
$id_judet = $db->loadResult();
$transmisie =& JRequest::getVar( 'transmisie', '', 'post', 'string' );
$app->setUserState('transmisie', $transmisie);
$user =& JFactory::getUser();
$uid = $user->id;
$register_anunt = 0;
//echo '>>>>> marca '.$marca.' >>>> '.$new_marca.' >>>>> '.$model_auto.' >>>>> '.$new_model.'<br />';
$link_redirect = JRoute::_('index.php?option=com_sauto&view=add_request');
if ($marca == '') {
//nu am selectat marca
$app->redirect($link_redirect, JText::_('SAUTO_NO_MARCA_ADDED'));
} else {
//marca existenta, obtinem id-ul
$query = "SELECT `id` FROM #__sa_marca_auto WHERE `marca_auto` = '".$marca."'";
$db->setQuery($query);
$mid = $db->loadResult();
$marca_auto_id = $mid;
$app->setUserState('marca', $mid);
//echo '<br />>>>>>'.$marca_auto_id.'<br />';
$model_auto_id = $model_auto;
$app->setUserState('model_auto', $model_auto);
}
//echo '<br />>>>>>'.$model_auto_id.'<br />';
//verificam campurile introduse
if ($titlu_anunt == '') {
//nu avem introdus titlul
//SautoViewAdding::deleteModels($marca_noua_id, $model_nou_id);
$app->redirect($link_redirect, JText::_('SAUTO_NO_TITLE_ADDED'));
} else {
if ($an_fabricatie == '') {
//nu avem introdus anul fabricatiei
//SautoViewAdding::deleteModels($marca_noua_id, $model_nou_id);
$app->redirect($link_redirect, JText::_('SAUTO_NO_PRODUCTION_YEAR_ADDED'));
} else {
if ($cilindree == '') {
//cilindreea nu este introdusa
//SautoViewAdding::deleteModels($marca_noua_id, $model_nou_id);
$app->redirect($link_redirect, JText::_('SAUTO_NO_CAPACITY_ADDED'));
} else {
if ($carburant == '') {
//carburantul nu este ales
//SautoViewAdding::deleteModels($marca_noua_id, $model_nou_id);
$app->redirect($link_redirect, JText::_('SAUTO_NO_CARBURANT_ADDED'));
} else {
if ($caroserie == '') {
//nu este aleasa caroseria
//SautoViewAdding::deleteModels($marca_noua_id, $model_nou_id);
$app->redirect($link_redirect, JText::_('SAUTO_NO_CARSERIE_ADDED'));
} else {
if ($serie_caroserie == '') {
//seria caroseriei nu este introdusa
//SautoViewAdding::deleteModels($marca_noua_id, $model_nou_id);
$app->redirect($link_redirect, JText::_('SAUTO_NO_SERIE_CARSERIE_ADDED'));
} else {
if ($anunt == '') {
//nu este adaugat anuntul
//SautoViewAdding::deleteModels($marca_noua_id, $model_nou_id);
$app->redirect($link_redirect, JText::_('SAUTO_NO_ANUNT_ADDED'));
} else {
//e ok
$register_anunt = 1;
}
}
}
}
}
}
}
//sfarsit verificare
if ($register_anunt == 1) {
//obtin data curenta
$curentDate = date('Y-m-d H:i:s', $time);
$expiryDate = date('Y-m-d H:i:s', ($time+2592000));
//echo '<br />caroserie>>>>'.$caroserie.'<br />';
//adaug in baza de date
$query = "INSERT INTO #__sa_anunturi
(`titlu_anunt`, `anunt`, `tip_anunt`, `marca_auto`, `model_auto`, `an_fabricatie`,
`cilindree`, `carburant`, `caroserie`, `serie_caroserie`, `proprietar`, `data_adaugarii`,
`status_anunt`, `raportat`, `data_expirarii`, `judet`, `city`, `transmisie`)
VALUES
('".$titlu_anunt."', '".$anunt."', '8', '".$marca_auto_id."', '".$model_auto_id."', '".$an_fabricatie."',
'".$cilindree."', '".$carburant."','".$caroserie."', '".$serie_caroserie."', '".$uid."', '".$curentDate."',
'1', '0', '".$expiryDate."', '".$id_judet."', '".$city."', '".$transmisie."')";
$db->setQuery($query);
$db->query();
$anunt_id = $db->insertid();
###########################prelucrare imagine#############
SautoViewAdding::uploadImg($time, $uid, $anunt_id);
SautoViewAdding::sendMail($anunt_id);
###########################end prelucrare imagine################## $app->setUserState('titlu_anunt', '');
//parcam masina daca este cazul....
$parcheaza =& JRequest::getVar( 'parcheaza', '', 'post', 'string' );
if ($parcheaza == 1) {
$query = "INSERT INTO #__sa_garaj
(`owner`, `marca`, `model`, `an_fabricatie`, `cilindree`, `carburant`,
`caroserie`, `serie_caroserie`, `transmisie`)
VALUES
('".$uid."', '".$marca_auto_id."', '".$model_auto_id."', '".$an_fabricatie."', '".$cilindree."',
'".$carburant."', '".$caroserie."', '".$serie_caroserie."', '".$transmisie."')";
$db->setQuery($query);
$db->query();
}
//end parcare masina
$app->setUserState('an_fabricatie', '');
$app->setUserState('cilindree', '');
$app->setUserState('carburant', '');
$app->setUserState('marca', '');
$app->setUserState('caroserie', '');
$app->setUserState('serie_caroserie', '');
$app->setUserState('model_auto', '');
$app->setUserState('request', '');$app->setUserState('transmisie', '');
$app->setUserState('titlu_anunt', '');
$app->setUserState('transmisie', '');
$app->setUserState('anunt', '');
$link_redirect_fr = JRoute::_('index.php?option=com_sauto');
$app->redirect($link_redirect_fr, JText::_('SAUTO_SUCCESS_ADDED'));
}
?>
| grchis/android | components/com_sauto/views/adding/tmpl/default_8.php | PHP | gpl-2.0 | 6,604 |
#!/usr/bin/env python3
# This file is part of ipxact2systemverilog
# Copyright (C) 2013 Andreas Lindh
#
# 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.
#
# andreas.lindh (a) hiced.com
import math
import os
import sys
import xml.etree.ElementTree as ETree
import tabulate
from mdutils.mdutils import MdUtils
DEFAULT_INI = {'global': {'unusedholes': 'yes',
'onebitenum': 'no'}}
def sortRegisterAndFillHoles(regName,
fieldNameList,
bitOffsetList,
bitWidthList,
fieldDescList,
enumTypeList,
unusedHoles=True):
# sort the lists, highest offset first
fieldNameList = fieldNameList
bitOffsetList = [int(x) for x in bitOffsetList]
bitWidthList = [int(x) for x in bitWidthList]
fieldDescList = fieldDescList
enumTypeList = enumTypeList
matrix = list(zip(bitOffsetList, fieldNameList, bitWidthList, fieldDescList, enumTypeList))
matrix.sort(key=lambda x: x[0]) # , reverse=True)
bitOffsetList, fieldNameList, bitWidthList, fieldDescList, enumTypeList = list(zip(*matrix))
# zip return tuples not lists
fieldNameList = list(fieldNameList)
bitOffsetList = list([int(x) for x in bitOffsetList])
bitWidthList = list([int(x) for x in bitWidthList])
fieldDescList = list(fieldDescList)
enumTypeList = list(enumTypeList)
if unusedHoles:
unUsedCnt = 0
nextFieldStartingPos = 0
# fill up the holes
index = 0
register_width = bitOffsetList[-1] + bitWidthList[-1]
while register_width > nextFieldStartingPos:
if nextFieldStartingPos != bitOffsetList[index]:
newBitWidth = bitOffsetList[index] - nextFieldStartingPos
bitOffsetList.insert(index, nextFieldStartingPos)
fieldNameList.insert(index, 'unused' + str(unUsedCnt))
bitWidthList.insert(index, newBitWidth)
fieldDescList.insert(index, 'unused')
enumTypeList.insert(index, '')
unUsedCnt += 1
nextFieldStartingPos = int(bitOffsetList[index]) + int(bitWidthList[index])
index += 1
return regName, fieldNameList, bitOffsetList, bitWidthList, fieldDescList, enumTypeList
class documentClass():
def __init__(self, name):
self.name = name
self.memoryMapList = []
def addMemoryMap(self, memoryMap):
self.memoryMapList.append(memoryMap)
class memoryMapClass():
def __init__(self, name):
self.name = name
self.addressBlockList = []
def addAddressBlock(self, addressBlock):
self.addressBlockList.append(addressBlock)
class addressBlockClass():
def __init__(self, name, addrWidth, dataWidth):
self.name = name
self.addrWidth = addrWidth
self.dataWidth = dataWidth
self.registerList = []
self.suffix = ""
def addRegister(self, reg):
assert isinstance(reg, registerClass)
self.registerList.append(reg)
def setRegisterList(self, registerList):
self.registerList = registerList
def returnAsString(self):
raise NotImplementedError("method returnAsString() is virutal and must be overridden.")
class registerClass():
def __init__(self, name, address, resetValue, size, access, desc, fieldNameList,
bitOffsetList, bitWidthList, fieldDescList, enumTypeList):
assert isinstance(enumTypeList, list), 'enumTypeList is not a list'
self.name = name
self.address = address
self.resetValue = resetValue
self.size = size
self.access = access
self.desc = desc
self.fieldNameList = fieldNameList
self.bitOffsetList = bitOffsetList
self.bitWidthList = bitWidthList
self.fieldDescList = fieldDescList
self.enumTypeList = enumTypeList
class enumTypeClassRegistry():
""" should perhaps be a singleton instead """
def __init__(self):
self.listOfEnums = []
def enumAllReadyExist(self, enum):
for e in self.listOfEnums:
if e.compare(enum):
enum.allReadyExist = True
enum.enumName = e.name
break
self.listOfEnums.append(enum)
return enum
class enumTypeClass():
def __init__(self, name, bitWidth, keyList, valueList, descrList):
self.name = name
self.bitWidth = bitWidth
matrix = list(zip(valueList, keyList, descrList))
matrix.sort(key=lambda x: x[0])
valueList, keyList, descrList = list(zip(*matrix))
self.keyList = list(keyList)
self.valueList = list(valueList)
self.allReadyExist = False
self.enumName = None
self.descrList = descrList
def compare(self, other):
result = True
result = self.bitWidth == other.bitWidth and result
result = self.compareLists(self.keyList, other.keyList) and result
return result
def compareLists(self, list1, list2):
for val in list1:
if val in list2:
return True
return False
class rstAddressBlock(addressBlockClass):
"""Generates a ReStructuredText file from a IP-XACT register description"""
def __init__(self, name, addrWidth, dataWidth):
self.name = name
self.addrWidth = addrWidth
self.dataWidth = dataWidth
self.registerList = []
self.suffix = ".rst"
def returnEnumValueString(self, enumTypeObj):
if isinstance(enumTypeObj, enumTypeClass):
l = []
for i in range(len(enumTypeObj.keyList)):
l.append(enumTypeObj.keyList[i] + '=' + enumTypeObj.valueList[i])
s = ", ".join(l)
else:
s = ''
return s
def returnAsString(self):
r = ""
regNameList = [reg.name for reg in self.registerList]
regAddressList = [reg.address for reg in self.registerList]
regDescrList = [reg.desc for reg in self.registerList]
r += self.returnRstTitle()
r += self.returnRstSubTitle()
summary_table = []
for i in range(len(regNameList)):
summary_table.append(["%#04x" % regAddressList[i], str(regNameList[i]) + "_", str(regDescrList[i])])
r += tabulate.tabulate(summary_table,
headers=['Address', 'Register Name', 'Description'],
tablefmt="grid")
r += "\n"
r += "\n"
for reg in self.registerList:
r += self.returnRstRegDesc(reg.name, reg.address, reg.size, reg.resetValue, reg.desc, reg.access)
reg_table = []
for fieldIndex in reversed(list(range(len(reg.fieldNameList)))):
bits = "[" + str(reg.bitOffsetList[fieldIndex] + reg.bitWidthList[fieldIndex] - 1) + \
":" + str(reg.bitOffsetList[fieldIndex]) + "]"
_line = [bits,
reg.fieldNameList[fieldIndex]]
if reg.resetValue:
temp = (int(reg.resetValue, 0) >> reg.bitOffsetList[fieldIndex])
mask = (2 ** reg.bitWidthList[fieldIndex]) - 1
temp &= mask
temp = "{value:#0{width}x}".format(value=temp,
width=math.ceil(reg.bitWidthList[fieldIndex] / 4) + 2)
_line.append(temp)
_line.append(reg.fieldDescList[fieldIndex])
reg_table.append(_line)
_headers = ['Bits', 'Field name']
if reg.resetValue:
_headers.append('Reset')
_headers.append('Description')
r += tabulate.tabulate(reg_table,
headers=_headers,
tablefmt="grid")
r += "\n"
r += "\n"
# enumerations
for enum in reg.enumTypeList:
if enum:
# header
r += enum.name + "\n"
r += ',' * len(enum.name) + "\n"
r += "\n"
# table
enum_table = []
for i in range(len(enum.keyList)):
_value = "{value:#0{width}x}".format(value=int(enum.valueList[i], 0),
width=math.ceil(int(enum.bitWidth, 0) / 4) + 2)
_line = [enum.keyList[i],
_value,
enum.descrList[i]]
enum_table.append(_line)
r += tabulate.tabulate(enum_table,
headers=['Name', 'Value', 'Description'],
tablefmt="grid")
r += "\n\n"
return r
def returnRstTitle(self):
r = ''
r += "====================\n"
r += "Register description\n"
r += "====================\n\n"
return r
def returnRstSubTitle(self):
r = ''
r += "Registers\n"
r += "---------\n\n"
return r
def returnRstRegDesc(self, name, address, size, resetValue, desc, access):
r = ""
r += name + "\n"
r += len(name) * '-' + "\n"
r += "\n"
r += ":Name: " + str(name) + "\n"
r += ":Address: " + hex(address) + "\n"
if resetValue:
# display the resetvalue in hex notation in the full length of the register
r += ":Reset Value: {value:#0{size:d}x}\n".format(value=int(resetValue, 0), size=size // 4 + 2)
r += ":Access: " + access + "\n"
r += ":Description: " + desc + "\n"
r += "\n"
return r
class mdAddressBlock(addressBlockClass):
"""Generates a Markdown file from a IP-XACT register description"""
def __init__(self, name, addrWidth, dataWidth):
self.name = name
self.addrWidth = addrWidth
self.dataWidth = dataWidth
self.registerList = []
self.suffix = ".md"
self.mdFile = MdUtils(file_name="none",
title="")
def returnEnumValueString(self, enumTypeObj):
if isinstance(enumTypeObj, enumTypeClass):
l = []
for i in range(len(enumTypeObj.keyList)):
l.append(enumTypeObj.keyList[i] + '=' + enumTypeObj.valueList[i])
s = ", ".join(l)
else:
s = ''
return s
def returnAsString(self):
regNameList = [reg.name for reg in self.registerList]
regAddressList = [reg.address for reg in self.registerList]
regDescrList = [reg.desc for reg in self.registerList]
self.mdFile.new_header(level=1, title="Register description")
self.mdFile.new_header(level=2, title="Registers")
# summary
header = ['Address', 'Register Name', 'Description']
rows = []
for i in range(len(regNameList)):
rows.extend(["{:#04x}".format(regAddressList[i]),
f"[{regNameList[i]}](#{regNameList[i]})",
str(regDescrList[i])])
self.mdFile.new_table(columns=len(header),
rows=len(regNameList) + 1, # header + data
text=header + rows,
text_align='left')
# all registers
for reg in self.registerList:
headers = ['Bits', 'Field name']
if reg.resetValue:
headers.append('Reset')
headers.append('Description')
self.returnMdRegDesc(reg.name, reg.address, reg.size, reg.resetValue, reg.desc, reg.access)
reg_table = []
for fieldIndex in reversed(list(range(len(reg.fieldNameList)))):
bits = "[" + str(reg.bitOffsetList[fieldIndex] + reg.bitWidthList[fieldIndex] - 1) + \
":" + str(reg.bitOffsetList[fieldIndex]) + "]"
reg_table.append(bits)
reg_table.append(reg.fieldNameList[fieldIndex])
if reg.resetValue:
temp = (int(reg.resetValue, 0) >> reg.bitOffsetList[fieldIndex])
mask = (2 ** reg.bitWidthList[fieldIndex]) - 1
temp &= mask
temp = "{value:#0{width}x}".format(value=temp,
width=math.ceil(reg.bitWidthList[fieldIndex] / 4) + 2)
reg_table.append(temp)
reg_table.append(reg.fieldDescList[fieldIndex])
self.mdFile.new_table(columns=len(headers),
rows=len(reg.fieldNameList) + 1,
text=headers + reg_table,
text_align='left')
# enumerations
for enum in reg.enumTypeList:
if enum:
self.mdFile.new_header(level=4,
title=enum.name)
enum_table = []
for i in range(len(enum.keyList)):
_value = "{value:#0{width}x}".format(value=int(enum.valueList[i], 0),
width=math.ceil(int(enum.bitWidth, 0) / 4) + 2)
enum_table.append(enum.keyList[i])
enum_table.append(_value)
enum_table.append(enum.descrList[i])
headers = ['Name', 'Value', 'Description']
self.mdFile.new_table(columns=len(headers),
rows=len(enum.keyList) + 1,
text=headers + enum_table,
text_align='left')
return self.mdFile.file_data_text
def returnMdRegDesc(self, name, address, size, resetValue, desc, access):
self.mdFile.new_header(level=3, title=name)
self.mdFile.new_line("**Name** " + str(name))
self.mdFile.new_line("**Address** " + hex(address))
if resetValue:
# display the resetvalue in hex notation in the full length of the register
self.mdFile.new_line(
"**Reset Value** {value:#0{size:d}x}".format(value=int(resetValue, 0), size=size // 4 + 2))
self.mdFile.new_line("**Access** " + access)
self.mdFile.new_line("**Description** " + desc)
class vhdlAddressBlock(addressBlockClass):
"""Generates a vhdl file from a IP-XACT register description"""
def __init__(self, name, addrWidth, dataWidth):
self.name = name
self.addrWidth = addrWidth
self.dataWidth = dataWidth
self.registerList = []
self.suffix = "_vhd_pkg.vhd"
def returnAsString(self):
r = ''
r += self.returnPkgHeaderString()
r += "\n\n"
r += self.returnPkgBodyString()
return r
def returnPkgHeaderString(self):
r = ''
r += "--\n"
r += "-- Automatically generated\n"
r += "-- with the command '%s'\n" % (' '.join(sys.argv))
r += "--\n"
r += "-- Do not manually edit!\n"
r += "--\n"
r += "-- VHDL 93\n"
r += "--\n"
r += "\n"
r += "library ieee;\n"
r += "use ieee.std_logic_1164.all;\n"
r += "use ieee.numeric_std.all;\n"
r += "\n"
r += "package " + self.name + "_vhd_pkg is\n"
r += "\n"
r += " constant addr_width : natural := " + str(self.addrWidth) + ";\n"
r += " constant data_width : natural := " + str(self.dataWidth) + ";\n"
r += "\n\n"
r += self.returnRegFieldEnumTypeStrings(True)
for reg in self.registerList:
r += " constant {name}_addr : natural := {address} ; -- {address:#0{width}x}\n".format(name=reg.name,
address=reg.address,
width=math.ceil(
self.addrWidth / 4) + 2) # +2 for the '0x'
r += "\n"
for reg in self.registerList:
if reg.resetValue:
r += " constant {name}_reset_value : std_ulogic_vector(data_width-1 downto 0) := std_ulogic_vector(to_unsigned({value:d}, data_width)); -- {value:#0{width}x}\n".format(
name=reg.name,
value=int(reg.resetValue, 0),
width=math.ceil((self.dataWidth / 4)) + 2)
r += "\n\n"
for reg in self.registerList:
r += self.returnRegRecordTypeString(reg)
r += self.returnRegistersInRecordTypeString()
r += self.returnRegistersOutRecordTypeString()
r += self.returnRegistersReadFunction()
r += self.returnRegistersWriteFunction()
r += self.returnRegistersResetFunction()
r += "end;\n"
return r
def returnRegFieldEnumTypeStrings(self, prototype):
r = ''
for reg in self.registerList:
for enum in reg.enumTypeList:
if isinstance(enum, enumTypeClass) and not enum.allReadyExist:
r += " -- {}\n".format(enum.name) # group the enums in the package
if prototype:
t = " type " + enum.name + "_enum is ("
indent = t.find('(') + 1
r += t
for ki in range(len(enum.keyList)):
if ki != 0: # no indentation for the first element
r += " " * indent
r += enum.keyList[ki]
if ki != len(enum.keyList) - 1: # no ',' for the last element
r += ","
else: # last element
r += ");"
if enum.descrList[ki]:
r += " -- " + enum.descrList[ki]
if ki != len(enum.keyList) - 1: # no new line for the last element
r += "\n"
r += "\n"
r += " function " + enum.name + \
"_enum_to_sulv(v: " + enum.name + "_enum ) return std_ulogic_vector"
if prototype:
r += ";\n"
else:
r += " is\n"
r += " variable r : std_ulogic_vector(" + str(enum.bitWidth) + "-1 downto 0);\n"
r += " begin\n"
r += " case v is\n"
for i in range(len(enum.keyList)):
r += ' when {key} => r:="{value_int:0{bitwidth}b}"; -- {value}\n'.format(
key=enum.keyList[i],
value=enum.valueList[i],
value_int=int(enum.valueList[i]),
bitwidth=int(enum.bitWidth))
r += " end case;\n"
r += " return r;\n"
r += " end function;\n\n"
r += " function sulv_to_" + enum.name + \
"_enum(v: std_ulogic_vector(" + str(enum.bitWidth) + "-1 downto 0)) return " + \
enum.name + "_enum"
if prototype:
r += ";\n"
else:
r += " is\n"
r += " variable r : " + enum.name + "_enum;\n"
r += " begin\n"
r += " case v is\n"
for i in range(len(enum.keyList)):
r += ' when "{value_int:0{bitwidth}b}" => r:={key};\n'.format(key=enum.keyList[i],
value_int=int(
enum.valueList[
i]),
bitwidth=int(
enum.bitWidth))
r += ' when others => r:=' + enum.keyList[0] + '; -- error\n'
r += " end case;\n"
r += " return r;\n"
r += " end function;\n\n"
if prototype:
r += "\n"
if prototype:
r += "\n"
return r
def returnRegRecordTypeString(self, reg):
r = ''
r += " type " + reg.name + "_record_type is record\n"
for i in reversed(list(range(len(reg.fieldNameList)))):
bits = "[" + str(reg.bitOffsetList[i] + reg.bitWidthList[i] - 1) + ":" + str(reg.bitOffsetList[i]) + "]"
bit = "[" + str(reg.bitOffsetList[i]) + "]"
if isinstance(reg.enumTypeList[i], enumTypeClass):
if not reg.enumTypeList[i].allReadyExist:
r += " " + reg.fieldNameList[i] + " : " + \
reg.enumTypeList[i].name + "_enum; -- " + bits + "\n"
else:
r += " " + reg.fieldNameList[i] + " : " + \
reg.enumTypeList[i].enumName + "_enum; -- " + bits + "\n"
else:
if reg.bitWidthList[i] == 1: # single bit
r += " " + reg.fieldNameList[i] + " : std_ulogic; -- " + bit + "\n"
else: # vector
r += " " + reg.fieldNameList[i] + " : std_ulogic_vector(" + str(reg.bitWidthList[i] - 1) + \
" downto 0); -- " + bits + "\n"
r += " end record;\n\n"
return r
def returnRegistersInRecordTypeString(self):
r = ""
r += " type " + self.name + "_in_record_type is record\n"
for reg in self.registerList:
if reg.access == "read-only":
r += " {name} : {name}_record_type; -- addr {addr:#0{width}x}\n".format(name=reg.name,
addr=reg.address,
width=math.ceil(
self.addrWidth / 4) + 2) # +2 for the '0x'
r += " end record;\n\n"
return r
def returnRegistersOutRecordTypeString(self):
r = ""
r += " type " + self.name + "_out_record_type is record\n"
for reg in self.registerList:
if reg.access != "read-only":
r += " {name} : {name}_record_type; -- addr {addr:#0{width}x}\n".format(name=reg.name,
addr=reg.address,
width=math.ceil(
self.addrWidth / 4) + 2) # +2 for the '0x'
r += " end record;\n\n"
return r
def returnRegistersReadFunction(self):
r = " function read_" + self.name + "(registers_i : " + self.name + "_in_record_type;\n"
indent = r.find('(') + 1
r += " " * indent + "registers_o : " + self.name + "_out_record_type;\n"
r += " " * indent + "address : std_ulogic_vector(addr_width-1 downto 0)\n"
r += " " * indent + ") return std_ulogic_vector;\n\n"
return r
def returnRegistersWriteFunction(self):
r = " function write_" + self.name + "(value : std_ulogic_vector(data_width-1 downto 0);\n"
indent = r.find('(') + 1
r += " " * indent + "address : std_ulogic_vector(addr_width-1 downto 0);\n"
r += " " * indent + "registers_o : " + self.name + "_out_record_type\n"
r += " " * indent + ") return " + self.name + "_out_record_type;\n\n"
return r
def returnRegistersResetFunction(self):
r = " function reset_" + self.name + " return " + self.name + "_out_record_type;\n"
r += " function reset_" + self.name + "(address: std_ulogic_vector(addr_width-1 downto 0);\n"
indent = r.splitlines()[-1].find('(') + 1
r += " " * indent + "registers_o : " + self.name + "_out_record_type\n"
r += " " * indent + ") return " + self.name + "_out_record_type;\n\n"
return r
def returnRecToSulvFunctionString(self, reg):
r = ""
r += " function " + reg.name + \
"_record_type_to_sulv(v : " + reg.name + "_record_type) return std_ulogic_vector is\n"
r += " variable r : std_ulogic_vector(data_width-1 downto 0);\n"
r += " begin\n"
r += " r := (others => '0');\n"
for i in reversed(list(range(len(reg.fieldNameList)))):
bits = str(reg.bitOffsetList[i] + reg.bitWidthList[i] - 1) + " downto " + str(reg.bitOffsetList[i])
bit = str(reg.bitOffsetList[i])
if isinstance(reg.enumTypeList[i], enumTypeClass):
if not reg.enumTypeList[i].allReadyExist:
r += " r(" + bits + ") := " + \
reg.enumTypeList[i].name + "_enum_to_sulv(v." + reg.fieldNameList[i] + ");\n"
else:
r += " r(" + bits + ") := " + \
reg.enumTypeList[i].enumName + "_enum_to_sulv(v." + reg.fieldNameList[i] + ");\n"
else:
if reg.bitWidthList[i] == 1: # single bit
r += " r(" + bit + ") := v." + reg.fieldNameList[i] + ";\n"
else: # vector
r += " r(" + bits + ") := v." + reg.fieldNameList[i] + ";\n"
r += " return r;\n"
r += " end function;\n\n"
return r
def returnSulvToRecFunctionString(self, reg):
r = ""
r += " function sulv_to_" + reg.name + \
"_record_type(v : std_ulogic_vector) return " + reg.name + "_record_type is\n"
r += " variable r : " + reg.name + "_record_type;\n"
r += " begin\n"
for i in reversed(list(range(len(reg.fieldNameList)))):
bits = str(reg.bitOffsetList[i] + reg.bitWidthList[i] - 1) + " downto " + str(reg.bitOffsetList[i])
bit = str(reg.bitOffsetList[i])
if isinstance(reg.enumTypeList[i], enumTypeClass):
if not reg.enumTypeList[i].allReadyExist:
r += " r." + reg.fieldNameList[i] + " := sulv_to_" + \
reg.enumTypeList[i].name + "_enum(v(" + bits + "));\n"
else:
r += " r." + reg.fieldNameList[i] + " := sulv_to_" + \
reg.enumTypeList[i].enumName + "_enum(v(" + bits + "));\n"
else:
if reg.bitWidthList[i] == 1: # single bit
r += " r." + reg.fieldNameList[i] + " := v(" + bit + ");\n"
else:
r += " r." + reg.fieldNameList[i] + " := v(" + bits + ");\n"
r += " return r;\n"
r += " end function;\n\n"
return r
def returnReadFunctionString(self):
r = ""
t = " function read_" + self.name + "(registers_i : " + self.name + "_in_record_type;\n"
indent = t.find('(') + 1
r += t
r += " " * indent + "registers_o : " + self.name + "_out_record_type;\n"
r += " " * indent + "address : std_ulogic_vector(addr_width-1 downto 0)\n"
r += " " * indent + ") return std_ulogic_vector is\n"
r += " variable r : std_ulogic_vector(data_width-1 downto 0);\n"
r += " begin\n"
r += " case to_integer(unsigned(address)) is\n"
for reg in self.registerList:
if reg.access == "read-only":
r += " when " + reg.name + "_addr => r:= " + reg.name + \
"_record_type_to_sulv(registers_i." + reg.name + ");\n"
else:
r += " when " + reg.name + "_addr => r:= " + reg.name + \
"_record_type_to_sulv(registers_o." + reg.name + ");\n"
r += " when others => r := (others => '0');\n"
r += " end case;\n"
r += " return r;\n"
r += " end function;\n\n"
return r
def returnWriteFunctionString(self):
r = ""
t = " function write_" + self.name + "(value : std_ulogic_vector(data_width-1 downto 0);\n"
r += t
indent = t.find('(') + 1
r += " " * indent + "address : std_ulogic_vector(addr_width-1 downto 0);\n"
r += " " * indent + "registers_o : " + self.name + "_out_record_type\n"
r += " " * indent + ") return " + self.name + "_out_record_type is\n"
r += " variable r : " + self.name + "_out_record_type;\n"
r += " begin\n"
r += " r := registers_o;\n"
r += " case to_integer(unsigned(address)) is\n"
for reg in self.registerList:
if reg.access != "read-only":
r += " when " + reg.name + "_addr => r." + reg.name + \
" := sulv_to_" + reg.name + "_record_type(value);\n"
r += " when others => null;\n"
r += " end case;\n"
r += " return r;\n"
r += " end function;\n\n"
return r
def returnResetFunctionString(self):
r = ""
r += " function reset_" + self.name + " return " + self.name + "_out_record_type is\n"
r += " variable r : " + self.name + "_out_record_type;\n"
r += " begin\n"
for reg in self.registerList:
if reg.resetValue:
if reg.access != "read-only":
r += " r." + reg.name + " := sulv_to_" + \
reg.name + "_record_type(" + reg.name + "_reset_value);\n"
r += " return r;\n"
r += " end function;\n"
r += "\n"
r += " function reset_" + self.name + "(address: std_ulogic_vector(addr_width-1 downto 0);\n"
indent = r.splitlines()[-1].find('(') + 1
r += " " * indent + "registers_o : " + self.name + "_out_record_type\n"
r += " " * indent + ") return " + self.name + "_out_record_type is\n"
r += " variable r : " + self.name + "_out_record_type;\n"
r += " begin\n"
r += " r := registers_o;\n"
r += " case to_integer(unsigned(address)) is\n"
for reg in self.registerList:
if reg.resetValue:
if reg.access != "read-only":
r += " when " + reg.name + "_addr => r." + reg.name + \
" := sulv_to_" + reg.name + "_record_type(" + reg.name + "_reset_value);\n"
r += " when others => null;\n"
r += " end case;\n"
r += " return r;\n"
r += " end function;\n\n"
return r
def returnPkgBodyString(self):
r = ""
r += "package body " + self.name + "_vhd_pkg is\n\n"
r += self.returnRegFieldEnumTypeStrings(False)
for reg in self.registerList:
r += self.returnRecToSulvFunctionString(reg)
r += self.returnSulvToRecFunctionString(reg)
r += self.returnReadFunctionString()
r += self.returnWriteFunctionString()
r += self.returnResetFunctionString()
r += "end package body;\n"
return r
class systemVerilogAddressBlock(addressBlockClass):
def __init__(self, name, addrWidth, dataWidth):
self.name = name
self.addrWidth = addrWidth
self.dataWidth = dataWidth
self.registerList = []
self.suffix = "_sv_pkg.sv"
def returnIncludeString(self):
r = "\n"
r += "`define " + self.name + "_addr_width " + str(self.addrWidth) + "\n"
r += "`define " + self.name + "_data_width " + str(self.dataWidth) + "\n"
return r
def returnSizeString(self):
r = "\n"
r += "const int addr_width = " + str(self.addrWidth) + ";\n"
r += "const int data_width = " + str(self.dataWidth) + ";\n"
return r
def returnAddressesString(self):
r = "\n"
for reg in self.registerList:
r += "const int " + reg.name + "_addr = " + str(reg.address) + ";\n"
r += "\n"
return r
def returnAddressListString(self):
r = "\n"
r = "//synopsys translate_off\n"
r += "const int " + self.name + "_regAddresses [" + str(len(self.registerList)) + "] = '{"
l = []
for reg in self.registerList:
l.append("\n " + reg.name + "_addr")
r += ",".join(l)
r += "};\n"
r += "\n"
r += "const string " + self.name + "_regNames [" + str(len(self.registerList)) + "] = '{"
l = []
for reg in self.registerList:
l.append('\n "' + reg.name + '"')
r += ",".join(l)
r += "};\n"
r += "const reg " + self.name + "_regUnResetedAddresses [" + str(len(self.registerList)) + "] = '{"
l = []
for reg in self.registerList:
if reg.resetValue:
l.append("\n 1'b0")
else:
l.append("\n 1'b1")
r += ",".join(l)
r += "};\n"
r += "\n"
r += "//synopsys translate_on\n\n"
return r
def enumeratedType(self, prepend, fieldName, valueNames, values):
r = "\n"
members = []
# dont want to create to simple names in the global names space.
# should preppend with name from ipxact file
for index in range(len(valueNames)):
name = valueNames[index]
value = values[index]
members.append(name + "=" + value)
r += "typedef enum { " + ",".join(members) + "} enum_" + fieldName + ";\n"
return r
def returnResetValuesString(self):
r = ""
for reg in self.registerList:
if reg.resetValue:
r += "const " + reg.name + "_struct_type " + reg.name + \
"_reset_value = " + str(int(reg.resetValue, 0)) + ";\n"
r += "\n"
return r
def returnStructString(self):
r = "\n"
for reg in self.registerList:
r += "\ntypedef struct packed {\n"
for i in reversed(list(range(len(reg.fieldNameList)))):
bits = "bits [" + str(reg.bitOffsetList[i] + reg.bitWidthList[i] - 1) + \
":" + str(reg.bitOffsetList[i]) + "]"
r += " bit [" + str(reg.bitWidthList[i] - 1) + ":0] " + \
str(reg.fieldNameList[i]) + ";//" + bits + "\n"
r += "} " + reg.name + "_struct_type;\n\n"
return r
def returnRegistersStructString(self):
r = "typedef struct packed {\n"
for reg in self.registerList:
r += " " + reg.name + "_struct_type " + reg.name + ";\n"
r += "} " + self.name + "_struct_type;\n\n"
return r
def returnReadFunctionString(self):
r = "function bit [31:0] read_" + self.name + "(" + self.name + "_struct_type registers,int address);\n"
r += " bit [31:0] r;\n"
r += " case(address)\n"
for reg in self.registerList:
r += " " + reg.name + "_addr: r[$bits(registers." + reg.name + ")-1:0] = registers." + reg.name + ";\n"
r += " default: r =0;\n"
r += " endcase\n"
r += " return r;\n"
r += "endfunction\n\n"
return r
def returnWriteFunctionString(self):
t = "function " + self.name + "_struct_type write_" + self.name + "(bit [31:0] data, int address,\n"
r = t
indent = r.find('(') + 1
r += " " * indent + self.name + "_struct_type registers);\n"
r += " " + self.name + "_struct_type r;\n"
r += " r = registers;\n"
r += " case(address)\n"
for reg in self.registerList:
r += " " + reg.name + "_addr: r." + reg.name + " = data[$bits(registers." + reg.name + ")-1:0];\n"
r += " endcase // case address\n"
r += " return r;\n"
r += "endfunction\n\n"
return r
def returnResetFunctionString(self):
r = "function " + self.name + "_struct_type reset_" + self.name + "();\n"
r += " " + self.name + "_struct_type r;\n"
for reg in self.registerList:
if reg.resetValue:
r += " r." + reg.name + "=" + reg.name + "_reset_value;\n"
r += " return r;\n"
r += "endfunction\n"
r += "\n"
return r
def returnAsString(self):
r = ''
r += "// Automatically generated\n"
r += "// with the command '%s'\n" % (' '.join(sys.argv))
r += "//\n"
r += "// Do not manually edit!\n"
r += "//\n"
r += "package " + self.name + "_sv_pkg;\n\n"
r += self.returnSizeString()
r += self.returnAddressesString()
r += self.returnAddressListString()
r += self.returnStructString()
r += self.returnResetValuesString()
r += self.returnRegistersStructString()
r += self.returnReadFunctionString()
r += self.returnWriteFunctionString()
r += self.returnResetFunctionString()
r += "endpackage //" + self.name + "_sv_pkg\n"
return r
class ipxactParser():
def __init__(self, srcFile, config):
self.srcFile = srcFile
self.config = config
self.enumTypeClassRegistry = enumTypeClassRegistry()
def returnDocument(self):
spirit_ns = 'http://www.spiritconsortium.org/XMLSchema/SPIRIT/1.5'
tree = ETree.parse(self.srcFile)
ETree.register_namespace('spirit', spirit_ns)
namespace = tree.getroot().tag[1:].split("}")[0]
spiritString = '{' + spirit_ns + '}'
docName = tree.find(spiritString + "name").text
d = documentClass(docName)
memoryMaps = tree.find(spiritString + "memoryMaps")
memoryMapList = memoryMaps.findall(spiritString + "memoryMap") if memoryMaps is not None else []
for memoryMap in memoryMapList:
memoryMapName = memoryMap.find(spiritString + "name").text
addressBlockList = memoryMap.findall(spiritString + "addressBlock")
m = memoryMapClass(memoryMapName)
for addressBlock in addressBlockList:
addressBlockName = addressBlock.find(spiritString + "name").text
registerList = addressBlock.findall(spiritString + "register")
baseAddress = int(addressBlock.find(spiritString + "baseAddress").text, 0)
nbrOfAddresses = int(addressBlock.find(spiritString + "range").text, 0) # TODO, this is wrong
addrWidth = int(math.ceil((math.log(baseAddress + nbrOfAddresses, 2))))
dataWidth = int(addressBlock.find(spiritString + "width").text, 0)
a = addressBlockClass(addressBlockName, addrWidth, dataWidth)
for registerElem in registerList:
regName = registerElem.find(spiritString + "name").text
reset = registerElem.find(spiritString + "reset")
if reset is not None:
resetValue = reset.find(spiritString + "value").text
else:
resetValue = None
size = int(registerElem.find(spiritString + "size").text, 0)
access = registerElem.find(spiritString + "access").text
if registerElem.find(spiritString + "description") != None:
desc = registerElem.find(spiritString + "description").text
else:
desc = ""
regAddress = baseAddress + int(registerElem.find(spiritString + "addressOffset").text, 0)
r = self.returnRegister(spiritString, registerElem, regAddress,
resetValue, size, access, desc, dataWidth)
a.addRegister(r)
m.addAddressBlock(a)
d.addMemoryMap(m)
return d
def returnRegister(self, spiritString, registerElem, regAddress, resetValue, size, access, regDesc, dataWidth):
regName = registerElem.find(spiritString + "name").text
fieldList = registerElem.findall(spiritString + "field")
fieldNameList = [item.find(spiritString + "name").text for item in fieldList]
bitOffsetList = [item.find(spiritString + "bitOffset").text for item in fieldList]
bitWidthList = [item.find(spiritString + "bitWidth").text for item in fieldList]
fieldDescList = [item.find(spiritString + "description").text for item in fieldList]
enumTypeList = []
for index in range(len(fieldList)):
fieldElem = fieldList[index]
bitWidth = bitWidthList[index]
fieldName = fieldNameList[index]
enumeratedValuesElem = fieldElem.find(spiritString + "enumeratedValues")
if enumeratedValuesElem is not None:
enumeratedValueList = enumeratedValuesElem.findall(spiritString + "enumeratedValue")
valuesNameList = [item.find(spiritString + "name").text for item in enumeratedValueList]
descrList = [item.find(spiritString + "description").text if item.find(
spiritString + "description") is not None else "" for item in enumeratedValueList]
valuesList = [item.find(spiritString + "value").text for item in enumeratedValueList]
if len(valuesNameList) > 0:
if int(bitWidth) > 1: # if the field of a enum is longer than 1 bit, always use enums
enum = enumTypeClass(fieldName, bitWidth, valuesNameList, valuesList, descrList)
enum = self.enumTypeClassRegistry.enumAllReadyExist(enum)
enumTypeList.append(enum)
else: # bit field of 1 bit
if self.config['global'].getboolean('onebitenum'): # do create one bit enums
enum = enumTypeClass(fieldName, bitWidth, valuesNameList, valuesList, descrList)
enum = self.enumTypeClassRegistry.enumAllReadyExist(enum)
enumTypeList.append(enum)
else: # dont create enums of booleans because this only decreases readability
enumTypeList.append(None)
else:
enumTypeList.append(None)
else:
enumTypeList.append(None)
if len(fieldNameList) == 0:
fieldNameList.append(regName)
bitOffsetList.append(0)
bitWidthList.append(dataWidth)
fieldDescList.append('')
enumTypeList.append(None)
(regName, fieldNameList, bitOffsetList, bitWidthList, fieldDescList, enumTypeList) = sortRegisterAndFillHoles(
regName, fieldNameList, bitOffsetList, bitWidthList, fieldDescList, enumTypeList,
self.config['global'].getboolean('unusedholes'))
reg = registerClass(regName, regAddress, resetValue, size, access, regDesc, fieldNameList,
bitOffsetList, bitWidthList, fieldDescList, enumTypeList)
return reg
class ipxact2otherGenerator():
def __init__(self, destDir, namingScheme="addressBlockName"):
self.destDir = destDir
self.namingScheme = namingScheme
def write(self, fileName, string):
_dest = os.path.join(self.destDir, fileName)
print("writing file " + _dest)
if not os.path.exists(os.path.dirname(_dest)):
os.makedirs(os.path.dirname(_dest))
with open(_dest, "w") as f:
f.write(string)
def generate(self, generatorClass, document):
self.document = document
docName = document.name
for memoryMap in document.memoryMapList:
mapName = memoryMap.name
for addressBlock in memoryMap.addressBlockList:
blockName = addressBlock.name
block = generatorClass(addressBlock.name,
addressBlock.addrWidth,
addressBlock.dataWidth)
block.setRegisterList(addressBlock.registerList)
s = block.returnAsString()
if self.namingScheme == "addressBlockName":
fileName = blockName + block.suffix
else:
fileName = docName + '_' + mapName + '_' + blockName + block.suffix
self.write(fileName, s)
if generatorClass == systemVerilogAddressBlock:
includeFileName = fileName + "h"
includeString = block.returnIncludeString()
self.write(includeFileName, includeString)
| vermaete/ipxact2systemverilog | ipxact2systemverilog/ipxact2hdlCommon.py | Python | gpl-2.0 | 46,497 |
<?php
/*
+---------------------------------------------------------------------------+
| OpenX v2.8 |
| ========== |
| |
| Copyright (c) 2003-2009 OpenX Limited |
| For contact details, see: http://www.openx.org/ |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by |
| the Free Software Foundation; either version 2 of the License, or |
| (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
| |
| You should have received a copy of the GNU General Public License |
| along with this program; if not, write to the Free Software |
| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
+---------------------------------------------------------------------------+
$Id: PasswordRecovery.php 82775 2013-08-06 23:40:26Z chris.nutting $
*/
/**
* Password recovery DAL for Openads
*
* @package OpenXDal
*/
require_once MAX_PATH.'/lib/OA/Dal.php';
require_once MAX_PATH.'/lib/max/Plugin.php';
class OA_Dal_PasswordRecovery extends OA_Dal
{
/**
* Search users with a matching email address
*
* @param string e-mail
* @return array matching users
*/
function searchMatchingUsers($email)
{
$doUsers = OA_Dal::factoryDO('users');
$doUsers->email_address = $email;
$doUsers->find();
$users = array();
while ($doUsers->fetch()) {
$users[] = $doUsers->toArray();
}
return $users;
}
/**
* Generate and save a recovery ID for a user
*
* @param int user ID
* @return array generated recovery ID
*/
function generateRecoveryId($userId)
{
$doPwdRecovery = OA_Dal::factoryDO('password_recovery');
// Make sure that recoveryId is unique in password_recovery table
do {
$recoveryId = strtoupper(md5(uniqid('', true)));
$recoveryId = substr(chunk_split($recoveryId, 8, '-'), -23, 22);
$doPwdRecovery->recovery_id = $recoveryId;
} while ($doPwdRecovery->find()>0);
$doPwdRecovery = OA_Dal::factoryDO('password_recovery');
$doPwdRecovery->whereAdd('user_id = '.DBC::makeLiteral($userId));
$doPwdRecovery->delete(true);
$doPwdRecovery = OA_Dal::factoryDO('password_recovery');
$doPwdRecovery->user_type = 'user';
$doPwdRecovery->user_id = $userId;
$doPwdRecovery->recovery_id = $recoveryId;
$doPwdRecovery->updated = OA::getNowUTC();
$doPwdRecovery->insert();
return $recoveryId;
}
/**
* Check if recovery ID is valid
*
* @param string recovery ID
* @return bool true if recovery ID is valid
*/
function checkRecoveryId($recoveryId)
{
$doPwdRecovery = OA_Dal::factoryDO('password_recovery');
$doPwdRecovery->recovery_id = $recoveryId;
return (bool)$doPwdRecovery->count();
}
/**
* Save the new password in the user properties
*
* @param string recovery ID
* @param string new password
* @return bool Ttrue the new password was correctly saved
*/
function saveNewPasswordAndLogin($recoveryId, $password)
{
$doPwdRecovery = OA_Dal::factoryDO('password_recovery');
$doPwdRecovery->recovery_id = $recoveryId;
$doPwdRecoveryClone = clone($doPwdRecovery);
$doPwdRecovery->find();
if ($doPwdRecovery->fetch()) {
$userId = $doPwdRecovery->user_id;
$doPlugin = &OA_Auth::staticGetAuthPlugin();
$doPlugin->setNewPassword($userId, $password);
$doPwdRecoveryClone->delete();
phpAds_SessionStart();
$doUser = OA_Dal::staticGetDO('users', $userId);
phpAds_SessionDataRegister(OA_Auth::getSessionData($doUser));
phpAds_SessionDataStore();
return true;
}
return false;
}
}
?>
| maestrano/openx | lib/OA/Dal/PasswordRecovery.php | PHP | gpl-2.0 | 4,846 |
class CreateTeachers < ActiveRecord::Migration
def change
create_table :teachers do |t|
t.string :name, null: false
t.integer :grade
t.integer :college_id
t.integer :user_id
t.string :address
t.string :phone
t.string :email
t.timestamps null: false
end
end
end
| vjudge1/score | db/migrate/20150908120446_create_teachers.rb | Ruby | gpl-2.0 | 322 |
describe('PastDateValidatorWidgetFactory', function() {
var Mock = {};
var factory;
var whoAmI;
beforeEach(function() {
angular.mock.module('studio');
mockElement();
inject(function(_$injector_) {
mockWidgetScope(_$injector_);
factory = _$injector_.get('PastDateValidatorWidgetFactory');
});
widget = factory.create(Mock.scope, Mock.element);
});
describe('Start a PastDate Factory Object', function() {
it('should return a PastDate Validator Object', function() {
pending();
});
it('should start the data field as date', function() {
expect(widget.data).toBeDefined();
expect(widget.data).toEqual(false);
});
});
describe('updates on data', function() {
xit('should model data value be equal to self value', function() {
// expect(Mock.question.fillingRules.options['pastDate'].data.reference).toEqual(widget.data);
});
it('should call updateFillingRules from parente widget', function() {
spyOn(Mock.parentWidget, 'updateFillingRules');
widget.updateData();
expect(Mock.parentWidget.updateFillingRules).toHaveBeenCalled();
});
});
function mockElement() {
Mock.element = {};
}
function mockWidgetScope($injector) {
Mock.scope = {
class: '',
$parent: {
widget: mockParentWidget($injector)
}
};
return Mock.scope;
}
function mockParentWidget($injector) {
mockQuestion($injector);
Mock.parentWidget = {
getItem: function() {
return Mock.question;
},
updateFillingRules: function() {}
};
return Mock.parentWidget;
}
function mockQuestion($injector) {
Mock.question = $injector.get('SurveyItemFactory').create('IntegerQuestion', 'Q1');
Mock.question.fillingRules.options.pastDate = $injector.get('RulesFactory').create('pastDate');
return Mock.question;
}
function mockAdd($injector) {
Mock.add = $injector.get('FillingRulesEditorWidgetFactory').create();
}
});
| ccem-dev/studio | tests/unit/editor/ui/validation/require/past-date/past-date-validator-widget-factory-spec.js | JavaScript | gpl-2.0 | 2,268 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bc;
import be.ReporteFumigacion;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author argos
*/
@Stateless
public class ReporteFumigacionFacade extends AbstractFacade<ReporteFumigacion> implements ReporteFumigacionFacadeLocal {
@PersistenceContext(unitName = "sistema-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
public ReporteFumigacionFacade() {
super(ReporteFumigacion.class);
}
}
| jchalco/Ate | sistema/sistema-ejb/src/java/bc/ReporteFumigacionFacade.java | Java | gpl-2.0 | 663 |
require File.dirname(__FILE__) + '/../spec_helper'
describe PagesController do
describe 'handling GET for a single post' do
before(:each) do
@page = mock_model(Page)
Page.stub(:find_by_slug).and_return(@page)
end
def do_get
get :show, :id => 'a-page'
end
it "should be successful" do
do_get
response.should be_success
end
it "should render show template" do
do_get
response.should render_template('show')
end
it 'should find the page requested' do
Page.should_receive(:find_by_slug).with('a-page').and_return(@page)
do_get
end
it 'should assign the page found for the view' do
do_get
assigns[:page].should equal(@page)
end
end
describe 'handling GET with invalid page' do
it 'raises a RecordNotFound error' do
Page.stub(:find_by_slug).and_return(nil)
lambda {
get :show, :id => 'a-page'
}.should raise_error(ActiveRecord::RecordNotFound)
end
end
end
| scottwainstock/pbm-blog | spec/controllers/pages_controller_spec.rb | Ruby | gpl-2.0 | 1,013 |
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2013 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#ifndef XCSOAR_CYLINDER_ZONE_EDIT_WIDGET_HPP
#define XCSOAR_CYLINDER_ZONE_EDIT_WIDGET_HPP
#include "ObservationZoneEditWidget.hpp"
#include <assert.h>
class CylinderZone;
class CylinderZoneEditWidget : public ObservationZoneEditWidget {
const bool radius_editable;
public:
CylinderZoneEditWidget(CylinderZone &oz, bool _length_editable);
protected:
const CylinderZone &GetObject() const {
return (const CylinderZone &)ObservationZoneEditWidget::GetObject();
}
CylinderZone &GetObject() {
return (CylinderZone &)ObservationZoneEditWidget::GetObject();
}
public:
/* virtual methods from class Widget */
virtual void Prepare(ContainerWindow &parent,
const PixelRect &rc) override;
virtual bool Save(bool &changed) override;
};
#endif
| onkelhotte/test | src/Dialogs/Task/Widgets/CylinderZoneEditWidget.hpp | C++ | gpl-2.0 | 1,691 |
<?php defined('_JEXEC') or die('Restricted access');
// SEF problem
$isThereQMR = false;
$isThereQMR = preg_match("/\?/i", $this->tmpl['action']);
if ($isThereQMR) {
$amp = '&';
} else {
$amp = '?';
}
if ((int)$this->tmpl['displayratingimg'] == 1) {
// Leave message for already voted images
$vote = JRequest::getVar('vote', 0, '', 'int');
if ($vote == 1) {
$voteMsg = JText::_('PHOCA GALLERY IMAGE RATED');
} else {
$voteMsg = JText::_('You have already rated this image');
}
?><table style="text-align:left" border="0"><tr><td><?php
echo '<strong>' . JText::_('Rating'). '</strong>: ' . $this->tmpl['votesaverageimg'] .' / '.$this->tmpl['votescountimg'] . ' ' . JText::_($this->tmpl['votestextimg']). ' ';
if ($this->tmpl['alreadyratedimg']) {
echo '<td style="text-align:left"><ul class="star-rating">'
.'<li class="current-rating" style="width:'.$this->tmpl['voteswidthimg'].'px"></li>'
.'<li><span class="star1"></span></li>';
for ($i = 2;$i < 6;$i++) {
echo '<li><span class="stars'.$i.'"></span></li>';
}
echo '</ul></td>'
.'<td style="text-align:left" colspan="4"> '.$voteMsg.'</td></tr>';
} else if ($this->tmpl['notregisteredimg']) {
echo '<td style="text-align:left"><ul class="star-rating">'
.'<li class="current-rating" style="width:'.$this->tmpl['voteswidthimg'].'px"></li>'
.'<li><span class="star1"></span></li>';
for ($i = 2;$i < 6;$i++) {
echo '<li><span class="stars'.$i.'"></span></li>';
}
echo '</ul></td>'
.'<td style="text-align:left" colspan="4"> '.JText::_('Only registered and logged in user can rate this image').'</td>';
} else {
echo '<td style="text-align:left"><ul class="star-rating">'
.'<li class="current-rating" style="width:'.$this->tmpl['voteswidthimg'].'px"></li>'
.'<li><a href="'.$this->tmpl['action'].$amp.'controller=detail&task=rate&rating=1" title="1 '. JText::_('star out of').' 5" class="star1">1</a></li>';
for ($i = 2;$i < 6;$i++) {
echo '<li><a href="'.$this->tmpl['action'].$amp.'controller=detail&task=rate&rating='.$i.'" title="'.$i.' '. JText::_('star out of').' 5" class="stars'.$i.'">'.$i.'</a></li>';
}
echo '</td>';
}
?></tr></table><?php
}
?>
| prabhu9484/testFork | components/com_phocagallery/views/detail/tmpl/default_rating.php | PHP | gpl-2.0 | 2,301 |
#!/usr/bin/python
# encoding: utf-8
# filename: outroTipoDeProducaoBibliografica.py
#
# scriptLattes V8
# Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr.
# http://scriptlattes.sourceforge.net/
#
#
# Este programa é um software livre; você pode redistribui-lo e/ou
# modifica-lo dentro dos termos da Licença Pública Geral GNU como
# publicada pela Fundação do Software Livre (FSF); na versão 2 da
# Licença, ou (na sua opinião) qualquer versão.
#
# Este programa é distribuído na esperança que possa ser util,
# mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer
# MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a
# Licença Pública Geral GNU para maiores detalhes.
#
# Você deve ter recebido uma cópia da Licença Pública Geral GNU
# junto com este programa, se não, escreva para a Fundação do Software
# Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
from scriptLattes import *
from geradorDePaginasWeb import *
import re
class OutroTipoDeProducaoBibliografica:
item = None # dado bruto
idMembro = None
relevante = None
autores = None
titulo = None
ano = None
natureza = None # tipo de producao
chave = None
def __init__(self, idMembro, partesDoItem='', relevante=''):
self.idMembro = set([])
self.idMembro.add(idMembro)
if not partesDoItem=='':
# partesDoItem[0]: Numero (NAO USADO)
# partesDoItem[1]: Descricao do livro (DADO BRUTO)
self.relevante = relevante
self.item = partesDoItem[1]
# Dividir o item na suas partes constituintes
partes = self.item.partition(" . ")
self.autores = partes[0].strip()
partes = partes[2]
aux = re.findall(u' \((.*?)\)\.$', partes)
if len(aux)>0:
self.natureza = aux[-1]
partes = partes.rpartition(" (")
partes = partes[0]
else:
self.natureza = ''
aux = re.findall(u' ((?:19|20)\d\d)\\b', partes)
if len(aux)>0:
self.ano = aux[-1] #.strip().rstrip(".").rstrip(",")
partes = partes.rpartition(" ")
partes = partes[0]
else:
self.ano = ''
self.titulo = partes.strip().rstrip(".").rstrip(",")
self.chave = self.autores # chave de comparação entre os objetos
else:
self.relevante = ''
self.autores = ''
self.titulo = ''
self.ano = ''
self.natureza = ''
def compararCom(self, objeto):
if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo):
# Os IDs dos membros são agrupados.
# Essa parte é importante para a criação do GRAFO de colaborações
self.idMembro.update(objeto.idMembro)
if len(self.autores)<len(objeto.autores):
self.autores = objeto.autores
if len(self.titulo)<len(objeto.titulo):
self.titulo = objeto.titulo
if len(self.natureza)<len(objeto.natureza):
self.natureza = objeto.natureza
return self
else: # nao similares
return None
def html(self, listaDeMembros):
s = self.autores + '. <b>' + self.titulo + '</b>. '
s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. '
s+= self.natureza if not self.natureza=='' else ''
s+= menuHTMLdeBuscaPB(self.titulo)
return s
# ------------------------------------------------------------------------ #
def __str__(self):
s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n"
s += "+ID-MEMBRO : " + str(self.idMembro) + "\n"
s += "+RELEVANTE : " + str(self.relevante) + "\n"
s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n"
s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n"
s += "+ANO : " + str(self.ano) + "\n"
s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n"
s += "+item : " + self.item.encode('utf8','replace') + "\n"
return s
| DiegoQueiroz/scriptLattes | scriptLattes/producoesBibliograficas/outroTipoDeProducaoBibliografica.py | Python | gpl-2.0 | 3,771 |
<?php
/*
* Child theme creation results page
*/
?>
<div id="child_created" class="main-panel">
<h3><?php _e( 'Your child theme was successfully created!', 'divi-children' ); ?></h3>
<div id="created_theme">
<div class="theme_screenshot">
<img src="<?php echo $divichild['new_theme_dir'] . '/screenshot.jpg'; ?>" alt="screenshot">
</div>
<div class="theme_info">
<h3><?php echo $divichild['new_theme_name']; ?></h3>
<h4><?php _e( 'By', 'divi-children' ); ?><?php echo ' ' . $divichild['new_theme_authorname']; ?></h4>
<p><em><?php _e( 'Version', 'divi-children' ); ?></em><b><?php echo ': ' . $divichild['new_theme_version']; ?></b></p>
<p><b><?php echo $divichild['new_theme_description']; ?></b></p>
<p><em><?php _e( 'Parent Theme', 'divi-children' ); ?></em><b><?php echo ': ' . $divichild['new_theme_parent']; ?></b></p>
<p><em><?php _e( 'Theme URI', 'divi-children' ); ?></em><b><?php echo ': ' . $divichild['new_theme_uri']; ?></b></p>
<p><em><?php _e( 'Author URI', 'divi-children' ); ?></em><b><?php echo ': ' . $divichild['new_theme_authoruri']; ?></b></p>
<a href="<?php echo admin_url( 'themes.php' ); ?>" class="button-primary"><?php _e( 'You can activate it now in the Themes Manager', 'divi-children' ); ?></a>
</div>
</div>
</div>
<div id="footer_display">
<h3><?php _e( 'Your footer credits will look like this:', 'divi-children' ); ?></h3>
<div class="footer-display">
<?php
$firstyear = get_option( 'footer_credits_firstyear' );
$owner = get_option( 'footer_credits_owner' );
$ownerlink = get_option( 'footer_credits_ownerlink' );
$developed_text = get_option( 'footer_credits_developed' );
$developer = get_option( 'footer_credits_developer' );
$developerlink = get_option( 'footer_credits_developerlink' );
$powered_text = get_option( 'footer_credits_powered' );
$powered_code = get_option( 'footer_credits_poweredcode' );
$powered_codelink = get_option( 'footer_credits_poweredcodelink' );
$footer_credits = 'Copyright © ';
$current_year = date( 'Y' );
if ( $firstyear AND ($firstyear != 0 )) {
if( $firstyear != $current_year ) {
$footer_credits .= $firstyear . ' - ' . $current_year;
}
} else {
$footer_credits .= $current_year;
}
$footer_credits .= ' <a href="' . esc_url( $ownerlink ) . '">' . $owner . '</a>';
if ( $developed_text ) {
$footer_credits .= ' | ' . $developed_text . ' ' . '<a href="' . esc_url( $developerlink ) . '">' . $developer . '</a>';
}
if ( $powered_text ) {
$footer_credits .= ' | ' . $powered_text . ' ' . '<a href="' . esc_url( $powered_codelink ) . '">' . $powered_code . '</a>';
}
echo $footer_credits;
?>
</div>
</div> | todd3773/netpartnering | wp-content/plugins/Divi_Children_2.0.8/includes/results-page.php | PHP | gpl-2.0 | 2,728 |
using System.IO;
using System.Text;
namespace CodeMask.WPF.Controls.Gif.Decoding
{
internal class GifCommentExtension : GifExtension
{
internal const int ExtensionLabel = 0xFE;
private GifCommentExtension()
{
}
public string Text { get; private set; }
internal override GifBlockKind Kind
{
get { return GifBlockKind.SpecialPurpose; }
}
internal static GifCommentExtension ReadComment(Stream stream)
{
var comment = new GifCommentExtension();
comment.Read(stream);
return comment;
}
private void Read(Stream stream)
{
// Note: at this point, the label (0xFE) has already been read
var bytes = GifHelpers.ReadDataBlocks(stream, false);
if (bytes != null)
Text = Encoding.ASCII.GetString(bytes);
}
}
} | cooglex/CodeMask | CodeMask/CodeMask.WPF.Controls/Gif/Decoding/GifCommentExtension.cs | C# | gpl-2.0 | 929 |
/**
* @file SleepTimer.cpp
* @author Pere Tuset-Peiro (peretuset@openmote.com)
* @version v0.1
* @date May, 2015
* @brief
*
* @copyright Copyright 2015, OpenMote Technologies, S.L.
* This file is licensed under the GNU General Public License v2.
*/
/*================================ include ==================================*/
#include "SleepTimer.h"
#include "InterruptHandler.h"
#include "cc2538_include.h"
/*================================ define ===================================*/
/*================================ typedef ==================================*/
/*=============================== variables =================================*/
/*=============================== prototypes ================================*/
/*================================= public ==================================*/
SleepTimer::SleepTimer(uint32_t interrupt):
interrupt_(interrupt)
{
}
void SleepTimer::start(uint32_t counts)
{
uint32_t current;
// Get current counter
current = SleepModeTimerCountGet();
// Set future timeout
SleepModeTimerCompareSet(current + counts);
}
void SleepTimer::stop(void)
{
// Nothing to do here, SleepTimer cannot be stopped
}
uint32_t SleepTimer::sleep(void)
{
return 0;
}
void SleepTimer::wakeup(uint32_t ticks)
{
}
uint32_t SleepTimer::getCounter(void)
{
// Get current counter
return SleepModeTimerCountGet();
}
bool SleepTimer::isExpired(uint32_t future)
{
uint32_t current;
int32_t delta;
// Get current counter
current = SleepModeTimerCountGet();
// Calculate delta
delta = (int32_t) (current - future);
// Return true if expired
return (delta < 0);
}
void SleepTimer::setCallback(Callback* callback)
{
callback_ = callback;
}
void SleepTimer::clearCallback(void)
{
callback_ = nullptr;
}
void SleepTimer::enableInterrupts(void)
{
InterruptHandler::getInstance().setInterruptHandler(this);
IntEnable(interrupt_);
}
void SleepTimer::disableInterrupts(void)
{
IntDisable(interrupt_);
InterruptHandler::getInstance().clearInterruptHandler(this);
}
/*=============================== protected =================================*/
/*================================ private ==================================*/
void SleepTimer::interruptHandler(void)
{
if (callback_ != nullptr)
{
callback_->execute();
}
}
| tdautc19841202/firmware | platform/cc2538/SleepTimer.cpp | C++ | gpl-2.0 | 2,420 |
<?php
/*
*
* Copyright 2001-2004 Thomas Belliard, Laurent Delineau, Edouard Hue, Eric Lebrun
*
* This file is part of GEPI.
*
* GEPI 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.
*
* GEPI 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 GEPI; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Initialisations files
require_once("../lib/initialisations.inc.php");
// Resume session
$resultat_session = $session_gepi->security_check();
if ($resultat_session == '0') {
header("Location: ../logout.php?auto=1");
die();
};
//**************** EN-TETE *****************
require_once("../lib/header.inc.php");
//**************** FIN EN-TETE *************
?>
<h1 class='gepi'>GEPI - Informations générales</h1>
<?php
echo "Vous êtes actuellement connecté sur l'application <b>GEPI (".getSettingValue("gepiSchoolName").")</b>.
<br />Par sécurité, si vous n'envoyez aucune information au serveur (activation d'un lien ou soumission d'un formulaire) pendant plus de <b>".getSettingValue("sessionMaxLength")." minutes</b>, vous serez automatiquement déconnecté de l'application.";
echo "<h2>Administration de l'application GEPI</h2>\n";
echo "<table cellpadding='5' summary='Infos'>\n";
echo "<tr><td>Nom et prénom de l'administrateur : </td><td><b>".getSettingValue("gepiAdminNom")." ".getSettingValue("gepiAdminPrenom")."</b></td></tr>\n";
echo "<tr><td>Fonction de l'administrateur : </td><td><b>".getSettingValue("gepiAdminFonction")."</b></td></tr>\n";
echo "<tr><td>Email de l'administrateur : </td><td><b><a href=\"mailto:" . getSettingValue("gepiAdminAdress") . "\">".getSettingValue("gepiAdminAdress")."</a></b></td></tr>\n";
echo "<tr><td>Nom de l'établissement : </td><td><b>".getSettingValue("gepiSchoolName")."</b></td></tr>\n";
echo "<tr><td Valign='top'>Adresse : </td><td><b>".getSettingValue("gepiSchoolAdress1")."<br />".getSettingValue("gepiSchoolAdress2")."<br />".getSettingValue("gepiSchoolZipCode")." ".getSettingValue("gepiSchoolCity")."</b></td></tr>\n";
echo "</table>\n";
echo "<h2>Objectifs de l'application GEPI</h2>\n";
echo "L'objectif de GEPI est la <b>gestion pédagogique des élèves et de leur scolarité</b>.
Dans ce but, des données sont collectées et stockées dans une base unique de type MySql.";
echo "<h2>Obligations de l'utilisateur</h2>\n";
echo "Les membres de l'équipe pédagogique sont tenus de remplir les rubriques qui leur ont été affectées par l'administrateur
lors du paramétrage de l'application.";
echo "<br />Il est possible de modifier le contenu d'une rubrique tant que la période concernée n'a pas été close par l'administrateur.";
echo "<h2>Destinataires des données relatives au bulletin scolaire</h2>\n";
echo "Concernant le bulletin scolaire, les données suivantes sont récoltées auprès des membres de l'équipe pédagogique :
<ul><li>absences (pour chaque période : nombre de demi-journées d'absence, nombre d'absences non justifiées, nombre de retards, observations)</li>
<li>moyennes et appréciations par matière,</li>
<li>moyennes et appréciations par projet inter-disciplinaire,</li>
<li>avis du conseil de classe.</li>
</ul>
Toutes ces informations sont intégralement reproduites sur un bulletin à la fin de chaque période (voir ci-dessous).
<br /><br />
Ces données servent à :
<ul>
<li>l'élaboration d'un bulletin à la fin de chaque période, édité par le service scolarité et communiqué à l'élève
et à ses responsables légaux : notes obtenues, absences, moyennes, appréciations des enseignants, avis du conseil de classe.</li>
<li>l'élaboration d'un document de travail reprenant les informations du bulletin officiel et disponible pour les membres de l'équipe pédagogique de la classe concernée</li>
</ul>\n";
//On vérifie si le module cahiers de texte est activé
if (getSettingValue("active_cahiers_texte")=='y') {
echo "<h2>Destinataires des données relatives au cahier de texte</h2>\n";
echo "Conformément aux directives de l'Education Nationale, chaque professeur dispose dans GEPI d'un cahier de texte pour chacune de ses classes qu'il peut tenir à jour
en étant connecté.
<br />
Le cahier de texte relate le travail réalisé en classe :
<ul>
<li>projet de l'équipe pédagogique,</li>
<li>contenu pédagogique de chaque séance, chronologie, objectif visé, travail à faire ...</li>
<li>documents divers,</li>
<li>évaluations, ...</li>
</ul>
Il constitue un outil de communication pour l'élève, les équipes disciplinaires
et pluridisciplinaires, l'administration, le chef d'établissement, les corps d'inspection et les familles.
<br /> Les cahiers de texte sont accessibles en ligne.";
if ((getSettingValue("cahiers_texte_login_pub") != '') and (getSettingValue("cahiers_texte_passwd_pub") != '')) {
echo " <b>En raison du caractére personnel du contenu, l'accès à l'interface de consultation publique est restreint</b>. Pour accéder aux cahiers de texte, il est nécessaire de demander auprès de l'administrateur,
le nom d'utilisateur et le mot de passe valides.";
} else {
echo " <b>L'accès à l'interface de consultation publique est entièrement libre et n'est soumise à aucune restriction.</b>\n";
}
}
//On vérifie si le module carnet de notes est activé
if (getSettingValue("active_carnets_notes")=='y') {
echo "<h2>Destinataires des données relatives au carnet de notes</h2>\n";
echo "Chaque professeur dispose dans GEPI d'un carnet de notes pour chacune de ses classes, qu'il peut tenir à jour
en étant connecté.
<br />
Le carnet de note permet la saisie des notes et/ou des commentaires de tout type d'évaluation (formatives, sommatives, oral, TP, TD, ...).
<br /><b>Le professeur s'engage à ne faire figurer dans le carnet de notes que des notes et commentaires portés à la connaissance de l'élève (note et commentaire portés sur la copie, ...).</b>
Ces données stockées dans GEPI n'ont pas d'autre destinataire que le professeur lui-même et le ou les professeurs principaux de la classe.
<br />Les notes peuvent servir à l'élaboration d'une moyenne qui figurera dans le bulletin officiel à la fin de chaque période.";
}
//On vérifie si le plugin suivi_eleves est activé
$test_plugin = sql_query1("select ouvert from plugins where nom='suivi_eleves'");
if ($test_plugin=='y') {
echo "<h2>Destinataires des données relatives au module de suivi des élèves</h2>\n";
echo "Chaque professeur dispose dans GEPI d'un outil de suivi des élèves (\"observatoire\") pour chacune de ses classes, qu'il peut tenir à jour
en étant connecté.
<br />
Dans l'observatoire, le professeur a la possibilité d'attribuer à chacun de ses élèves un code pour chaque période.
Ces codes et leur signification sont paramétrables par les administrateurs de l'observatoire désignés par l'administrateur général de GEPI.
<br />.
Le professeur dispose également de la possibilité de saisir un commentaire pour chacun de ses élèves
dans le respect de la loi et dans le cadre strict de l'Education Nationale.
<br /><br />L'observatoire et les données qui y figurent sont accessibles à l'ensemble de l'équipe pédagogique de l'établissement.
<br /><br />Dans le respect de la loi informatique et liberté 78-17 du 6 janvier 1978, chaque élève a également accès dans son espace GEPI aux données qui le concernent";
}
require("../lib/footer.inc.php");
?>
| Regis85/gepi | gestion/info_gepi.php | PHP | gpl-2.0 | 8,127 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.stat.clustering;
import java.io.Serializable;
import java.util.Collection;
import java.util.Arrays;
import org.apache.commons.math3.util.MathArrays;
/**
* A simple implementation of {@link Clusterable} for points with double coordinates.
* @version $Id$
* @since 3.1
*/
public class EuclideanDoublePoint implements Clusterable<EuclideanDoublePoint>, Serializable {
/** Serializable version identifier. */
private static final long serialVersionUID = 8026472786091227632L;
/** Point coordinates. */
private final double[] point;
/**
* Build an instance wrapping an integer array.
* <p>
* The wrapped array is referenced, it is <em>not</em> copied.
*
* @param point the n-dimensional point in integer space
*/
public EuclideanDoublePoint(final double[] point) {
this.point = point;
}
/** {@inheritDoc} */
public EuclideanDoublePoint centroidOf(final Collection<EuclideanDoublePoint> points) {
final double[] centroid = new double[getPoint().length];
for (final EuclideanDoublePoint p : points) {
for (int i = 0; i < centroid.length; i++) {
centroid[i] += p.getPoint()[i];
}
}
for (int i = 0; i < centroid.length; i++) {
centroid[i] /= points.size();
}
return new EuclideanDoublePoint(centroid);
}
/** {@inheritDoc} */
public double distanceFrom(final EuclideanDoublePoint p) {
return MathArrays.distance(point, p.getPoint());
}
/** {@inheritDoc} */
@Override
public boolean equals(final Object other) {
if (!(other instanceof EuclideanDoublePoint)) {
return false;
}
return Arrays.equals(point, ((EuclideanDoublePoint) other).point);
}
/**
* Get the n-dimensional point in integer space.
*
* @return a reference (not a copy!) to the wrapped array
*/
public double[] getPoint() {
return point;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return Arrays.hashCode(point);
}
/** {@inheritDoc} */
@Override
public String toString() {
return Arrays.toString(point);
}
}
| SpoonLabs/astor | examples/math_5/src/main/java/org/apache/commons/math3/stat/clustering/EuclideanDoublePoint.java | Java | gpl-2.0 | 3,065 |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
#
# 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$
__all__ = ["LinkBox"]
#-------------------------------------------------------------------------
#
# Standard python modules
#
#-------------------------------------------------------------------------
import logging
_LOG = logging.getLogger(".widgets.linkbox")
#-------------------------------------------------------------------------
#
# GTK/Gnome modules
#
#-------------------------------------------------------------------------
from gi.repository import GObject
from gi.repository import Gtk
#-------------------------------------------------------------------------
#
# LinkBox class
#
#-------------------------------------------------------------------------
class LinkBox(Gtk.HBox):
def __init__(self, link, button):
GObject.GObject.__init__(self)
self.set_spacing(6)
self.pack_start(link, False, True, 0)
if button:
self.pack_start(button, False, True, 0)
self.show()
| Forage/Gramps | gramps/gui/widgets/linkbox.py | Python | gpl-2.0 | 1,754 |
/*
Copyright_License {
Top Hat Soaring Glide Computer - http://www.tophatsoaring.org/
Copyright (C) 2000-2016 The Top Hat Soaring Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#include "ConditionMonitors.hpp"
#include "ConditionMonitorAATTime.hpp"
#include "ConditionMonitorFinalGlide.hpp"
#include "ConditionMonitorGlideTerrain.hpp"
#include "ConditionMonitorLandableReachable.hpp"
#include "ConditionMonitorSunset.hpp"
#include "ConditionMonitorWind.hpp"
static ConditionMonitorWind cm_wind;
static ConditionMonitorFinalGlide cm_finalglide;
static ConditionMonitorSunset cm_sunset;
static ConditionMonitorAATTime cm_aattime;
static ConditionMonitorGlideTerrain cm_glideterrain;
static ConditionMonitorLandableReachable cm_landablereachable;
void
ConditionMonitorsUpdate(const NMEAInfo &basic, const DerivedInfo &calculated,
const ComputerSettings &settings)
{
cm_wind.Update(basic, calculated, settings);
cm_finalglide.Update(basic, calculated, settings);
cm_sunset.Update(basic, calculated, settings);
cm_aattime.Update(basic, calculated, settings);
cm_glideterrain.Update(basic, calculated, settings);
cm_landablereachable.Update(basic, calculated, settings);
}
| rdunning0823/tophat | src/Computer/ConditionMonitor/ConditionMonitors.cpp | C++ | gpl-2.0 | 1,954 |
template <typename Item>
void mergesort(Item a[], int l, int r)
{
if (r <= 1) return ;
int m = (r+1)/2;
mergesort(a, l, m);
mergesort(a, m+1, r);
merge(a, l, m, r);
}
| flow-J/Exercise | garbage/Algorithm_in_c++/test8.3.cpp | C++ | gpl-2.0 | 187 |
/* This file is part of the KDE project
Copyright (C) 2002 Carsten Pfeiffer <pfeiffer@kde.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation, version 2.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include <dcopclient.h>
#include <kapplication.h>
#include <kprocess.h>
#include <kstaticdeleter.h>
#include "watcher_stub.h"
#include "mrml_utils.h"
// after 100 of no use, terminate the mrmld
#define TIMEOUT 100
// how often to restart the mrmld in case of failure
#define NUM_RESTARTS 5
using namespace KMrml;
KStaticDeleter<Util> utils_sd;
Util *Util::s_self = 0L;
Util::Util()
{
// we need our own dcopclient, when used in kio_mrml
if ( !DCOPClient::mainClient() )
{
DCOPClient::setMainClient( new DCOPClient() );
if ( !DCOPClient::mainClient()->attach() )
qWarning( "kio_mrml: Can't attach to DCOP Server.");
}
}
Util::~Util()
{
if ( this == s_self )
s_self = 0L;
}
Util *Util::self()
{
if ( !s_self )
s_self = utils_sd.setObject( new Util() );
return s_self;
}
bool Util::requiresLocalServerFor( const KURL& url )
{
return url.host().isEmpty() || url.host() == "localhost";
}
bool Util::startLocalServer( const Config& config )
{
if ( config.serverStartedIndividually() )
return true;
DCOPClient *client = DCOPClient::mainClient();
// ### check if it's already running (add dcop method to Watcher)
Watcher_stub watcher( client, "kded", "daemonwatcher");
return ( watcher.requireDaemon( client->appId(),
"mrmld", config.mrmldCommandline(),
TIMEOUT, NUM_RESTARTS )
&& watcher.ok() );
}
void Util::unrequireLocalServer()
{
DCOPClient *client = DCOPClient::mainClient();
Watcher_stub watcher( client, "kded", "daemonwatcher");
watcher.unrequireDaemon( client->appId(), "mrmld" );
}
| iegor/kdegraphics | kmrml/kmrml/lib/mrml_utils.cpp | C++ | gpl-2.0 | 2,481 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2015
* $Id$
*
*/
class CRM_Event_Import_Controller extends CRM_Core_Controller {
/**
* Class constructor.
*
* @param null $title
* @param bool|int $action
* @param bool $modal
*/
public function __construct($title = NULL, $action = CRM_Core_Action::NONE, $modal = TRUE) {
parent::__construct($title, $modal);
// lets get around the time limit issue if possible, CRM-2113
if (!ini_get('safe_mode')) {
set_time_limit(0);
}
$this->_stateMachine = new CRM_Import_StateMachine($this, $action);
// create and instantiate the pages
$this->addPages($this->_stateMachine, $action);
// add all the actions
$config = CRM_Core_Config::singleton();
$this->addActions($config->uploadDir, array('uploadFile'));
}
}
| alfonsom/ccdrupal | sites/all/modules/civicrm/CRM/Event/Import/Controller.php | PHP | gpl-2.0 | 2,507 |
<?php
/**
* @version $Id: legacy.php 10066 2008-02-26 04:20:57Z ian $
* @package Joomla
* @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.plugin.plugin' );
/**
* Joomla! Debug plugin
*
* @author Johan Janssens <johan.janssens@joomla.org>
* @package Joomla
* @subpackage System
*/
class plgSystemLegacy extends JPlugin
{
/**
* Constructor
*
* For php4 compatability we must not use the __constructor as a constructor for plugins
* because func_get_args ( void ) returns a copy of all passed arguments NOT references.
* This causes problems with cross-referencing necessary for the observer design pattern.
*
* @param object $subject The object to observe
* @param array $config An array that holds the plugin configuration
* @since 1.0
*/
function plgSystemLegacy(& $subject, $config)
{
parent::__construct($subject, $config);
global $mainframe;
// Define the 1.0 legacy mode constant
define('_JLEGACY', '1.0');
// Set global configuration var for legacy mode
$config = &JFactory::getConfig();
$config->setValue('config.legacy', 1);
// Import library dependencies
require_once(dirname(__FILE__).DS.'legacy'.DS.'classes.php');
require_once(dirname(__FILE__).DS.'legacy'.DS.'functions.php');
// Register legacy classes for autoloading
JLoader::register('mosAdminMenus' , dirname(__FILE__).DS.'legacy'.DS.'adminmenus.php');
JLoader::register('mosCache' , dirname(__FILE__).DS.'legacy'.DS.'cache.php');
JLoader::register('mosCategory' , dirname(__FILE__).DS.'legacy'.DS.'category.php');
JLoader::register('mosCommonHTML' , dirname(__FILE__).DS.'legacy'.DS.'commonhtml.php');
JLoader::register('mosComponent' , dirname(__FILE__).DS.'legacy'.DS.'component.php');
JLoader::register('mosContent' , dirname(__FILE__).DS.'legacy'.DS.'content.php');
JLoader::register('mosDBTable' , dirname(__FILE__).DS.'legacy'.DS.'dbtable.php');
JLoader::register('mosHTML' , dirname(__FILE__).DS.'legacy'.DS.'html.php');
JLoader::register('mosInstaller' , dirname(__FILE__).DS.'legacy'.DS.'installer.php');
JLoader::register('mosMainFrame' , dirname(__FILE__).DS.'legacy'.DS.'mainframe.php');
JLoader::register('mosMambot' , dirname(__FILE__).DS.'legacy'.DS.'mambot.php');
JLoader::register('mosMambotHandler', dirname(__FILE__).DS.'legacy'.DS.'mambothandler.php');
JLoader::register('mosMenu' , dirname(__FILE__).DS.'legacy'.DS.'menu.php');
JLoader::register('mosMenuBar' , dirname(__FILE__).DS.'legacy'.DS.'menubar.php');
JLoader::register('mosModule' , dirname(__FILE__).DS.'legacy'.DS.'module.php');
//JLoader::register('mosPageNav' , dirname(__FILE__).DS.'legacy'.DS.'pagination.php');
JLoader::register('mosParameters' , dirname(__FILE__).DS.'legacy'.DS.'parameters.php');
JLoader::register('patFactory' , dirname(__FILE__).DS.'legacy'.DS.'patfactory.php');
JLoader::register('mosProfiler' , dirname(__FILE__).DS.'legacy'.DS.'profiler.php');
JLoader::register('mosSection' , dirname(__FILE__).DS.'legacy'.DS.'section.php');
JLoader::register('mosSession' , dirname(__FILE__).DS.'legacy'.DS.'session.php');
JLoader::register('mosToolbar' , dirname(__FILE__).DS.'legacy'.DS.'toolbar.php');
JLoader::register('mosUser' , dirname(__FILE__).DS.'legacy'.DS.'user.php');
// Register class for the database, depends on which db type has been selected for use
$dbtype = $config->getValue('config.dbtype', 'mysql');
JLoader::register('database' , dirname(__FILE__).DS.'legacy'.DS.$dbtype.'.php');
/**
* Legacy define, _ISO define not used anymore. All output is forced as utf-8.
* @deprecated As of version 1.5
*/
define('_ISO','charset=utf-8');
/**
* Legacy constant, use _JEXEC instead
* @deprecated As of version 1.5
*/
define( '_VALID_MOS', 1 );
/**
* Legacy constant, use _JEXEC instead
* @deprecated As of version 1.5
*/
define( '_MOS_MAMBO_INCLUDED', 1 );
/**
* Legacy constant, use DATE_FORMAT_LC instead
* @deprecated As of version 1.5
*/
DEFINE('_DATE_FORMAT_LC', JText::_('DATE_FORMAT_LC1') ); //Uses PHP's strftime Command Format
/**
* Legacy constant, use DATE_FORMAT_LC2 instead
* @deprecated As of version 1.5
*/
DEFINE('_DATE_FORMAT_LC2', JText::_('DATE_FORMAT_LC2'));
/**
* Legacy constant, use JFilterInput instead
* @deprecated As of version 1.5
*/
DEFINE( "_MOS_NOTRIM", 0x0001 );
/**
* Legacy constant, use JFilterInput instead
* @deprecated As of version 1.5
*/
DEFINE( "_MOS_ALLOWHTML", 0x0002 );
/**
* Legacy constant, use JFilterInput instead
* @deprecated As of version 1.5
*/
DEFINE( "_MOS_ALLOWRAW", 0x0004 );
/**
* Legacy global, use JVersion->getLongVersion() instead
* @name $_VERSION
* @deprecated As of version 1.5
*/
$GLOBALS['_VERSION'] = new JVersion();
$version = $GLOBALS['_VERSION']->getLongVersion();
/**
* Legacy global, use JFactory::getDBO() instead
* @name $database
* @deprecated As of version 1.5
*/
$conf =& JFactory::getConfig();
$GLOBALS['database'] = new database($conf->getValue('config.host'), $conf->getValue('config.user'), $conf->getValue('config.password'), $conf->getValue('config.db'), $conf->getValue('config.dbprefix'));
$GLOBALS['database']->debug($conf->getValue('config.debug'));
/**
* Legacy global, use JFactory::getUser() [JUser object] instead
* @name $my
* @deprecated As of version 1.5
*/
$user =& JFactory::getUser();
$GLOBALS['my'] = (object)$user->getProperties();
$GLOBALS['my']->gid = $user->get('aid', 0);
/**
* Insert configuration values into global scope (for backwards compatibility)
* @deprecated As of version 1.5
*/
$temp = new JConfig;
foreach (get_object_vars($temp) as $k => $v) {
$name = 'mosConfig_'.$k;
$GLOBALS[$name] = $v;
}
$GLOBALS['mosConfig_live_site'] = substr_replace(JURI::root(), '', -1, 1);
$GLOBALS['mosConfig_absolute_path'] = JPATH_SITE;
$GLOBALS['mosConfig_cachepath'] = JPATH_BASE.DS.'cache';
$GLOBALS['mosConfig_offset_user'] = 0;
$lang =& JFactory::getLanguage();
$GLOBALS['mosConfig_lang'] = $lang->getBackwardLang();
$config->setValue('config.live_site', $GLOBALS['mosConfig_live_site']);
$config->setValue('config.absolute_path', $GLOBALS['mosConfig_absolute_path']);
$config->setValue('config.lang', $GLOBALS['mosConfig_lang']);
/**
* Legacy global, use JFactory::getUser() instead
* @name $acl
* @deprecated As of version 1.5
*/
$acl =& JFactory::getACL();
// Legacy ACL's for backward compat
$acl->addACL( 'administration', 'edit', 'users', 'super administrator', 'components', 'all' );
$acl->addACL( 'administration', 'edit', 'users', 'administrator', 'components', 'all' );
$acl->addACL( 'administration', 'edit', 'users', 'super administrator', 'user properties', 'block_user' );
$acl->addACL( 'administration', 'manage', 'users', 'super administrator', 'components', 'com_users' );
$acl->addACL( 'administration', 'manage', 'users', 'administrator', 'components', 'com_users' );
$acl->addACL( 'administration', 'config', 'users', 'super administrator' );
//$acl->addACL( 'administration', 'config', 'users', 'administrator' );
$acl->addACL( 'action', 'add', 'users', 'author', 'content', 'all' );
$acl->addACL( 'action', 'add', 'users', 'editor', 'content', 'all' );
$acl->addACL( 'action', 'add', 'users', 'publisher', 'content', 'all' );
$acl->addACL( 'action', 'edit', 'users', 'author', 'content', 'own' );
$acl->addACL( 'action', 'edit', 'users', 'editor', 'content', 'all' );
$acl->addACL( 'action', 'edit', 'users', 'publisher', 'content', 'all' );
$acl->addACL( 'action', 'publish', 'users', 'publisher', 'content', 'all' );
$acl->addACL( 'action', 'add', 'users', 'manager', 'content', 'all' );
$acl->addACL( 'action', 'edit', 'users', 'manager', 'content', 'all' );
$acl->addACL( 'action', 'publish', 'users', 'manager', 'content', 'all' );
$acl->addACL( 'action', 'add', 'users', 'administrator', 'content', 'all' );
$acl->addACL( 'action', 'edit', 'users', 'administrator', 'content', 'all' );
$acl->addACL( 'action', 'publish', 'users', 'administrator', 'content', 'all' );
$acl->addACL( 'action', 'add', 'users', 'super administrator', 'content', 'all' );
$acl->addACL( 'action', 'edit', 'users', 'super administrator', 'content', 'all' );
$acl->addACL( 'action', 'publish', 'users', 'super administrator', 'content', 'all' );
$acl->addACL( 'com_syndicate', 'manage', 'users', 'super administrator' );
$acl->addACL( 'com_syndicate', 'manage', 'users', 'administrator' );
$acl->addACL( 'com_syndicate', 'manage', 'users', 'manager' );
$GLOBALS['acl'] =& $acl;
/**
* Legacy global
* @name $task
* @deprecated As of version 1.5
*/
$GLOBALS['task'] = JRequest::getString('task');
/**
* Load the site language file (the old way - to be deprecated)
* @deprecated As of version 1.5
*/
global $mosConfig_lang;
$mosConfig_lang = JFilterInput::clean($mosConfig_lang, 'cmd');
$file = JPATH_SITE.DS.'language'.DS.$mosConfig_lang.'.php';
if (file_exists( $file )) {
require_once( $file);
} else {
$file = JPATH_SITE.DS.'language'.DS.'english.php';
if (file_exists( $file )) {
require_once( $file );
}
}
/**
* Legacy global
* use JApplicaiton->registerEvent and JApplication->triggerEvent for event handling
* use JPlugingHelper::importPlugin to load bot code
* @deprecated As of version 1.5
*/
$GLOBALS['_MAMBOTS'] = new mosMambotHandler();
}
function onAfterRoute()
{
global $mainframe;
if ($mainframe->isAdmin()) {
return;
}
switch(JRequest::getCmd('option'))
{
case 'com_content' :
$this->routeContent();
break;
case 'com_newsfeeds' :
$this->routeNewsfeeds();
break;
case 'com_weblinks' :
$this->routeWeblinks();
break;
case 'com_frontpage' :
JRequest::setVar('option', 'com_content');
JRequest::setVar('view', 'frontpage');
break;
case 'com_login' :
JRequest::setVar('option', 'com_user');
JRequest::setVar('view', 'login');
break;
case 'com_registration' :
JRequest::setVar('option', 'com_user');
JRequest::setVar('view', 'register');
break;
}
/**
* Legacy global, use JApplication::getTemplate() instead
* @name $cur_template
* @deprecated As of version 1.5
*/
$GLOBALS['cur_template'] = $mainframe->getTemplate();
}
function routeContent()
{
$viewName = JRequest::getCmd( 'view', 'article' );
$layout = JRequest::getCmd( 'layout', 'default' );
// interceptors to support legacy urls
switch( JRequest::getCmd('task'))
{
//index.php?option=com_content&task=x&id=x&Itemid=x
case 'blogsection':
$viewName = 'section';
$layout = 'blog';
break;
case 'section':
$viewName = 'section';
break;
case 'category':
$viewName = 'category';
break;
case 'blogcategory':
$viewName = 'category';
$layout = 'blog';
break;
case 'archivesection':
case 'archivecategory':
$viewName = 'archive';
break;
case 'frontpage' :
$viewName = 'frontpage';
break;
case 'view':
$viewName = 'article';
break;
}
JRequest::setVar('layout', $layout);
JRequest::setVar('view', $viewName);
}
function routeNewsfeeds()
{
$viewName = JRequest::getCmd( 'view', 'categories' );
// interceptors to support legacy urls
switch( JRequest::getCmd('task'))
{
//index.php?option=com_newsfeeds&task=x&catid=xid=x&Itemid=x
case 'view':
$viewName = 'newsfeed';
break;
default:
{
if(JRequest::getInt('catid') && !JRequest::getCmd('view')) {
$viewName = 'category';
}
}
}
JRequest::setVar('view', $viewName);
}
function routeWeblinks()
{
$viewName = JRequest::getCmd( 'view', 'categories' );
// interceptors to support legacy urls
switch( JRequest::getCmd('task'))
{
//index.php?option=com_weblinks&task=x&catid=xid=x
case 'view':
$viewName = 'weblink';
break;
default:
{
if(($catid = JRequest::getInt('catid')) && !JRequest::getCmd('view')) {
$viewName = 'category';
JRequest::setVar('id', $catid);
}
}
}
JRequest::setVar('view', $viewName);
}
} | google-code/administradora-beraca | plugins/system/legacy.php | PHP | gpl-2.0 | 13,245 |
def spaceship_building(cans):
total_cans = 0
for week in range(1,53):
total_cans = total_cans + cans
print('Week %s = %s cans' % (week, total_cans))
spaceship_building(2)
spaceship_building(13) | erikdejonge/python_for_kids | chapter07/spaceship_building.py | Python | gpl-2.0 | 227 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-24 15:28
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('emailer', '0007_auto_20150509_1922'),
]
operations = [
migrations.AlterField(
model_name='email',
name='recipient',
field=models.EmailField(db_index=True, max_length=254),
),
]
| JustinWingChungHui/okKindred | emailer/migrations/0008_auto_20151224_1528.py | Python | gpl-2.0 | 467 |
/* $Id: VBoxGuest-win.cpp $ */
/** @file
* VBoxGuest - Windows specifics.
*/
/*
* Copyright (C) 2010-2015 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#define LOG_GROUP LOG_GROUP_SUP_DRV
#include "VBoxGuest-win.h"
#include "VBoxGuestInternal.h"
#include <iprt/asm.h>
#include <iprt/asm-amd64-x86.h>
#include <VBox/log.h>
#include <VBox/VBoxGuestLib.h>
#include <iprt/string.h>
/*
* XP DDK #defines ExFreePool to ExFreePoolWithTag. The latter does not exist
* on NT4, so... The same for ExAllocatePool.
*/
#ifdef TARGET_NT4
# undef ExAllocatePool
# undef ExFreePool
#endif
/*******************************************************************************
* Internal Functions *
*******************************************************************************/
RT_C_DECLS_BEGIN
static NTSTATUS vbgdNtAddDevice(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj);
static void vbgdNtUnload(PDRIVER_OBJECT pDrvObj);
static NTSTATUS vbgdNtCreate(PDEVICE_OBJECT pDevObj, PIRP pIrp);
static NTSTATUS vbgdNtClose(PDEVICE_OBJECT pDevObj, PIRP pIrp);
static NTSTATUS vbgdNtIOCtl(PDEVICE_OBJECT pDevObj, PIRP pIrp);
static NTSTATUS vbgdNtInternalIOCtl(PDEVICE_OBJECT pDevObj, PIRP pIrp);
static NTSTATUS vbgdNtRegistryReadDWORD(ULONG ulRoot, PCWSTR pwszPath, PWSTR pwszName, PULONG puValue);
static NTSTATUS vbgdNtSystemControl(PDEVICE_OBJECT pDevObj, PIRP pIrp);
static NTSTATUS vbgdNtShutdown(PDEVICE_OBJECT pDevObj, PIRP pIrp);
static NTSTATUS vbgdNtNotSupportedStub(PDEVICE_OBJECT pDevObj, PIRP pIrp);
#ifdef DEBUG
static void vbgdNtDoTests(void);
#endif
RT_C_DECLS_END
/*******************************************************************************
* Exported Functions *
*******************************************************************************/
RT_C_DECLS_BEGIN
ULONG DriverEntry(PDRIVER_OBJECT pDrvObj, PUNICODE_STRING pRegPath);
RT_C_DECLS_END
#ifdef ALLOC_PRAGMA
# pragma alloc_text(INIT, DriverEntry)
# pragma alloc_text(PAGE, vbgdNtAddDevice)
# pragma alloc_text(PAGE, vbgdNtUnload)
# pragma alloc_text(PAGE, vbgdNtCreate)
# pragma alloc_text(PAGE, vbgdNtClose)
# pragma alloc_text(PAGE, vbgdNtShutdown)
# pragma alloc_text(PAGE, vbgdNtNotSupportedStub)
# pragma alloc_text(PAGE, vbgdNtScanPCIResourceList)
#endif
/*******************************************************************************
* Global Variables *
*******************************************************************************/
/** The detected NT (windows) version. */
VBGDNTVER g_enmVbgdNtVer = VBGDNTVER_INVALID;
/**
* Driver entry point.
*
* @returns appropriate status code.
* @param pDrvObj Pointer to driver object.
* @param pRegPath Registry base path.
*/
ULONG DriverEntry(PDRIVER_OBJECT pDrvObj, PUNICODE_STRING pRegPath)
{
NTSTATUS rc = STATUS_SUCCESS;
LogFunc(("Driver built: %s %s\n", __DATE__, __TIME__));
/*
* Check if the the NT version is supported and initializing
* g_enmVbgdNtVer in the process.
*/
ULONG ulMajorVer;
ULONG ulMinorVer;
ULONG ulBuildNo;
BOOLEAN fCheckedBuild = PsGetVersion(&ulMajorVer, &ulMinorVer, &ulBuildNo, NULL);
/* Use RTLogBackdoorPrintf to make sure that this goes to VBox.log */
RTLogBackdoorPrintf("VBoxGuest: Windows version %u.%u, build %u\n", ulMajorVer, ulMinorVer, ulBuildNo);
if (fCheckedBuild)
RTLogBackdoorPrintf("VBoxGuest: Windows checked build\n");
#ifdef DEBUG
vbgdNtDoTests();
#endif
switch (ulMajorVer)
{
case 10:
switch (ulMinorVer)
{
case 0:
/* Windows 10 Preview builds starting with 9926. */
default:
/* Also everything newer. */
g_enmVbgdNtVer = VBGDNTVER_WIN10;
break;
}
break;
case 6: /* Windows Vista or Windows 7 (based on minor ver) */
switch (ulMinorVer)
{
case 0: /* Note: Also could be Windows 2008 Server! */
g_enmVbgdNtVer = VBGDNTVER_WINVISTA;
break;
case 1: /* Note: Also could be Windows 2008 Server R2! */
g_enmVbgdNtVer = VBGDNTVER_WIN7;
break;
case 2:
g_enmVbgdNtVer = VBGDNTVER_WIN8;
break;
case 3:
g_enmVbgdNtVer = VBGDNTVER_WIN81;
break;
case 4:
/* Windows 10 Preview builds. */
default:
/* Also everything newer. */
g_enmVbgdNtVer = VBGDNTVER_WIN10;
break;
}
break;
case 5:
switch (ulMinorVer)
{
default:
case 2:
g_enmVbgdNtVer = VBGDNTVER_WIN2K3;
break;
case 1:
g_enmVbgdNtVer = VBGDNTVER_WINXP;
break;
case 0:
g_enmVbgdNtVer = VBGDNTVER_WIN2K;
break;
}
break;
case 4:
g_enmVbgdNtVer = VBGDNTVER_WINNT4;
break;
default:
if (ulMajorVer > 6)
{
/* "Windows 10 mode" for Windows 8.1+. */
g_enmVbgdNtVer = VBGDNTVER_WIN10;
}
else
{
if (ulMajorVer < 4)
LogRelFunc(("At least Windows NT4 required! (%u.%u)\n", ulMajorVer, ulMinorVer));
else
LogRelFunc(("Unknown version %u.%u!\n", ulMajorVer, ulMinorVer));
rc = STATUS_DRIVER_UNABLE_TO_LOAD;
}
break;
}
if (NT_SUCCESS(rc))
{
/*
* Setup the driver entry points in pDrvObj.
*/
pDrvObj->DriverUnload = vbgdNtUnload;
pDrvObj->MajorFunction[IRP_MJ_CREATE] = vbgdNtCreate;
pDrvObj->MajorFunction[IRP_MJ_CLOSE] = vbgdNtClose;
pDrvObj->MajorFunction[IRP_MJ_DEVICE_CONTROL] = vbgdNtIOCtl;
pDrvObj->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] = vbgdNtInternalIOCtl;
pDrvObj->MajorFunction[IRP_MJ_SHUTDOWN] = vbgdNtShutdown;
pDrvObj->MajorFunction[IRP_MJ_READ] = vbgdNtNotSupportedStub;
pDrvObj->MajorFunction[IRP_MJ_WRITE] = vbgdNtNotSupportedStub;
#ifdef TARGET_NT4
rc = vbgdNt4CreateDevice(pDrvObj, NULL /* pDevObj */, pRegPath);
#else
pDrvObj->MajorFunction[IRP_MJ_PNP] = vbgdNtPnP;
pDrvObj->MajorFunction[IRP_MJ_POWER] = vbgdNtPower;
pDrvObj->MajorFunction[IRP_MJ_SYSTEM_CONTROL] = vbgdNtSystemControl;
pDrvObj->DriverExtension->AddDevice = (PDRIVER_ADD_DEVICE)vbgdNtAddDevice;
#endif
}
LogFlowFunc(("Returning %#x\n", rc));
return rc;
}
#ifndef TARGET_NT4
/**
* Handle request from the Plug & Play subsystem.
*
* @returns NT status code
* @param pDrvObj Driver object
* @param pDevObj Device object
*/
static NTSTATUS vbgdNtAddDevice(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj)
{
NTSTATUS rc;
LogFlowFuncEnter();
/*
* Create device.
*/
UNICODE_STRING DevName;
RtlInitUnicodeString(&DevName, VBOXGUEST_DEVICE_NAME_NT);
PDEVICE_OBJECT pDeviceObject = NULL;
rc = IoCreateDevice(pDrvObj, sizeof(VBOXGUESTDEVEXTWIN), &DevName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDeviceObject);
if (NT_SUCCESS(rc))
{
/*
* Create symbolic link (DOS devices).
*/
UNICODE_STRING DosName;
RtlInitUnicodeString(&DosName, VBOXGUEST_DEVICE_NAME_DOS);
rc = IoCreateSymbolicLink(&DosName, &DevName);
if (NT_SUCCESS(rc))
{
/*
* Setup the device extension.
*/
PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDeviceObject->DeviceExtension;
RT_ZERO(*pDevExt);
KeInitializeSpinLock(&pDevExt->MouseEventAccessLock);
pDevExt->pDeviceObject = pDeviceObject;
pDevExt->prevDevState = STOPPED;
pDevExt->devState = STOPPED;
pDevExt->pNextLowerDriver = IoAttachDeviceToDeviceStack(pDeviceObject, pDevObj);
if (pDevExt->pNextLowerDriver != NULL)
{
/*
* If we reached this point we're fine with the basic driver setup,
* so continue to init our own things.
*/
#ifdef VBOX_WITH_GUEST_BUGCHECK_DETECTION
vbgdNtBugCheckCallback(pDevExt); /* Ignore failure! */
#endif
if (NT_SUCCESS(rc))
{
/* VBoxGuestPower is pageable; ensure we are not called at elevated IRQL */
pDeviceObject->Flags |= DO_POWER_PAGABLE;
/* Driver is ready now. */
pDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING;
LogFlowFunc(("Returning with rc=0x%x (success)\n", rc));
return rc;
}
IoDetachDevice(pDevExt->pNextLowerDriver);
}
else
{
LogFunc(("IoAttachDeviceToDeviceStack did not give a nextLowerDriver!\n"));
rc = STATUS_DEVICE_NOT_CONNECTED;
}
/* bail out */
IoDeleteSymbolicLink(&DosName);
}
else
LogFunc(("IoCreateSymbolicLink failed with rc=%#x!\n", rc));
IoDeleteDevice(pDeviceObject);
}
else
LogFunc(("IoCreateDevice failed with rc=%#x!\n", rc));
LogFunc(("Returning with rc=0x%x\n", rc));
return rc;
}
#endif
/**
* Debug helper to dump a device resource list.
*
* @param pResourceList list of device resources.
*/
static void vbgdNtShowDeviceResources(PCM_PARTIAL_RESOURCE_LIST pResourceList)
{
#ifdef LOG_ENABLED
PCM_PARTIAL_RESOURCE_DESCRIPTOR pResource = pResourceList->PartialDescriptors;
ULONG cResources = pResourceList->Count;
for (ULONG i = 0; i < cResources; ++i, ++pResource)
{
ULONG uType = pResource->Type;
static char const * const s_apszName[] =
{
"CmResourceTypeNull",
"CmResourceTypePort",
"CmResourceTypeInterrupt",
"CmResourceTypeMemory",
"CmResourceTypeDma",
"CmResourceTypeDeviceSpecific",
"CmResourceTypeBusNumber",
"CmResourceTypeDevicePrivate",
"CmResourceTypeAssignedResource",
"CmResourceTypeSubAllocateFrom",
};
LogFunc(("Type=%s", uType < RT_ELEMENTS(s_apszName) ? s_apszName[uType] : "Unknown"));
switch (uType)
{
case CmResourceTypePort:
case CmResourceTypeMemory:
LogFunc(("Start %8X%8.8lX, length=%X\n",
pResource->u.Port.Start.HighPart, pResource->u.Port.Start.LowPart,
pResource->u.Port.Length));
break;
case CmResourceTypeInterrupt:
LogFunc(("Level=%X, vector=%X, affinity=%X\n",
pResource->u.Interrupt.Level, pResource->u.Interrupt.Vector,
pResource->u.Interrupt.Affinity));
break;
case CmResourceTypeDma:
LogFunc(("Channel %d, Port %X\n",
pResource->u.Dma.Channel, pResource->u.Dma.Port));
break;
default:
LogFunc(("\n"));
break;
}
}
#endif
}
/**
* Global initialisation stuff (PnP + NT4 legacy).
*
* @param pDevObj Device object.
* @param pIrp Request packet.
*/
#ifndef TARGET_NT4
NTSTATUS vbgdNtInit(PDEVICE_OBJECT pDevObj, PIRP pIrp)
#else
NTSTATUS vbgdNtInit(PDRIVER_OBJECT pDrvObj, PDEVICE_OBJECT pDevObj, PUNICODE_STRING pRegPath)
#endif
{
PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
#ifndef TARGET_NT4
PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
#endif
LogFlowFuncEnter();
int rc = STATUS_SUCCESS; /** @todo r=bird: s/rc/rcNt/ and s/int/NTSTATUS/. gee. */
#ifdef TARGET_NT4
/*
* Let's have a look at what our PCI adapter offers.
*/
LogFlowFunc(("Starting to scan PCI resources of VBoxGuest ...\n"));
/* Assign the PCI resources. */
PCM_RESOURCE_LIST pResourceList = NULL;
UNICODE_STRING classNameString;
RtlInitUnicodeString(&classNameString, L"VBoxGuestAdapter");
rc = HalAssignSlotResources(pRegPath, &classNameString,
pDrvObj, pDevObj,
PCIBus, pDevExt->busNumber, pDevExt->slotNumber,
&pResourceList);
if (pResourceList && pResourceList->Count > 0)
vbgdNtShowDeviceResources(&pResourceList->List[0].PartialResourceList);
if (NT_SUCCESS(rc))
rc = vbgdNtScanPCIResourceList(pResourceList, pDevExt);
#else
if (pStack->Parameters.StartDevice.AllocatedResources->Count > 0)
vbgdNtShowDeviceResources(&pStack->Parameters.StartDevice.AllocatedResources->List[0].PartialResourceList);
if (NT_SUCCESS(rc))
rc = vbgdNtScanPCIResourceList(pStack->Parameters.StartDevice.AllocatedResourcesTranslated, pDevExt);
#endif
if (NT_SUCCESS(rc))
{
/*
* Map physical address of VMMDev memory into MMIO region
* and init the common device extension bits.
*/
void *pvMMIOBase = NULL;
uint32_t cbMMIO = 0;
rc = vbgdNtMapVMMDevMemory(pDevExt,
pDevExt->vmmDevPhysMemoryAddress,
pDevExt->vmmDevPhysMemoryLength,
&pvMMIOBase,
&cbMMIO);
if (NT_SUCCESS(rc))
{
pDevExt->Core.pVMMDevMemory = (VMMDevMemory *)pvMMIOBase;
LogFunc(("pvMMIOBase=0x%p, pDevExt=0x%p, pDevExt->Core.pVMMDevMemory=0x%p\n",
pvMMIOBase, pDevExt, pDevExt ? pDevExt->Core.pVMMDevMemory : NULL));
int vrc = VbgdCommonInitDevExt(&pDevExt->Core,
pDevExt->Core.IOPortBase,
pvMMIOBase, cbMMIO,
vbgdNtVersionToOSType(g_enmVbgdNtVer),
VMMDEV_EVENT_MOUSE_POSITION_CHANGED);
if (RT_FAILURE(vrc))
{
LogFunc(("Could not init device extension, rc=%Rrc\n", vrc));
rc = STATUS_DEVICE_CONFIGURATION_ERROR;
}
}
else
LogFunc(("Could not map physical address of VMMDev, rc=0x%x\n", rc));
}
if (NT_SUCCESS(rc))
{
int vrc = VbglGRAlloc((VMMDevRequestHeader **)&pDevExt->pPowerStateRequest,
sizeof(VMMDevPowerStateRequest), VMMDevReq_SetPowerStatus);
if (RT_FAILURE(vrc))
{
LogFunc(("Alloc for pPowerStateRequest failed, rc=%Rrc\n", vrc));
rc = STATUS_UNSUCCESSFUL;
}
}
if (NT_SUCCESS(rc))
{
/*
* Register DPC and ISR.
*/
LogFlowFunc(("Initializing DPC/ISR ...\n"));
IoInitializeDpcRequest(pDevExt->pDeviceObject, vbgdNtDpcHandler);
#ifdef TARGET_NT4
ULONG uInterruptVector;
KIRQL irqLevel;
/* Get an interrupt vector. */
/* Only proceed if the device provides an interrupt. */
if ( pDevExt->interruptLevel
|| pDevExt->interruptVector)
{
LogFlowFunc(("Getting interrupt vector (HAL): Bus=%u, IRQL=%u, Vector=%u\n",
pDevExt->busNumber, pDevExt->interruptLevel, pDevExt->interruptVector));
uInterruptVector = HalGetInterruptVector(PCIBus,
pDevExt->busNumber,
pDevExt->interruptLevel,
pDevExt->interruptVector,
&irqLevel,
&pDevExt->interruptAffinity);
LogFlowFunc(("HalGetInterruptVector returns vector=%u\n", uInterruptVector));
if (uInterruptVector == 0)
LogFunc(("No interrupt vector found!\n"));
}
else
LogFunc(("Device does not provide an interrupt!\n"));
#endif
if (pDevExt->interruptVector)
{
LogFlowFunc(("Connecting interrupt ...\n"));
rc = IoConnectInterrupt(&pDevExt->pInterruptObject, /* Out: interrupt object. */
(PKSERVICE_ROUTINE)vbgdNtIsrHandler, /* Our ISR handler. */
pDevExt, /* Device context. */
NULL, /* Optional spinlock. */
#ifdef TARGET_NT4
uInterruptVector, /* Interrupt vector. */
irqLevel, /* Interrupt level. */
irqLevel, /* Interrupt level. */
#else
pDevExt->interruptVector, /* Interrupt vector. */
(KIRQL)pDevExt->interruptLevel, /* Interrupt level. */
(KIRQL)pDevExt->interruptLevel, /* Interrupt level. */
#endif
pDevExt->interruptMode, /* LevelSensitive or Latched. */
TRUE, /* Shareable interrupt. */
pDevExt->interruptAffinity, /* CPU affinity. */
FALSE); /* Don't save FPU stack. */
if (NT_ERROR(rc))
LogFunc(("Could not connect interrupt, rc=0x%x\n", rc));
}
else
LogFunc(("No interrupt vector found!\n"));
}
#ifdef VBOX_WITH_HGCM
LogFunc(("Allocating kernel session data ...\n"));
int vrc = VbgdCommonCreateKernelSession(&pDevExt->Core, &pDevExt->pKernelSession);
if (RT_FAILURE(vrc))
{
LogFunc(("Failed to allocated kernel session data, rc=%Rrc\n", rc));
rc = STATUS_UNSUCCESSFUL;
}
#endif
if (RT_SUCCESS(rc))
{
ULONG ulValue = 0;
NTSTATUS rcNt = vbgdNtRegistryReadDWORD(RTL_REGISTRY_SERVICES,
L"VBoxGuest", L"LoggingEnabled", &ulValue);
if (NT_SUCCESS(rcNt))
{
pDevExt->Core.fLoggingEnabled = ulValue >= 0xFF;
if (pDevExt->Core.fLoggingEnabled)
LogRelFunc(("Logging to host log enabled (0x%x)", ulValue));
}
/* Ready to rumble! */
LogRelFunc(("Device is ready!\n"));
VBOXGUEST_UPDATE_DEVSTATE(pDevExt, WORKING);
}
else
pDevExt->pInterruptObject = NULL;
/** @todo r=bird: The error cleanup here is completely missing. We'll leak a
* whole bunch of things... */
LogFunc(("Returned with rc=0x%x\n", rc));
return rc;
}
/**
* Cleans up hardware resources.
* Do not delete DevExt here.
*
* @param pDrvObj Driver object.
*/
NTSTATUS vbgdNtCleanup(PDEVICE_OBJECT pDevObj)
{
LogFlowFuncEnter();
PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
if (pDevExt)
{
#if 0 /* @todo: test & enable cleaning global session data */
#ifdef VBOX_WITH_HGCM
if (pDevExt->pKernelSession)
{
VbgdCommonCloseSession(pDevExt, pDevExt->pKernelSession);
pDevExt->pKernelSession = NULL;
}
#endif
#endif
if (pDevExt->pInterruptObject)
{
IoDisconnectInterrupt(pDevExt->pInterruptObject);
pDevExt->pInterruptObject = NULL;
}
/** @todo: cleanup the rest stuff */
#ifdef VBOX_WITH_GUEST_BUGCHECK_DETECTION
hlpDeregisterBugCheckCallback(pDevExt); /* ignore failure! */
#endif
/* According to MSDN we have to unmap previously mapped memory. */
vbgdNtUnmapVMMDevMemory(pDevExt);
}
return STATUS_SUCCESS;
}
/**
* Unload the driver.
*
* @param pDrvObj Driver object.
*/
static void vbgdNtUnload(PDRIVER_OBJECT pDrvObj)
{
LogFlowFuncEnter();
#ifdef TARGET_NT4
vbgdNtCleanup(pDrvObj->DeviceObject);
/* Destroy device extension and clean up everything else. */
if (pDrvObj->DeviceObject && pDrvObj->DeviceObject->DeviceExtension)
VbgdCommonDeleteDevExt((PVBOXGUESTDEVEXT)pDrvObj->DeviceObject->DeviceExtension);
/*
* I don't think it's possible to unload a driver which processes have
* opened, at least we'll blindly assume that here.
*/
UNICODE_STRING DosName;
RtlInitUnicodeString(&DosName, VBOXGUEST_DEVICE_NAME_DOS);
NTSTATUS rc = IoDeleteSymbolicLink(&DosName);
IoDeleteDevice(pDrvObj->DeviceObject);
#else /* !TARGET_NT4 */
/* On a PnP driver this routine will be called after
* IRP_MN_REMOVE_DEVICE (where we already did the cleanup),
* so don't do anything here (yet). */
#endif /* !TARGET_NT4 */
LogFlowFunc(("Returning\n"));
}
/**
* Create (i.e. Open) file entry point.
*
* @param pDevObj Device object.
* @param pIrp Request packet.
*/
static NTSTATUS vbgdNtCreate(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
/** @todo AssertPtrReturn(pIrp); */
PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
/** @todo AssertPtrReturn(pStack); */
PFILE_OBJECT pFileObj = pStack->FileObject;
PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
NTSTATUS rc = STATUS_SUCCESS;
if (pDevExt->devState != WORKING)
{
LogFunc(("Device is not working currently, state=%d\n", pDevExt->devState));
rc = STATUS_UNSUCCESSFUL;
}
else if (pStack->Parameters.Create.Options & FILE_DIRECTORY_FILE)
{
/*
* We are not remotely similar to a directory...
* (But this is possible.)
*/
LogFlowFunc(("Uhm, we're not a directory!\n"));
rc = STATUS_NOT_A_DIRECTORY;
}
else
{
#ifdef VBOX_WITH_HGCM
if (pFileObj)
{
LogFlowFunc(("File object type=%d\n", pFileObj->Type));
int vrc;
PVBOXGUESTSESSION pSession;
if (pFileObj->Type == 5 /* File Object */)
{
/*
* Create a session object if we have a valid file object. This session object
* exists for every R3 process.
*/
vrc = VbgdCommonCreateUserSession(&pDevExt->Core, &pSession);
}
else
{
/* ... otherwise we've been called from R0! */
vrc = VbgdCommonCreateKernelSession(&pDevExt->Core, &pSession);
}
if (RT_SUCCESS(vrc))
pFileObj->FsContext = pSession;
}
#endif
}
/* Complete the request! */
pIrp->IoStatus.Information = 0;
pIrp->IoStatus.Status = rc;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
LogFlowFunc(("Returning rc=0x%x\n", rc));
return rc;
}
/**
* Close file entry point.
*
* @param pDevObj Device object.
* @param pIrp Request packet.
*/
static NTSTATUS vbgdNtClose(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
PFILE_OBJECT pFileObj = pStack->FileObject;
LogFlowFunc(("pDevExt=0x%p, pFileObj=0x%p, FsContext=0x%p\n",
pDevExt, pFileObj, pFileObj->FsContext));
#ifdef VBOX_WITH_HGCM
/* Close both, R0 and R3 sessions. */
PVBOXGUESTSESSION pSession = (PVBOXGUESTSESSION)pFileObj->FsContext;
if (pSession)
VbgdCommonCloseSession(&pDevExt->Core, pSession);
#endif
pFileObj->FsContext = NULL;
pIrp->IoStatus.Information = 0;
pIrp->IoStatus.Status = STATUS_SUCCESS;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
/**
* Device I/O Control entry point.
*
* @param pDevObj Device object.
* @param pIrp Request packet.
*/
static NTSTATUS vbgdNtIOCtl(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
NTSTATUS Status = STATUS_SUCCESS;
PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
unsigned int uCmd = (unsigned int)pStack->Parameters.DeviceIoControl.IoControlCode;
char *pBuf = (char *)pIrp->AssociatedIrp.SystemBuffer; /* All requests are buffered. */
size_t cbData = pStack->Parameters.DeviceIoControl.InputBufferLength;
size_t cbOut = 0;
/* Do we have a file object associated?*/
PFILE_OBJECT pFileObj = pStack->FileObject;
PVBOXGUESTSESSION pSession = NULL;
if (pFileObj) /* ... then we might have a session object as well! */
pSession = (PVBOXGUESTSESSION)pFileObj->FsContext;
LogFlowFunc(("uCmd=%u, pDevExt=0x%p, pSession=0x%p\n",
uCmd, pDevExt, pSession));
/* We don't have a session associated with the file object? So this seems
* to be a kernel call then. */
/** @todo r=bird: What on earth is this supposed to be? Each kernel session
* shall have its own context of course, no hacks, pleeease. */
if (pSession == NULL)
{
LogFunc(("XXX: BUGBUG: FIXME: Using ugly kernel session data hack ...\n"));
#ifdef DEBUG_andy
RTLogBackdoorPrintf("XXX: BUGBUG: FIXME: Using ugly kernel session data hack ... Please don't forget to fix this one, Andy!\n");
#endif
pSession = pDevExt->pKernelSession;
}
/* Verify that it's a buffered CTL. */
if ((pStack->Parameters.DeviceIoControl.IoControlCode & 0x3) == METHOD_BUFFERED)
{
/*
* Process the common IOCtls.
*/
size_t cbDataReturned;
int vrc = VbgdCommonIoCtl(uCmd, &pDevExt->Core, pSession, pBuf, cbData, &cbDataReturned);
LogFlowFunc(("rc=%Rrc, pBuf=0x%p, cbData=%u, cbDataReturned=%u\n",
vrc, pBuf, cbData, cbDataReturned));
if (RT_SUCCESS(vrc))
{
if (RT_UNLIKELY( cbDataReturned > cbData
|| cbDataReturned > pStack->Parameters.DeviceIoControl.OutputBufferLength))
{
LogFunc(("Too much output data %u - expected %u!\n", cbDataReturned, cbData));
cbDataReturned = cbData;
Status = STATUS_BUFFER_TOO_SMALL;
}
if (cbDataReturned > 0)
cbOut = cbDataReturned;
}
else
{
if ( vrc == VERR_NOT_SUPPORTED
|| vrc == VERR_INVALID_PARAMETER)
Status = STATUS_INVALID_PARAMETER;
else if (vrc == VERR_OUT_OF_RANGE)
Status = STATUS_INVALID_BUFFER_SIZE;
else
Status = STATUS_UNSUCCESSFUL;
}
}
else
{
LogFunc(("Not buffered request (%#x) - not supported\n", pStack->Parameters.DeviceIoControl.IoControlCode));
Status = STATUS_NOT_SUPPORTED;
}
pIrp->IoStatus.Status = Status;
pIrp->IoStatus.Information = cbOut;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
//LogFlowFunc(("Returned cbOut=%d rc=%#x\n", cbOut, Status));
return Status;
}
/**
* Internal Device I/O Control entry point.
*
* @param pDevObj Device object.
* @param pIrp Request packet.
*/
static NTSTATUS vbgdNtInternalIOCtl(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
NTSTATUS Status = STATUS_SUCCESS;
PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
unsigned int uCmd = (unsigned int)pStack->Parameters.DeviceIoControl.IoControlCode;
bool fProcessed = false;
unsigned Info = 0;
/*
* Override common behavior of some operations.
*/
/** @todo r=bird: Better to add dedicated worker functions for this! */
switch (uCmd)
{
case VBOXGUEST_IOCTL_SET_MOUSE_NOTIFY_CALLBACK:
{
PVOID pvBuf = pStack->Parameters.Others.Argument1;
size_t cbData = (size_t)pStack->Parameters.Others.Argument2;
fProcessed = true;
if (cbData != sizeof(VBoxGuestMouseSetNotifyCallback))
{
AssertFailed();
Status = STATUS_INVALID_PARAMETER;
break;
}
VBoxGuestMouseSetNotifyCallback *pInfo = (VBoxGuestMouseSetNotifyCallback*)pvBuf;
/* we need a lock here to avoid concurrency with the set event functionality */
KIRQL OldIrql;
KeAcquireSpinLock(&pDevExt->MouseEventAccessLock, &OldIrql);
pDevExt->Core.MouseNotifyCallback = *pInfo;
KeReleaseSpinLock(&pDevExt->MouseEventAccessLock, OldIrql);
Status = STATUS_SUCCESS;
break;
}
default:
break;
}
if (fProcessed)
{
pIrp->IoStatus.Status = Status;
pIrp->IoStatus.Information = Info;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
return Status;
}
/*
* No override, go to common code.
*/
return vbgdNtIOCtl(pDevObj, pIrp);
}
/**
* IRP_MJ_SYSTEM_CONTROL handler.
*
* @returns NT status code
* @param pDevObj Device object.
* @param pIrp IRP.
*/
NTSTATUS vbgdNtSystemControl(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
LogFlowFuncEnter();
/* Always pass it on to the next driver. */
IoSkipCurrentIrpStackLocation(pIrp);
return IoCallDriver(pDevExt->pNextLowerDriver, pIrp);
}
/**
* IRP_MJ_SHUTDOWN handler.
*
* @returns NT status code
* @param pDevObj Device object.
* @param pIrp IRP.
*/
NTSTATUS vbgdNtShutdown(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
LogFlowFuncEnter();
VMMDevPowerStateRequest *pReq = pDevExt->pPowerStateRequest;
if (pReq)
{
pReq->header.requestType = VMMDevReq_SetPowerStatus;
pReq->powerState = VMMDevPowerState_PowerOff;
int rc = VbglGRPerform(&pReq->header);
if (RT_FAILURE(rc))
LogFunc(("Error performing request to VMMDev, rc=%Rrc\n", rc));
}
return STATUS_SUCCESS;
}
/**
* Stub function for functions we don't implemented.
*
* @returns STATUS_NOT_SUPPORTED
* @param pDevObj Device object.
* @param pIrp IRP.
*/
NTSTATUS vbgdNtNotSupportedStub(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
LogFlowFuncEnter();
pIrp->IoStatus.Information = 0;
pIrp->IoStatus.Status = STATUS_NOT_SUPPORTED;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
return STATUS_NOT_SUPPORTED;
}
/**
* DPC handler.
*
* @param pDPC DPC descriptor.
* @param pDevObj Device object.
* @param pIrp Interrupt request packet.
* @param pContext Context specific pointer.
*/
void vbgdNtDpcHandler(PKDPC pDPC, PDEVICE_OBJECT pDevObj, PIRP pIrp, PVOID pContext)
{
PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pDevObj->DeviceExtension;
Log3Func(("pDevExt=0x%p\n", pDevExt));
/* Test & reset the counter. */
if (ASMAtomicXchgU32(&pDevExt->Core.u32MousePosChangedSeq, 0))
{
/* we need a lock here to avoid concurrency with the set event ioctl handler thread,
* i.e. to prevent the event from destroyed while we're using it */
Assert(KeGetCurrentIrql() == DISPATCH_LEVEL);
KeAcquireSpinLockAtDpcLevel(&pDevExt->MouseEventAccessLock);
if (pDevExt->Core.MouseNotifyCallback.pfnNotify)
pDevExt->Core.MouseNotifyCallback.pfnNotify(pDevExt->Core.MouseNotifyCallback.pvUser);
KeReleaseSpinLockFromDpcLevel(&pDevExt->MouseEventAccessLock);
}
/* Process the wake-up list we were asked by the scheduling a DPC
* in vbgdNtIsrHandler(). */
VbgdCommonWaitDoWakeUps(&pDevExt->Core);
}
/**
* ISR handler.
*
* @return BOOLEAN Indicates whether the IRQ came from us (TRUE) or not (FALSE).
* @param pInterrupt Interrupt that was triggered.
* @param pServiceContext Context specific pointer.
*/
BOOLEAN vbgdNtIsrHandler(PKINTERRUPT pInterrupt, PVOID pServiceContext)
{
PVBOXGUESTDEVEXTWIN pDevExt = (PVBOXGUESTDEVEXTWIN)pServiceContext;
if (pDevExt == NULL)
return FALSE;
/*Log3Func(("pDevExt=0x%p, pVMMDevMemory=0x%p\n", pDevExt, pDevExt ? pDevExt->pVMMDevMemory : NULL));*/
/* Enter the common ISR routine and do the actual work. */
BOOLEAN fIRQTaken = VbgdCommonISR(&pDevExt->Core);
/* If we need to wake up some events we do that in a DPC to make
* sure we're called at the right IRQL. */
if (fIRQTaken)
{
Log3Func(("IRQ was taken! pInterrupt=0x%p, pDevExt=0x%p\n", pInterrupt, pDevExt));
if (ASMAtomicUoReadU32( &pDevExt->Core.u32MousePosChangedSeq)
|| !RTListIsEmpty(&pDevExt->Core.WakeUpList))
{
Log3Func(("Requesting DPC ...\n"));
IoRequestDpc(pDevExt->pDeviceObject, pDevExt->pCurrentIrp, NULL);
}
}
return fIRQTaken;
}
/**
* Overridden routine for mouse polling events.
*
* @param pDevExt Device extension structure.
*/
void VbgdNativeISRMousePollEvent(PVBOXGUESTDEVEXT pDevExt)
{
NOREF(pDevExt);
/* nothing to do here - i.e. since we can not KeSetEvent from ISR level,
* we rely on the pDevExt->u32MousePosChangedSeq to be set to a non-zero value on a mouse event
* and queue the DPC in our ISR routine in that case doing KeSetEvent from the DPC routine */
}
/**
* Queries (gets) a DWORD value from the registry.
*
* @return NTSTATUS
* @param ulRoot Relative path root. See RTL_REGISTRY_SERVICES or RTL_REGISTRY_ABSOLUTE.
* @param pwszPath Path inside path root.
* @param pwszName Actual value name to look up.
* @param puValue On input this can specify the default value (if RTL_REGISTRY_OPTIONAL is
* not specified in ulRoot), on output this will retrieve the looked up
* registry value if found.
*/
NTSTATUS vbgdNtRegistryReadDWORD(ULONG ulRoot, PCWSTR pwszPath, PWSTR pwszName, PULONG puValue)
{
if (!pwszPath || !pwszName || !puValue)
return STATUS_INVALID_PARAMETER;
ULONG ulDefault = *puValue;
RTL_QUERY_REGISTRY_TABLE tblQuery[2];
RtlZeroMemory(tblQuery, sizeof(tblQuery));
/** @todo Add RTL_QUERY_REGISTRY_TYPECHECK! */
tblQuery[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
tblQuery[0].Name = pwszName;
tblQuery[0].EntryContext = puValue;
tblQuery[0].DefaultType = REG_DWORD;
tblQuery[0].DefaultData = &ulDefault;
tblQuery[0].DefaultLength = sizeof(ULONG);
return RtlQueryRegistryValues(ulRoot,
pwszPath,
&tblQuery[0],
NULL /* Context */,
NULL /* Environment */);
}
/**
* Helper to scan the PCI resource list and remember stuff.
*
* @param pResList Resource list
* @param pDevExt Device extension
*/
NTSTATUS vbgdNtScanPCIResourceList(PCM_RESOURCE_LIST pResList, PVBOXGUESTDEVEXTWIN pDevExt)
{
/* Enumerate the resource list. */
LogFlowFunc(("Found %d resources\n",
pResList->List->PartialResourceList.Count));
NTSTATUS rc = STATUS_SUCCESS;
PCM_PARTIAL_RESOURCE_DESCRIPTOR pPartialData = NULL;
ULONG rangeCount = 0;
ULONG cMMIORange = 0;
PVBOXGUESTWINBASEADDRESS pBaseAddress = pDevExt->pciBaseAddress;
for (ULONG i = 0; i < pResList->List->PartialResourceList.Count; i++)
{
pPartialData = &pResList->List->PartialResourceList.PartialDescriptors[i];
switch (pPartialData->Type)
{
case CmResourceTypePort:
{
/* Overflow protection. */
if (rangeCount < PCI_TYPE0_ADDRESSES)
{
LogFlowFunc(("I/O range: Base=%08x:%08x, length=%08x\n",
pPartialData->u.Port.Start.HighPart,
pPartialData->u.Port.Start.LowPart,
pPartialData->u.Port.Length));
/* Save the IO port base. */
/** @todo Not so good.
* Update/bird: What is not so good? That we just consider the last range? */
pDevExt->Core.IOPortBase = (RTIOPORT)pPartialData->u.Port.Start.LowPart;
/* Save resource information. */
pBaseAddress->RangeStart = pPartialData->u.Port.Start;
pBaseAddress->RangeLength = pPartialData->u.Port.Length;
pBaseAddress->RangeInMemory = FALSE;
pBaseAddress->ResourceMapped = FALSE;
LogFunc(("I/O range for VMMDev found! Base=%08x:%08x, length=%08x\n",
pPartialData->u.Port.Start.HighPart,
pPartialData->u.Port.Start.LowPart,
pPartialData->u.Port.Length));
/* Next item ... */
rangeCount++; pBaseAddress++;
}
break;
}
case CmResourceTypeInterrupt:
{
LogFunc(("Interrupt: Level=%x, vector=%x, mode=%x\n",
pPartialData->u.Interrupt.Level,
pPartialData->u.Interrupt.Vector,
pPartialData->Flags));
/* Save information. */
pDevExt->interruptLevel = pPartialData->u.Interrupt.Level;
pDevExt->interruptVector = pPartialData->u.Interrupt.Vector;
pDevExt->interruptAffinity = pPartialData->u.Interrupt.Affinity;
/* Check interrupt mode. */
if (pPartialData->Flags & CM_RESOURCE_INTERRUPT_LATCHED)
pDevExt->interruptMode = Latched;
else
pDevExt->interruptMode = LevelSensitive;
break;
}
case CmResourceTypeMemory:
{
/* Overflow protection. */
if (rangeCount < PCI_TYPE0_ADDRESSES)
{
LogFlowFunc(("Memory range: Base=%08x:%08x, length=%08x\n",
pPartialData->u.Memory.Start.HighPart,
pPartialData->u.Memory.Start.LowPart,
pPartialData->u.Memory.Length));
/* We only care about read/write memory. */
/** @todo Reconsider memory type. */
if ( cMMIORange == 0 /* Only care about the first MMIO range (!!!). */
&& (pPartialData->Flags & VBOX_CM_PRE_VISTA_MASK) == CM_RESOURCE_MEMORY_READ_WRITE)
{
/* Save physical MMIO base + length for VMMDev. */
pDevExt->vmmDevPhysMemoryAddress = pPartialData->u.Memory.Start;
pDevExt->vmmDevPhysMemoryLength = (ULONG)pPartialData->u.Memory.Length;
/* Save resource information. */
pBaseAddress->RangeStart = pPartialData->u.Memory.Start;
pBaseAddress->RangeLength = pPartialData->u.Memory.Length;
pBaseAddress->RangeInMemory = TRUE;
pBaseAddress->ResourceMapped = FALSE;
LogFunc(("Memory range for VMMDev found! Base = %08x:%08x, Length = %08x\n",
pPartialData->u.Memory.Start.HighPart,
pPartialData->u.Memory.Start.LowPart,
pPartialData->u.Memory.Length));
/* Next item ... */
rangeCount++; pBaseAddress++; cMMIORange++;
}
else
LogFunc(("Ignoring memory: Flags=%08x\n", pPartialData->Flags));
}
break;
}
default:
{
LogFunc(("Unhandled resource found, type=%d\n", pPartialData->Type));
break;
}
}
}
/* Memorize the number of resources found. */
pDevExt->pciAddressCount = rangeCount;
return rc;
}
/**
* Maps the I/O space from VMMDev to virtual kernel address space.
*
* @return NTSTATUS
*
* @param pDevExt The device extension.
* @param PhysAddr Physical address to map.
* @param cbToMap Number of bytes to map.
* @param ppvMMIOBase Pointer of mapped I/O base.
* @param pcbMMIO Length of mapped I/O base.
*/
NTSTATUS vbgdNtMapVMMDevMemory(PVBOXGUESTDEVEXTWIN pDevExt, PHYSICAL_ADDRESS PhysAddr, ULONG cbToMap,
void **ppvMMIOBase, uint32_t *pcbMMIO)
{
AssertPtrReturn(pDevExt, VERR_INVALID_POINTER);
AssertPtrReturn(ppvMMIOBase, VERR_INVALID_POINTER);
/* pcbMMIO is optional. */
NTSTATUS rc = STATUS_SUCCESS;
if (PhysAddr.LowPart > 0) /* We're mapping below 4GB. */
{
VMMDevMemory *pVMMDevMemory = (VMMDevMemory *)MmMapIoSpace(PhysAddr, cbToMap, MmNonCached);
LogFlowFunc(("pVMMDevMemory = 0x%x\n", pVMMDevMemory));
if (pVMMDevMemory)
{
LogFunc(("VMMDevMemory: Version = 0x%x, Size = %d\n", pVMMDevMemory->u32Version, pVMMDevMemory->u32Size));
/* Check version of the structure; do we have the right memory version? */
if (pVMMDevMemory->u32Version == VMMDEV_MEMORY_VERSION)
{
/* Save results. */
*ppvMMIOBase = pVMMDevMemory;
if (pcbMMIO) /* Optional. */
*pcbMMIO = pVMMDevMemory->u32Size;
LogFlowFunc(("VMMDevMemory found and mapped! pvMMIOBase = 0x%p\n", *ppvMMIOBase));
}
else
{
/* Not our version, refuse operation and unmap the memory. */
LogFunc(("Wrong version (%u), refusing operation!\n", pVMMDevMemory->u32Version));
vbgdNtUnmapVMMDevMemory(pDevExt);
rc = STATUS_UNSUCCESSFUL;
}
}
else
rc = STATUS_UNSUCCESSFUL;
}
return rc;
}
/**
* Unmaps the VMMDev I/O range from kernel space.
*
* @param pDevExt The device extension.
*/
void vbgdNtUnmapVMMDevMemory(PVBOXGUESTDEVEXTWIN pDevExt)
{
LogFlowFunc(("pVMMDevMemory = 0x%x\n", pDevExt->Core.pVMMDevMemory));
if (pDevExt->Core.pVMMDevMemory)
{
MmUnmapIoSpace((void*)pDevExt->Core.pVMMDevMemory, pDevExt->vmmDevPhysMemoryLength);
pDevExt->Core.pVMMDevMemory = NULL;
}
pDevExt->vmmDevPhysMemoryAddress.QuadPart = 0;
pDevExt->vmmDevPhysMemoryLength = 0;
}
VBOXOSTYPE vbgdNtVersionToOSType(VBGDNTVER enmNtVer)
{
VBOXOSTYPE enmOsType;
switch (enmNtVer)
{
case VBGDNTVER_WINNT4:
enmOsType = VBOXOSTYPE_WinNT4;
break;
case VBGDNTVER_WIN2K:
enmOsType = VBOXOSTYPE_Win2k;
break;
case VBGDNTVER_WINXP:
#if ARCH_BITS == 64
enmOsType = VBOXOSTYPE_WinXP_x64;
#else
enmOsType = VBOXOSTYPE_WinXP;
#endif
break;
case VBGDNTVER_WIN2K3:
#if ARCH_BITS == 64
enmOsType = VBOXOSTYPE_Win2k3_x64;
#else
enmOsType = VBOXOSTYPE_Win2k3;
#endif
break;
case VBGDNTVER_WINVISTA:
#if ARCH_BITS == 64
enmOsType = VBOXOSTYPE_WinVista_x64;
#else
enmOsType = VBOXOSTYPE_WinVista;
#endif
break;
case VBGDNTVER_WIN7:
#if ARCH_BITS == 64
enmOsType = VBOXOSTYPE_Win7_x64;
#else
enmOsType = VBOXOSTYPE_Win7;
#endif
break;
case VBGDNTVER_WIN8:
#if ARCH_BITS == 64
enmOsType = VBOXOSTYPE_Win8_x64;
#else
enmOsType = VBOXOSTYPE_Win8;
#endif
break;
case VBGDNTVER_WIN81:
#if ARCH_BITS == 64
enmOsType = VBOXOSTYPE_Win81_x64;
#else
enmOsType = VBOXOSTYPE_Win81;
#endif
break;
case VBGDNTVER_WIN10:
#if ARCH_BITS == 64
enmOsType = VBOXOSTYPE_Win10_x64;
#else
enmOsType = VBOXOSTYPE_Win10;
#endif
break;
default:
/* We don't know, therefore NT family. */
enmOsType = VBOXOSTYPE_WinNT;
break;
}
return enmOsType;
}
#ifdef DEBUG
/**
* A quick implementation of AtomicTestAndClear for uint32_t and multiple bits.
*/
static uint32_t vboxugestwinAtomicBitsTestAndClear(void *pu32Bits, uint32_t u32Mask)
{
AssertPtrReturn(pu32Bits, 0);
LogFlowFunc(("*pu32Bits=0x%x, u32Mask=0x%x\n", *(uint32_t *)pu32Bits, u32Mask));
uint32_t u32Result = 0;
uint32_t u32WorkingMask = u32Mask;
int iBitOffset = ASMBitFirstSetU32 (u32WorkingMask);
while (iBitOffset > 0)
{
bool fSet = ASMAtomicBitTestAndClear(pu32Bits, iBitOffset - 1);
if (fSet)
u32Result |= 1 << (iBitOffset - 1);
u32WorkingMask &= ~(1 << (iBitOffset - 1));
iBitOffset = ASMBitFirstSetU32 (u32WorkingMask);
}
LogFlowFunc(("Returning 0x%x\n", u32Result));
return u32Result;
}
static void vbgdNtTestAtomicTestAndClearBitsU32(uint32_t u32Mask, uint32_t u32Bits, uint32_t u32Exp)
{
ULONG u32Bits2 = u32Bits;
uint32_t u32Result = vboxugestwinAtomicBitsTestAndClear(&u32Bits2, u32Mask);
if ( u32Result != u32Exp
|| (u32Bits2 & u32Mask)
|| (u32Bits2 & u32Result)
|| ((u32Bits2 | u32Result) != u32Bits)
)
AssertLogRelMsgFailed(("%s: TEST FAILED: u32Mask=0x%x, u32Bits (before)=0x%x, u32Bits (after)=0x%x, u32Result=0x%x, u32Exp=ox%x\n",
__PRETTY_FUNCTION__, u32Mask, u32Bits, u32Bits2,
u32Result));
}
static void vbgdNtDoTests(void)
{
vbgdNtTestAtomicTestAndClearBitsU32(0x00, 0x23, 0);
vbgdNtTestAtomicTestAndClearBitsU32(0x11, 0, 0);
vbgdNtTestAtomicTestAndClearBitsU32(0x11, 0x22, 0);
vbgdNtTestAtomicTestAndClearBitsU32(0x11, 0x23, 0x1);
vbgdNtTestAtomicTestAndClearBitsU32(0x11, 0x32, 0x10);
vbgdNtTestAtomicTestAndClearBitsU32(0x22, 0x23, 0x22);
}
#endif /* DEBUG */
#ifdef VBOX_WITH_DPC_LATENCY_CHECKER
/*
* DPC latency checker.
*/
/**
* One DPC latency sample.
*/
typedef struct DPCSAMPLE
{
LARGE_INTEGER PerfDelta;
LARGE_INTEGER PerfCounter;
LARGE_INTEGER PerfFrequency;
uint64_t u64TSC;
} DPCSAMPLE;
AssertCompileSize(DPCSAMPLE, 4*8);
/**
* The DPC latency measurement workset.
*/
typedef struct DPCDATA
{
KDPC Dpc;
KTIMER Timer;
KSPIN_LOCK SpinLock;
ULONG ulTimerRes;
bool volatile fFinished;
/** The timer interval (relative). */
LARGE_INTEGER DueTime;
LARGE_INTEGER PerfCounterPrev;
/** Align the sample array on a 64 byte boundrary just for the off chance
* that we'll get cache line aligned memory backing this structure. */
uint32_t auPadding[ARCH_BITS == 32 ? 5 : 7];
int cSamples;
DPCSAMPLE aSamples[8192];
} DPCDATA;
AssertCompileMemberAlignment(DPCDATA, aSamples, 64);
# define VBOXGUEST_DPC_TAG 'DPCS'
/**
* DPC callback routine for the DPC latency measurement code.
*
* @param pDpc The DPC, not used.
* @param pvDeferredContext Pointer to the DPCDATA.
* @param SystemArgument1 System use, ignored.
* @param SystemArgument2 System use, ignored.
*/
static VOID vbgdNtDpcLatencyCallback(PKDPC pDpc, PVOID pvDeferredContext, PVOID SystemArgument1, PVOID SystemArgument2)
{
DPCDATA *pData = (DPCDATA *)pvDeferredContext;
KeAcquireSpinLockAtDpcLevel(&pData->SpinLock);
if (pData->cSamples >= RT_ELEMENTS(pData->aSamples))
pData->fFinished = true;
else
{
DPCSAMPLE *pSample = &pData->aSamples[pData->cSamples++];
pSample->u64TSC = ASMReadTSC();
pSample->PerfCounter = KeQueryPerformanceCounter(&pSample->PerfFrequency);
pSample->PerfDelta.QuadPart = pSample->PerfCounter.QuadPart - pData->PerfCounterPrev.QuadPart;
pData->PerfCounterPrev.QuadPart = pSample->PerfCounter.QuadPart;
KeSetTimer(&pData->Timer, pData->DueTime, &pData->Dpc);
}
KeReleaseSpinLockFromDpcLevel(&pData->SpinLock);
}
/**
* Handles the DPC latency checker request.
*
* @returns VBox status code.
*/
int VbgdNtIOCtl_DpcLatencyChecker(void)
{
/*
* Allocate a block of non paged memory for samples and related data.
*/
DPCDATA *pData = (DPCDATA *)ExAllocatePoolWithTag(NonPagedPool, sizeof(DPCDATA), VBOXGUEST_DPC_TAG);
if (!pData)
{
RTLogBackdoorPrintf("VBoxGuest: DPC: DPCDATA allocation failed.\n");
return VERR_NO_MEMORY;
}
/*
* Initialize the data.
*/
KeInitializeDpc(&pData->Dpc, vbgdNtDpcLatencyCallback, pData);
KeInitializeTimer(&pData->Timer);
KeInitializeSpinLock(&pData->SpinLock);
pData->fFinished = false;
pData->cSamples = 0;
pData->PerfCounterPrev.QuadPart = 0;
pData->ulTimerRes = ExSetTimerResolution(1000 * 10, 1);
pData->DueTime.QuadPart = -(int64_t)pData->ulTimerRes / 10;
/*
* Start the DPC measurements and wait for a full set.
*/
KeSetTimer(&pData->Timer, pData->DueTime, &pData->Dpc);
while (!pData->fFinished)
{
LARGE_INTEGER Interval;
Interval.QuadPart = -100 * 1000 * 10;
KeDelayExecutionThread(KernelMode, TRUE, &Interval);
}
ExSetTimerResolution(0, 0);
/*
* Log everything to the host.
*/
RTLogBackdoorPrintf("DPC: ulTimerRes = %d\n", pData->ulTimerRes);
for (int i = 0; i < pData->cSamples; i++)
{
DPCSAMPLE *pSample = &pData->aSamples[i];
RTLogBackdoorPrintf("[%d] pd %lld pc %lld pf %lld t %lld\n",
i,
pSample->PerfDelta.QuadPart,
pSample->PerfCounter.QuadPart,
pSample->PerfFrequency.QuadPart,
pSample->u64TSC);
}
ExFreePoolWithTag(pData, VBOXGUEST_DPC_TAG);
return VINF_SUCCESS;
}
#endif /* VBOX_WITH_DPC_LATENCY_CHECKER */
| sobomax/virtualbox_64bit_edd | src/VBox/Additions/common/VBoxGuest/VBoxGuest-win.cpp | C++ | gpl-2.0 | 52,418 |
/***********************************************************************************
* Smooth Tasks
* Copyright (C) 2009 Mathias Panzenböck <grosser.meister.morti@gmx.net>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
***********************************************************************************/
#include "SmoothTasks/FixedItemCountTaskbarLayout.h"
#include <QApplication>
#include <cmath>
namespace SmoothTasks {
void FixedItemCountTaskbarLayout::setItemsPerRow(int itemsPerRow) {
if (m_itemsPerRow != itemsPerRow) {
m_itemsPerRow = itemsPerRow;
invalidate();
}
}
int FixedItemCountTaskbarLayout::optimumCapacity() const {
return m_itemsPerRow * maximumRows();
}
void FixedItemCountTaskbarLayout::doLayout() {
// I think this way the loops can be optimized by the compiler.
// (lifting out the comparison and making two loops; TODO: find out whether this is true):
const bool isVertical = orientation() == Qt::Vertical;
const QList<TaskbarItem*>& items = this->items();
const int N = items.size();
// if there is nothing to layout fill in some dummy data and leave
if (N == 0) {
stopAnimation();
QRectF rect(geometry());
m_rows = 1;
if (isVertical) {
m_cellHeight = rect.width();
}
else {
m_cellHeight = rect.height();
}
QSizeF newPreferredSize(qMin(10.0, rect.width()), qMin(10.0, rect.height()));
if (newPreferredSize != m_preferredSize) {
m_preferredSize = newPreferredSize;
emit sizeHintChanged(Qt::PreferredSize);
}
return;
}
const QRectF effectiveRect(effectiveGeometry());
const qreal availableWidth = isVertical ? effectiveRect.height() : effectiveRect.width();
const qreal availableHeight = isVertical ? effectiveRect.width() : effectiveRect.height();
const qreal spacing = this->spacing();
#define CELL_HEIGHT(ROWS) (((availableHeight + spacing) / ((qreal) (ROWS))) - spacing)
int itemsPerRow = m_itemsPerRow;
int rows = maximumRows();
if (itemsPerRow * rows < N) {
itemsPerRow = std::ceil(((qreal) N) / rows);
}
else {
rows = std::ceil(((qreal) N) / itemsPerRow);
}
qreal cellHeight = CELL_HEIGHT(rows);
qreal cellWidth = cellHeight * aspectRatio();
QList<RowInfo> rowInfos;
qreal maxPreferredRowWidth = 0;
buildRows(itemsPerRow, cellWidth, rowInfos, rows, maxPreferredRowWidth);
cellHeight = CELL_HEIGHT(rows);
updateLayout(rows, cellWidth, cellHeight, availableWidth, maxPreferredRowWidth, rowInfos, effectiveRect);
#undef CELL_HEIGHT
}
} // namespace SmoothTasks
| Nuk9/smooth-task-next | applet/SmoothTasks/FixedItemCountTaskbarLayout.cpp | C++ | gpl-2.0 | 3,155 |
'use strict';
var env = process.env.NODE_ENV || 'development',
config = require('./config'),
B = require('bluebird'),
_ = require('underscore'),
L = require('./logger'),
S = require('underscore.string'),
nodemailer = require('nodemailer'),
smtpTransport = require('nodemailer-smtp-pool');
var Mailer = function (options) {
var opts = _.extend({}, config.mail, options);
this.transporter = B.promisifyAll(nodemailer.createTransport(smtpTransport(opts)));
};
Mailer.prototype.send = function (options) {
var that = this;
return that.transporter.sendMailAsync(options);
};
module.exports = Mailer;
| zamamohammed/health-check | mailer.js | JavaScript | gpl-2.0 | 643 |
import MySQLdb
class DatabaseHandler:
def __init__(self):
pass
def is_delete(self, tableName):
reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"]
isDeleteFlag = 1
for name in reservedTableNameList:
isIdentical = cmp(tableName, name)
if isIdentical == 0:
isDeleteFlag = 0
break
return isDeleteFlag
def Clean_Database(self, hostUrl, account, password, databaseName):
print 'clean database1'
db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName)
cursor = db.cursor()
cursor.execute("Show Tables from " + databaseName)
result = cursor.fetchall()
for record in result:
tableName = record[0]
isDelete = self.is_delete(tableName)
if isDelete == 0:
print "Reserve " + tableName
else :
print "TRUNCATE TABLE `" + tableName + "`"
cursor.execute("TRUNCATE TABLE `" + tableName + "`")
print 'Add admin'
cursor.execute("INSERT INTO `account` VALUES (1, 'admin', 'admin', 'example@ezScrum.tw', '21232f297a57a5a743894a0e4a801fc3', 1, 1379910191599, 1379910191599)")
cursor.execute("INSERT INTO `system` VALUES (1, 1)")
db.commit()
#if __name__ == '__main__':
# databaseHandler = DatabaseHandler()
# databaseHandler.clean_database("localhost", "spark", "spark", "robottest")
| ezScrum/ezScrum | robotTesting/keywords/lib/DatabaseHandler.py | Python | gpl-2.0 | 1,547 |
#!/usr/bin/ruby
require File.expand_path(ENV['MOSYNCDIR']+'/rules/mosync_exe.rb')
work = PipeExeWork.new
work.instance_eval do
@SOURCES = ["."]
@LIBRARIES = ["mautil"]
@NAME = "Stylus"
end
work.invoke
| tybor/MoSync | examples/cpp/Moblet/Stylus/workfile.rb | Ruby | gpl-2.0 | 207 |
/***********************************************************************************
* *
* Voreen - The Volume Rendering Engine *
* *
* Copyright (C) 2005-2013 University of Muenster, Germany. *
* Visualization and Computer Graphics Group <http://viscg.uni-muenster.de> *
* For a list of authors please refer to the file "CREDITS.txt". *
* *
* This file is part of the Voreen software package. Voreen 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. *
* *
* Voreen is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR *
* A PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License in the file *
* "LICENSE.txt" along with this file. If not, see <http://www.gnu.org/licenses/>. *
* *
* For non-commercial academic use see the license exception specified in the file *
* "LICENSE-academic.txt". To get information about commercial licensing please *
* contact the authors. *
* *
***********************************************************************************/
#include "isolatedconnectedimagefilter.h"
#include "voreen/core/datastructures/volume/volumeram.h"
#include "voreen/core/datastructures/volume/volume.h"
#include "voreen/core/datastructures/volume/volumeatomic.h"
#include "voreen/core/ports/conditions/portconditionvolumetype.h"
#include "modules/itk/utils/itkwrapper.h"
#include "voreen/core/datastructures/volume/operators/volumeoperatorconvert.h"
#include "itkImage.h"
#include "itkIsolatedConnectedImageFilter.h"
#include <iostream>
namespace voreen {
const std::string IsolatedConnectedImageFilterITK::loggerCat_("voreen.IsolatedConnectedImageFilterITK");
IsolatedConnectedImageFilterITK::IsolatedConnectedImageFilterITK()
: ITKProcessor(),
inport1_(Port::INPORT, "InputImage"),
outport1_(Port::OUTPORT, "OutputImage"),
seedPointPort1_(Port::INPORT, "seedPointInput1"),
seedPointPort2_(Port::INPORT, "seedPointInput2"),
enableProcessing_("enabled", "Enable", false),
replaceValue_("replaceValue", "ReplaceValue"),
isolatedValueTolerance_("isolatedValueTolerance", "IsolatedValueTolerance"),
upper_("upper", "Upper"),
lower_("lower", "Lower"),
findUpperThreshold_("findUpperThreshold", "FindUpperThreshold", false)
{
addPort(inport1_);
PortConditionLogicalOr* orCondition1 = new PortConditionLogicalOr();
orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt8());
orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt8());
orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt16());
orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt16());
orCondition1->addLinkedCondition(new PortConditionVolumeTypeUInt32());
orCondition1->addLinkedCondition(new PortConditionVolumeTypeInt32());
orCondition1->addLinkedCondition(new PortConditionVolumeTypeFloat());
orCondition1->addLinkedCondition(new PortConditionVolumeTypeDouble());
inport1_.addCondition(orCondition1);
addPort(outport1_);
addPort(seedPointPort1_);
addPort(seedPointPort2_);
addProperty(enableProcessing_);
addProperty(replaceValue_);
addProperty(isolatedValueTolerance_);
addProperty(upper_);
addProperty(lower_);
addProperty(findUpperThreshold_);
}
Processor* IsolatedConnectedImageFilterITK::create() const {
return new IsolatedConnectedImageFilterITK();
}
template<class T>
void IsolatedConnectedImageFilterITK::isolatedConnectedImageFilterITK() {
replaceValue_.setVolume(inport1_.getData());
isolatedValueTolerance_.setVolume(inport1_.getData());
upper_.setVolume(inport1_.getData());
lower_.setVolume(inport1_.getData());
if (!enableProcessing_.get()) {
outport1_.setData(inport1_.getData(), false);
return;
}
typedef itk::Image<T, 3> InputImageType1;
typedef itk::Image<T, 3> OutputImageType1;
typename InputImageType1::Pointer p1 = voreenToITK<T>(inport1_.getData());
//Filter define
typedef itk::IsolatedConnectedImageFilter<InputImageType1, OutputImageType1> FilterType;
typename FilterType::Pointer filter = FilterType::New();
filter->SetInput(p1);
if (seedPointPort1_.hasChanged()) {
const PointListGeometry<tgt::vec3>* pointList1 = dynamic_cast< const PointListGeometry<tgt::vec3>* >(seedPointPort1_.getData());
if (pointList1) {
seedPoints1 = pointList1->getData();
}
}
filter->ClearSeeds1();
typename InputImageType1::IndexType seed1;
for (size_t i = 0; i < seedPoints1.size(); i++) {
seed1[0] = seedPoints1[i].x;
seed1[1] = seedPoints1[i].y;
seed1[2] = seedPoints1[i].z;
filter->AddSeed1(seed1);
}
if (seedPointPort2_.hasChanged()) {
const PointListGeometry<tgt::vec3>* pointList2 = dynamic_cast< const PointListGeometry<tgt::vec3>* >(seedPointPort2_.getData());
if (pointList2) {
seedPoints2 = pointList2->getData();
}
}
filter->ClearSeeds2();
typename InputImageType1::IndexType seed2;
for (size_t i = 0; i < seedPoints2.size(); i++) {
seed2[0] = seedPoints2[i].x;
seed2[1] = seedPoints2[i].y;
seed2[2] = seedPoints2[i].z;
filter->AddSeed2(seed2);
}
filter->SetReplaceValue(replaceValue_.getValue<T>());
filter->SetIsolatedValueTolerance(isolatedValueTolerance_.getValue<T>());
filter->SetUpper(upper_.getValue<T>());
filter->SetLower(lower_.getValue<T>());
filter->SetFindUpperThreshold(findUpperThreshold_.get());
observe(filter.GetPointer());
try
{
filter->Update();
}
catch (itk::ExceptionObject &e)
{
LERROR(e);
}
Volume* outputVolume1 = 0;
outputVolume1 = ITKToVoreenCopy<T>(filter->GetOutput());
if (outputVolume1) {
transferRWM(inport1_.getData(), outputVolume1);
transferTransformation(inport1_.getData(), outputVolume1);
outport1_.setData(outputVolume1);
} else
outport1_.setData(0);
}
void IsolatedConnectedImageFilterITK::process() {
const VolumeBase* inputHandle1 = inport1_.getData();
const VolumeRAM* inputVolume1 = inputHandle1->getRepresentation<VolumeRAM>();
if (dynamic_cast<const VolumeRAM_UInt8*>(inputVolume1)) {
isolatedConnectedImageFilterITK<uint8_t>();
}
else if (dynamic_cast<const VolumeRAM_Int8*>(inputVolume1)) {
isolatedConnectedImageFilterITK<int8_t>();
}
else if (dynamic_cast<const VolumeRAM_UInt16*>(inputVolume1)) {
isolatedConnectedImageFilterITK<uint16_t>();
}
else if (dynamic_cast<const VolumeRAM_Int16*>(inputVolume1)) {
isolatedConnectedImageFilterITK<int16_t>();
}
else if (dynamic_cast<const VolumeRAM_UInt32*>(inputVolume1)) {
isolatedConnectedImageFilterITK<uint32_t>();
}
else if (dynamic_cast<const VolumeRAM_Int32*>(inputVolume1)) {
isolatedConnectedImageFilterITK<int32_t>();
}
else if (dynamic_cast<const VolumeRAM_Float*>(inputVolume1)) {
isolatedConnectedImageFilterITK<float>();
}
else if (dynamic_cast<const VolumeRAM_Double*>(inputVolume1)) {
isolatedConnectedImageFilterITK<double>();
}
else {
LERROR("Inputformat of Volume 1 is not supported!");
}
}
} // namespace
| bilgili/Voreen | modules/itk_generated/processors/itk_RegionGrowing/isolatedconnectedimagefilter.cpp | C++ | gpl-2.0 | 8,330 |
#include "EOSProjectData.h"
EOSProjectData::EOSProjectData()
{
}
EOSProjectData::~EOSProjectData()
{
}
| eranif/codelite | EOSWiki/EOSProjectData.cpp | C++ | gpl-2.0 | 106 |
/*
* Copyright 2002-2011 the original author or authors.
*
* 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.springframework.cache.interceptor;
import java.io.Serializable;
import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* AOP Alliance MethodInterceptor for declarative cache
* management using the common Spring caching infrastructure
* ({@link org.springframework.cache.Cache}).
*
* <p>Derives from the {@link CacheAspectSupport} class which
* contains the integration with Spring's underlying caching API.
* CacheInterceptor simply calls the relevant superclass methods
* in the correct order.
*
* <p>CacheInterceptors are thread-safe.
*
* @author Costin Leau
* @author Juergen Hoeller
* @since 3.1
*/
@SuppressWarnings("serial")
public class CacheInterceptor extends CacheAspectSupport implements MethodInterceptor, Serializable {
private static class ThrowableWrapper extends RuntimeException {
private final Throwable original;
ThrowableWrapper(Throwable original) {
this.original = original;
}
}
public Object invoke(final MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
Invoker aopAllianceInvoker = new Invoker() {
public Object invoke() {
try {
return invocation.proceed();
} catch (Throwable ex) {
throw new ThrowableWrapper(ex);
}
}
};
try {
return execute(aopAllianceInvoker, invocation.getThis(), method, invocation.getArguments());
} catch (ThrowableWrapper th) {
throw th.original;
}
}
}
| deathspeeder/class-guard | spring-framework-3.2.x/spring-context/src/main/java/org/springframework/cache/interceptor/CacheInterceptor.java | Java | gpl-2.0 | 2,142 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2006-2011 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.protocols.jmx.connectors;
import javax.management.MBeanServerConnection;
/*
* This interface defines the ability to handle a live connection and the ability to
* close it.
*
* @author <A HREF="mailto:mike@opennms.org">Mike Jamison </A>
* @author <A HREF="http://www.opennms.org/">OpenNMS </A>
*/
/**
* <p>ConnectionWrapper interface.</p>
*
* @author ranger
* @version $Id: $
*/
public interface ConnectionWrapper {
/**
* <p>getMBeanServer</p>
*
* @return a {@link javax.management.MBeanServerConnection} object.
*/
public MBeanServerConnection getMBeanServer();
/**
* <p>close</p>
*/
public void close();
}
| tharindum/opennms_dashboard | opennms-services/src/main/java/org/opennms/protocols/jmx/connectors/ConnectionWrapper.java | Java | gpl-2.0 | 1,879 |
/*jshint strict: false */
/*global chrome */
var merge = require('./merge');
exports.extend = require('pouchdb-extend');
exports.ajax = require('./deps/ajax');
exports.createBlob = require('./deps/blob');
exports.uuid = require('./deps/uuid');
exports.getArguments = require('argsarray');
var buffer = require('./deps/buffer');
var errors = require('./deps/errors');
var EventEmitter = require('events').EventEmitter;
var collections = require('./deps/collections');
exports.Map = collections.Map;
exports.Set = collections.Set;
if (typeof global.Promise === 'function') {
exports.Promise = global.Promise;
} else {
exports.Promise = require('bluebird');
}
var Promise = exports.Promise;
function toObject(array) {
var obj = {};
array.forEach(function (item) { obj[item] = true; });
return obj;
}
// List of top level reserved words for doc
var reservedWords = toObject([
'_id',
'_rev',
'_attachments',
'_deleted',
'_revisions',
'_revs_info',
'_conflicts',
'_deleted_conflicts',
'_local_seq',
'_rev_tree',
//replication documents
'_replication_id',
'_replication_state',
'_replication_state_time',
'_replication_state_reason',
'_replication_stats'
]);
// List of reserved words that should end up the document
var dataWords = toObject([
'_attachments',
//replication documents
'_replication_id',
'_replication_state',
'_replication_state_time',
'_replication_state_reason',
'_replication_stats'
]);
exports.lastIndexOf = function (str, char) {
for (var i = str.length - 1; i >= 0; i--) {
if (str.charAt(i) === char) {
return i;
}
}
return -1;
};
exports.clone = function (obj) {
return exports.extend(true, {}, obj);
};
exports.inherits = require('inherits');
// Determine id an ID is valid
// - invalid IDs begin with an underescore that does not begin '_design' or
// '_local'
// - any other string value is a valid id
// Returns the specific error object for each case
exports.invalidIdError = function (id) {
var err;
if (!id) {
err = new TypeError(errors.MISSING_ID.message);
err.status = 412;
} else if (typeof id !== 'string') {
err = new TypeError(errors.INVALID_ID.message);
err.status = 400;
} else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
err = new TypeError(errors.RESERVED_ID.message);
err.status = 400;
}
if (err) {
throw err;
}
};
function isChromeApp() {
return (typeof chrome !== "undefined" &&
typeof chrome.storage !== "undefined" &&
typeof chrome.storage.local !== "undefined");
}
// Pretty dumb name for a function, just wraps callback calls so we dont
// to if (callback) callback() everywhere
exports.call = exports.getArguments(function (args) {
if (!args.length) {
return;
}
var fun = args.shift();
if (typeof fun === 'function') {
fun.apply(this, args);
}
});
exports.isLocalId = function (id) {
return (/^_local/).test(id);
};
// check if a specific revision of a doc has been deleted
// - metadata: the metadata object from the doc store
// - rev: (optional) the revision to check. defaults to winning revision
exports.isDeleted = function (metadata, rev) {
if (!rev) {
rev = merge.winningRev(metadata);
}
var dashIndex = rev.indexOf('-');
if (dashIndex !== -1) {
rev = rev.substring(dashIndex + 1);
}
var deleted = false;
merge.traverseRevTree(metadata.rev_tree,
function (isLeaf, pos, id, acc, opts) {
if (id === rev) {
deleted = !!opts.deleted;
}
});
return deleted;
};
exports.revExists = function (metadata, rev) {
var found = false;
merge.traverseRevTree(metadata.rev_tree, function (leaf, pos, id, acc, opts) {
if ((pos + '-' + id) === rev) {
found = true;
}
});
return found;
};
exports.filterChange = function (opts) {
return function (change) {
var req = {};
var hasFilter = opts.filter && typeof opts.filter === 'function';
req.query = opts.query_params;
if (opts.filter && hasFilter && !opts.filter.call(this, change.doc, req)) {
return false;
}
if (opts.doc_ids && opts.doc_ids.indexOf(change.id) === -1) {
return false;
}
if (!opts.include_docs) {
delete change.doc;
} else {
for (var att in change.doc._attachments) {
if (change.doc._attachments.hasOwnProperty(att)) {
change.doc._attachments[att].stub = true;
}
}
}
return true;
};
};
// Preprocess documents, parse their revisions, assign an id and a
// revision for new writes that are missing them, etc
exports.parseDoc = function (doc, newEdits) {
var nRevNum;
var newRevId;
var revInfo;
var error;
var opts = {status: 'available'};
if (doc._deleted) {
opts.deleted = true;
}
if (newEdits) {
if (!doc._id) {
doc._id = exports.uuid();
}
newRevId = exports.uuid(32, 16).toLowerCase();
if (doc._rev) {
revInfo = /^(\d+)-(.+)$/.exec(doc._rev);
if (!revInfo) {
var err = new TypeError("invalid value for property '_rev'");
err.status = 400;
}
doc._rev_tree = [{
pos: parseInt(revInfo[1], 10),
ids: [revInfo[2], {status: 'missing'}, [[newRevId, opts, []]]]
}];
nRevNum = parseInt(revInfo[1], 10) + 1;
} else {
doc._rev_tree = [{
pos: 1,
ids : [newRevId, opts, []]
}];
nRevNum = 1;
}
} else {
if (doc._revisions) {
doc._rev_tree = [{
pos: doc._revisions.start - doc._revisions.ids.length + 1,
ids: doc._revisions.ids.reduce(function (acc, x) {
if (acc === null) {
return [x, opts, []];
} else {
return [x, {status: 'missing'}, [acc]];
}
}, null)
}];
nRevNum = doc._revisions.start;
newRevId = doc._revisions.ids[0];
}
if (!doc._rev_tree) {
revInfo = /^(\d+)-(.+)$/.exec(doc._rev);
if (!revInfo) {
error = new TypeError(errors.BAD_ARG.message);
error.status = errors.BAD_ARG.status;
throw error;
}
nRevNum = parseInt(revInfo[1], 10);
newRevId = revInfo[2];
doc._rev_tree = [{
pos: parseInt(revInfo[1], 10),
ids: [revInfo[2], opts, []]
}];
}
}
exports.invalidIdError(doc._id);
doc._rev = [nRevNum, newRevId].join('-');
var result = {metadata : {}, data : {}};
for (var key in doc) {
if (doc.hasOwnProperty(key)) {
var specialKey = key[0] === '_';
if (specialKey && !reservedWords[key]) {
error = new Error(errors.DOC_VALIDATION.message + ': ' + key);
error.status = errors.DOC_VALIDATION.status;
throw error;
} else if (specialKey && !dataWords[key]) {
result.metadata[key.slice(1)] = doc[key];
} else {
result.data[key] = doc[key];
}
}
}
return result;
};
exports.isCordova = function () {
return (typeof cordova !== "undefined" ||
typeof PhoneGap !== "undefined" ||
typeof phonegap !== "undefined");
};
exports.hasLocalStorage = function () {
if (isChromeApp()) {
return false;
}
try {
return global.localStorage;
} catch (e) {
return false;
}
};
exports.Changes = Changes;
exports.inherits(Changes, EventEmitter);
function Changes() {
if (!(this instanceof Changes)) {
return new Changes();
}
var self = this;
EventEmitter.call(this);
this.isChrome = isChromeApp();
this.listeners = {};
this.hasLocal = false;
if (!this.isChrome) {
this.hasLocal = exports.hasLocalStorage();
}
if (this.isChrome) {
chrome.storage.onChanged.addListener(function (e) {
// make sure it's event addressed to us
if (e.db_name != null) {
//object only has oldValue, newValue members
self.emit(e.dbName.newValue);
}
});
} else if (this.hasLocal) {
if (global.addEventListener) {
global.addEventListener("storage", function (e) {
self.emit(e.key);
});
} else {
global.attachEvent("storage", function (e) {
self.emit(e.key);
});
}
}
}
Changes.prototype.addListener = function (dbName, id, db, opts) {
if (this.listeners[id]) {
return;
}
function eventFunction() {
db.changes({
include_docs: opts.include_docs,
conflicts: opts.conflicts,
continuous: false,
descending: false,
filter: opts.filter,
view: opts.view,
since: opts.since,
query_params: opts.query_params,
onChange: function (c) {
if (c.seq > opts.since && !opts.cancelled) {
opts.since = c.seq;
exports.call(opts.onChange, c);
}
}
});
}
this.listeners[id] = eventFunction;
this.on(dbName, eventFunction);
};
Changes.prototype.removeListener = function (dbName, id) {
if (!(id in this.listeners)) {
return;
}
EventEmitter.prototype.removeListener.call(this, dbName,
this.listeners[id]);
};
Changes.prototype.notifyLocalWindows = function (dbName) {
//do a useless change on a storage thing
//in order to get other windows's listeners to activate
if (this.isChrome) {
chrome.storage.local.set({dbName: dbName});
} else if (this.hasLocal) {
localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
}
};
Changes.prototype.notify = function (dbName) {
this.emit(dbName);
this.notifyLocalWindows(dbName);
};
if (!process.browser || !('atob' in global)) {
exports.atob = function (str) {
var base64 = new buffer(str, 'base64');
// Node.js will just skip the characters it can't encode instead of
// throwing and exception
if (base64.toString('base64') !== str) {
throw ("Cannot base64 encode full string");
}
return base64.toString('binary');
};
} else {
exports.atob = function (str) {
return atob(str);
};
}
if (!process.browser || !('btoa' in global)) {
exports.btoa = function (str) {
return new buffer(str, 'binary').toString('base64');
};
} else {
exports.btoa = function (str) {
return btoa(str);
};
}
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
exports.fixBinary = function (bin) {
if (!process.browser) {
// don't need to do this in Node
return bin;
}
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
};
// shim for browsers that don't support it
exports.readAsBinaryString = function (blob, callback) {
var reader = new FileReader();
var hasBinaryString = typeof reader.readAsBinaryString === 'function';
reader.onloadend = function (e) {
var result = e.target.result || '';
if (hasBinaryString) {
return callback(result);
}
callback(exports.arrayBufferToBinaryString(result));
};
if (hasBinaryString) {
reader.readAsBinaryString(blob);
} else {
reader.readAsArrayBuffer(blob);
}
};
exports.once = function (fun) {
var called = false;
return exports.getArguments(function (args) {
if (called) {
throw new Error('once called more than once');
} else {
called = true;
fun.apply(this, args);
}
});
};
exports.toPromise = function (func) {
//create the function we will be returning
return exports.getArguments(function (args) {
var self = this;
var tempCB =
(typeof args[args.length - 1] === 'function') ? args.pop() : false;
// if the last argument is a function, assume its a callback
var usedCB;
if (tempCB) {
// if it was a callback, create a new callback which calls it,
// but do so async so we don't trap any errors
usedCB = function (err, resp) {
process.nextTick(function () {
tempCB(err, resp);
});
};
}
var promise = new Promise(function (fulfill, reject) {
var resp;
try {
var callback = exports.once(function (err, mesg) {
if (err) {
reject(err);
} else {
fulfill(mesg);
}
});
// create a callback for this invocation
// apply the function in the orig context
args.push(callback);
resp = func.apply(self, args);
if (resp && typeof resp.then === 'function') {
fulfill(resp);
}
} catch (e) {
reject(e);
}
});
// if there is a callback, call it back
if (usedCB) {
promise.then(function (result) {
usedCB(null, result);
}, usedCB);
}
promise.cancel = function () {
return this;
};
return promise;
});
};
exports.adapterFun = function (name, callback) {
return exports.toPromise(exports.getArguments(function (args) {
if (this._closed) {
return Promise.reject(new Error('database is closed'));
}
var self = this;
if (!this.taskqueue.isReady) {
return new exports.Promise(function (fulfill, reject) {
self.taskqueue.addTask(function (failed) {
if (failed) {
reject(failed);
} else {
fulfill(self[name].apply(self, args));
}
});
});
}
return callback.apply(this, args);
}));
};
//Can't find original post, but this is close
//http://stackoverflow.com/questions/6965107/ (continues on next line)
//converting-between-strings-and-arraybuffers
exports.arrayBufferToBinaryString = function (buffer) {
var binary = "";
var bytes = new Uint8Array(buffer);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return binary;
};
exports.cancellableFun = function (fun, self, opts) {
opts = opts ? exports.clone(true, {}, opts) : {};
var emitter = new EventEmitter();
var oldComplete = opts.complete || function () { };
var complete = opts.complete = exports.once(function (err, resp) {
if (err) {
oldComplete(err);
} else {
emitter.emit('end', resp);
oldComplete(null, resp);
}
emitter.removeAllListeners();
});
var oldOnChange = opts.onChange || function () {};
var lastChange = 0;
self.on('destroyed', function () {
emitter.removeAllListeners();
});
opts.onChange = function (change) {
oldOnChange(change);
if (change.seq <= lastChange) {
return;
}
lastChange = change.seq;
emitter.emit('change', change);
if (change.deleted) {
emitter.emit('delete', change);
} else if (change.changes.length === 1 &&
change.changes[0].rev.slice(0, 1) === '1-') {
emitter.emit('create', change);
} else {
emitter.emit('update', change);
}
};
var promise = new Promise(function (fulfill, reject) {
opts.complete = function (err, res) {
if (err) {
reject(err);
} else {
fulfill(res);
}
};
});
promise.then(function (result) {
complete(null, result);
}, complete);
// this needs to be overwridden by caller, dont fire complete until
// the task is ready
promise.cancel = function () {
promise.isCancelled = true;
if (self.taskqueue.isReady) {
opts.complete(null, {status: 'cancelled'});
}
};
if (!self.taskqueue.isReady) {
self.taskqueue.addTask(function () {
if (promise.isCancelled) {
opts.complete(null, {status: 'cancelled'});
} else {
fun(self, opts, promise);
}
});
} else {
fun(self, opts, promise);
}
promise.on = emitter.on.bind(emitter);
promise.once = emitter.once.bind(emitter);
promise.addListener = emitter.addListener.bind(emitter);
promise.removeListener = emitter.removeListener.bind(emitter);
promise.removeAllListeners = emitter.removeAllListeners.bind(emitter);
promise.setMaxListeners = emitter.setMaxListeners.bind(emitter);
promise.listeners = emitter.listeners.bind(emitter);
promise.emit = emitter.emit.bind(emitter);
return promise;
};
exports.MD5 = exports.toPromise(require('./deps/md5'));
// designed to give info to browser users, who are disturbed
// when they see 404s in the console
exports.explain404 = function (str) {
if (process.browser && 'console' in global && 'info' in console) {
console.info('The above 404 is totally normal. ' +
str + '\n\u2665 the PouchDB team');
}
};
exports.parseUri = require('./deps/parse-uri');
exports.compare = function (left, right) {
return left < right ? -1 : left > right ? 1 : 0;
}; | mrded/wikijob | www/lib/pouchdb/lib/utils.js | JavaScript | gpl-2.0 | 16,505 |
/**
* OWASP Benchmark Project v1.2beta
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest01168")
public class BenchmarkTest01168 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String param = "";
boolean flag = true;
java.util.Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements() && flag) {
String name = (String) names.nextElement();
java.util.Enumeration<String> values = request.getHeaders(name);
if (values != null) {
while (values.hasMoreElements() && flag) {
String value = (String) values.nextElement();
if (value.equals("vector")) {
param = name;
flag = false;
}
}
}
}
String bar = new Test().doSomething(param);
try {
java.util.Random numGen = java.security.SecureRandom.getInstance("SHA1PRNG");
double rand = getNextNumber(numGen);
String rememberMeKey = Double.toString(rand).substring(2); // Trim off the 0. at the front.
String user = "SafeDonatella";
String fullClassName = this.getClass().getName();
String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length());
user+= testCaseNumber;
String cookieName = "rememberMe" + testCaseNumber;
boolean foundUser = false;
javax.servlet.http.Cookie[] cookies = request.getCookies();
for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) {
javax.servlet.http.Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
foundUser = true;
}
}
}
if (foundUser) {
response.getWriter().println("Welcome back: " + user + "<br/>");
} else {
javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
rememberMe.setSecure(true);
request.getSession().setAttribute(cookieName, rememberMeKey);
response.addCookie(rememberMe);
response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
+ " whose value is: " + rememberMe.getValue() + "<br/>");
}
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing SecureRandom.nextDouble() - TestCase");
throw new ServletException(e);
}
response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextDouble() executed");
}
double getNextNumber(java.util.Random generator) {
return generator.nextDouble();
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar;
// Simple if statement that assigns constant to bar on true condition
int num = 86;
if ( (7*42) - num > 200 )
bar = "This_should_always_happen";
else bar = param;
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| marylinh/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01168.java | Java | gpl-2.0 | 4,339 |
/*
Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved.
Contact:
SYSTAP, LLC
2501 Calvert ST NW #106
Washington, DC 20008
licenses@systap.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
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
*/
/*
* Created on Apr 18, 2009
*/
package com.bigdata.relation.accesspath;
import junit.framework.TestCase2;
import com.bigdata.striterator.IChunkedIterator;
/**
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a>
* @version $Id$
*/
public class TestUnsynchronizedUnboundedChunkBuffer extends TestCase2 {
/**
*
*/
public TestUnsynchronizedUnboundedChunkBuffer() {
}
/**
* @param arg0
*/
public TestUnsynchronizedUnboundedChunkBuffer(String arg0) {
super(arg0);
}
/**
* Test empty iterator.
*/
public void test_emptyIterator() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
// the iterator is initially empty.
assertFalse(buffer.iterator().hasNext());
}
/**
* Verify that elements are flushed when an iterator is requested so
* that they will be visited by the iterator.
*/
public void test_bufferFlushedByIterator() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
buffer.add("a");
assertSameIterator(new String[] { "a" }, buffer.iterator());
}
/**
* Verify that the iterator has snapshot semantics.
*/
public void test_snapshotIterator() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
buffer.add("a");
buffer.add("b");
buffer.add("c");
// visit once.
assertSameIterator(new String[] { "a", "b", "c" }, buffer.iterator());
// will visit again.
assertSameIterator(new String[] { "a", "b", "c" }, buffer.iterator());
}
/**
* Verify iterator visits chunks as placed onto the queue.
*/
public void test_chunkedIterator() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
buffer.add("a");
buffer.flush();
buffer.add("b");
buffer.add("c");
// visit once.
assertSameChunkedIterator(new String[][] { new String[] { "a" },
new String[] { "b", "c" } }, buffer.iterator());
}
/**
* Test class of chunks created by the iterator (the array class should be
* taken from the first visited chunk's class).
*/
// @SuppressWarnings("unchecked")
public void test_chunkClass() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
buffer.add("a");
buffer.flush();
buffer.add("b");
buffer.add("c");
// visit once.
assertSameChunkedIterator(new String[][] { new String[] { "a" },
new String[] { "b", "c" } }, buffer.iterator());
}
/**
* Verify that the iterator visits the expected chunks in the expected
* order.
*
* @param <E>
* @param chunks
* @param itr
*/
protected <E> void assertSameChunkedIterator(final E[][] chunks,
final IChunkedIterator<E> itr) {
for(E[] chunk : chunks) {
assertTrue(itr.hasNext());
final E[] actual = itr.nextChunk();
assertSameArray(chunk, actual);
}
assertFalse(itr.hasNext());
}
}
| smalyshev/blazegraph | bigdata/src/test/com/bigdata/relation/accesspath/TestUnsynchronizedUnboundedChunkBuffer.java | Java | gpl-2.0 | 4,863 |
/*******************************************************************************
* Copyright (C) 2011 - 2015 Yoav Artzi, All rights reserved.
* <p>
* 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 any later version.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*******************************************************************************/
package edu.cornell.cs.nlp.spf.parser.ccg.rules.coordination;
import edu.cornell.cs.nlp.spf.ccg.categories.Category;
import edu.cornell.cs.nlp.spf.ccg.categories.syntax.ComplexSyntax;
import edu.cornell.cs.nlp.spf.ccg.categories.syntax.Slash;
import edu.cornell.cs.nlp.spf.ccg.categories.syntax.Syntax;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.IBinaryParseRule;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.ParseRuleResult;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.RuleName;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.SentenceSpan;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.RuleName.Direction;
class C2Rule<MR> implements IBinaryParseRule<MR> {
private static final RuleName RULE_NAME = RuleName
.create("c2",
Direction.FORWARD);
private static final long serialVersionUID = 1876084168220307197L;
private final ICoordinationServices<MR> services;
public C2Rule(ICoordinationServices<MR> services) {
this.services = services;
}
@Override
public ParseRuleResult<MR> apply(Category<MR> left, Category<MR> right,
SentenceSpan span) {
if (left.getSyntax().equals(Syntax.C)
&& SyntaxCoordinationServices.isCoordinationOfType(
right.getSyntax(), null)) {
final MR semantics = services.expandCoordination(right
.getSemantics());
if (semantics != null) {
return new ParseRuleResult<MR>(RULE_NAME,
Category.create(
new ComplexSyntax(right.getSyntax(),
SyntaxCoordinationServices
.getCoordinationType(right
.getSyntax()),
Slash.BACKWARD), semantics));
}
}
return null;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("rawtypes")
final C2Rule other = (C2Rule) obj;
if (services == null) {
if (other.services != null) {
return false;
}
} else if (!services.equals(other.services)) {
return false;
}
return true;
}
@Override
public RuleName getName() {
return RULE_NAME;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ (RULE_NAME == null ? 0 : RULE_NAME.hashCode());
result = prime * result + (services == null ? 0 : services.hashCode());
return result;
}
}
| ayuzhanin/cornell-spf-scala | src/main/java/edu/cornell/cs/nlp/spf/parser/ccg/rules/coordination/C2Rule.java | Java | gpl-2.0 | 3,328 |
<?php
// https://raw.github.com/facebook/php-sdk/master/src/facebook.php
// modified
// Facebook PHP SDK (v.3.1.1)
/**
* Copyright 2011 Facebook, Inc.
*
* 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.
*/
/**
* Extends the BaseFacebook class with the intent of using
* PHP sessions to store user ids and access tokens.
*/
class Facebook extends BaseFacebook
{
/**
* Identical to the parent constructor, except that
* we start a PHP session to store the user ID and
* access token if during the course of execution
* we discover them.
*
* @param Array $config the application configuration.
* @see BaseFacebook::__construct in facebook.php
*/
public function __construct($config) {
if (!session_id()) {
session_start();
}
parent::__construct($config);
}
protected static $kSupportedKeys =
array('state', 'code', 'access_token', 'user_id');
/**
* Provides the implementations of the inherited abstract
* methods. The implementation uses PHP sessions to maintain
* a store for authorization codes, user ids, CSRF states, and
* access tokens.
*/
protected function setPersistentData($key, $value) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to setPersistentData.');
return;
}
$session_var_name = $this->constructSessionVariableName($key);
$_SESSION[$session_var_name] = $value;
}
protected function getPersistentData($key, $default = false) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to getPersistentData.');
return $default;
}
$session_var_name = $this->constructSessionVariableName($key);
return isset($_SESSION[$session_var_name]) ?
$_SESSION[$session_var_name] : $default;
}
protected function clearPersistentData($key) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to clearPersistentData.');
return;
}
$session_var_name = $this->constructSessionVariableName($key);
unset($_SESSION[$session_var_name]);
}
protected function clearAllPersistentData() {
foreach (self::$kSupportedKeys as $key) {
$this->clearPersistentData($key);
}
}
protected function constructSessionVariableName($key) {
return implode('_', array('fb',
$this->getAppId(),
$key));
}
}
| rijojoy/MyIceBerg | mod/elgg_social_login/vendors/hybridauth/Hybrid_plugin/thirdparty/Facebook/facebook.php | PHP | gpl-2.0 | 2,964 |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma once
#if !defined(RXCPP_OPERATORS_RX_SEQUENCE_EQUAL_HPP)
#define RXCPP_OPERATORS_RX_SEQUENCE_EQUAL_HPP
#include "../rx-includes.hpp"
namespace rxcpp {
namespace operators {
namespace detail {
template<class T, class Observable, class OtherObservable, class BinaryPredicate, class Coordination>
struct sequence_equal : public operator_base<bool>
{
typedef rxu::decay_t<Observable> source_type;
typedef rxu::decay_t<T> source_value_type;
typedef rxu::decay_t<OtherObservable> other_source_type;
typedef typename other_source_type::value_type other_source_value_type;
typedef rxu::decay_t<BinaryPredicate> predicate_type;
typedef rxu::decay_t<Coordination> coordination_type;
typedef typename coordination_type::coordinator_type coordinator_type;
struct values {
values(source_type s, other_source_type t, predicate_type pred, coordination_type sf)
: source(std::move(s))
, other(std::move(t))
, pred(std::move(pred))
, coordination(std::move(sf))
{
}
source_type source;
other_source_type other;
predicate_type pred;
coordination_type coordination;
};
values initial;
sequence_equal(source_type s, other_source_type t, predicate_type pred, coordination_type sf)
: initial(std::move(s), std::move(t), std::move(pred), std::move(sf))
{
}
template<class Subscriber>
void on_subscribe(Subscriber s) const {
typedef Subscriber output_type;
struct state_type
: public std::enable_shared_from_this<state_type>
, public values
{
state_type(const values& vals, coordinator_type coor, const output_type& o)
: values(vals)
, coordinator(std::move(coor))
, out(o)
, source_completed(false)
, other_completed(false)
{
out.add(other_lifetime);
out.add(source_lifetime);
}
composite_subscription other_lifetime;
composite_subscription source_lifetime;
coordinator_type coordinator;
output_type out;
mutable std::list<source_value_type> source_values;
mutable std::list<other_source_value_type> other_values;
mutable bool source_completed;
mutable bool other_completed;
};
auto coordinator = initial.coordination.create_coordinator();
auto state = std::make_shared<state_type>(initial, std::move(coordinator), std::move(s));
auto other = on_exception(
[&](){ return state->coordinator.in(state->other); },
state->out);
if (other.empty()) {
return;
}
auto source = on_exception(
[&](){ return state->coordinator.in(state->source); },
state->out);
if (source.empty()) {
return;
}
auto check_equal = [state]() {
if(!state->source_values.empty() && !state->other_values.empty()) {
auto x = std::move(state->source_values.front());
state->source_values.pop_front();
auto y = std::move(state->other_values.front());
state->other_values.pop_front();
if (!state->pred(x, y)) {
state->out.on_next(false);
state->out.on_completed();
}
} else {
if((!state->source_values.empty() && state->other_completed) ||
(!state->other_values.empty() && state->source_completed)) {
state->out.on_next(false);
state->out.on_completed();
}
}
};
auto check_complete = [state]() {
if(state->source_completed && state->other_completed) {
state->out.on_next(state->source_values.empty() && state->other_values.empty());
state->out.on_completed();
}
};
auto sinkOther = make_subscriber<other_source_value_type>(
state->out,
state->other_lifetime,
// on_next
[state, check_equal](other_source_value_type t) {
auto& values = state->other_values;
values.push_back(t);
check_equal();
},
// on_error
[state](std::exception_ptr e) {
state->out.on_error(e);
},
// on_completed
[state, check_complete]() {
auto& completed = state->other_completed;
completed = true;
check_complete();
}
);
auto selectedSinkOther = on_exception(
[&](){ return state->coordinator.out(sinkOther); },
state->out);
if (selectedSinkOther.empty()) {
return;
}
other->subscribe(std::move(selectedSinkOther.get()));
source.get().subscribe(
state->source_lifetime,
// on_next
[state, check_equal](source_value_type t) {
auto& values = state->source_values;
values.push_back(t);
check_equal();
},
// on_error
[state](std::exception_ptr e) {
state->out.on_error(e);
},
// on_completed
[state, check_complete]() {
auto& completed = state->source_completed;
completed = true;
check_complete();
}
);
}
};
template<class OtherObservable, class BinaryPredicate, class Coordination>
class sequence_equal_factory
{
typedef rxu::decay_t<OtherObservable> other_source_type;
typedef rxu::decay_t<Coordination> coordination_type;
typedef rxu::decay_t<BinaryPredicate> predicate_type;
other_source_type other_source;
coordination_type coordination;
predicate_type pred;
public:
sequence_equal_factory(other_source_type t, predicate_type p, coordination_type sf)
: other_source(std::move(t))
, coordination(std::move(sf))
, pred(std::move(p))
{
}
template<class Observable>
auto operator()(Observable&& source)
-> observable<bool, sequence_equal<rxu::value_type_t<rxu::decay_t<Observable>>, Observable, other_source_type, BinaryPredicate, Coordination>> {
return observable<bool, sequence_equal<rxu::value_type_t<rxu::decay_t<Observable>>, Observable, other_source_type, BinaryPredicate, Coordination>>(
sequence_equal<rxu::value_type_t<rxu::decay_t<Observable>>, Observable, other_source_type, BinaryPredicate, Coordination>(std::forward<Observable>(source), other_source, pred, coordination));
}
};
}
template<class OtherObservable>
inline auto sequence_equal(OtherObservable&& t)
-> detail::sequence_equal_factory<OtherObservable, rxu::equal_to<>, identity_one_worker> {
return detail::sequence_equal_factory<OtherObservable, rxu::equal_to<>, identity_one_worker>(std::forward<OtherObservable>(t), rxu::equal_to<>(), identity_current_thread());
}
template<class OtherObservable, class BinaryPredicate, class Check = typename std::enable_if<!is_coordination<BinaryPredicate>::value>::type>
inline auto sequence_equal(OtherObservable&& t, BinaryPredicate&& pred)
-> detail::sequence_equal_factory<OtherObservable, BinaryPredicate, identity_one_worker> {
return detail::sequence_equal_factory<OtherObservable, BinaryPredicate, identity_one_worker>(std::forward<OtherObservable>(t), std::forward<BinaryPredicate>(pred), identity_current_thread());
}
template<class OtherObservable, class Coordination, class Check = typename std::enable_if<is_coordination<Coordination>::value>::type>
inline auto sequence_equal(OtherObservable&& t, Coordination&& cn)
-> detail::sequence_equal_factory<OtherObservable, rxu::equal_to<>, Coordination> {
return detail::sequence_equal_factory<OtherObservable, rxu::equal_to<>, Coordination>(std::forward<OtherObservable>(t), rxu::equal_to<>(), std::forward<Coordination>(cn));
}
template<class OtherObservable, class BinaryPredicate, class Coordination>
inline auto sequence_equal(OtherObservable&& t, BinaryPredicate&& pred, Coordination&& cn)
-> detail::sequence_equal_factory<OtherObservable, BinaryPredicate, Coordination> {
return detail::sequence_equal_factory<OtherObservable, BinaryPredicate, Coordination>(std::forward<OtherObservable>(t), std::forward<BinaryPredicate>(pred), std::forward<Coordination>(cn));
}
}
}
#endif
| drazenzadravec/nequeo | Tools/Linq/cpp/RX/v2/rxcpp/operators/rx-sequence_equal.hpp | C++ | gpl-2.0 | 8,921 |
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE_AFL.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @copyright Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
var varienTabs = new Class.create();
varienTabs.prototype = {
initialize : function(containerId, destElementId, activeTabId, shadowTabs){
this.containerId = containerId;
this.destElementId = destElementId;
this.activeTab = null;
this.tabOnClick = this.tabMouseClick.bindAsEventListener(this);
this.tabs = $$('#'+this.containerId+' li a.tab-item-link');
this.hideAllTabsContent();
for (var tab=0; tab<this.tabs.length; tab++) {
Event.observe(this.tabs[tab],'click',this.tabOnClick);
// move tab contents to destination element
if($(this.destElementId)){
var tabContentElement = $(this.getTabContentElementId(this.tabs[tab]));
if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){
$(this.destElementId).appendChild(tabContentElement);
tabContentElement.container = this;
tabContentElement.statusBar = this.tabs[tab];
tabContentElement.tabObject = this.tabs[tab];
this.tabs[tab].contentMoved = true;
this.tabs[tab].container = this;
this.tabs[tab].show = function(){
this.container.showTabContent(this);
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]});
}
}
}
/*
// this code is pretty slow in IE, so lets do it in tabs*.phtml
// mark ajax tabs as not loaded
if (Element.hasClassName($(this.tabs[tab].id), 'ajax')) {
Element.addClassName($(this.tabs[tab].id), 'notloaded');
}
*/
// bind shadow tabs
if (this.tabs[tab].id && shadowTabs && shadowTabs[this.tabs[tab].id]) {
this.tabs[tab].shadowTabs = shadowTabs[this.tabs[tab].id];
}
}
this.displayFirst = activeTabId;
Event.observe(window,'load',this.moveTabContentInDest.bind(this));
},
setSkipDisplayFirstTab : function(){
this.displayFirst = null;
},
moveTabContentInDest : function(){
for(var tab=0; tab<this.tabs.length; tab++){
if($(this.destElementId) && !this.tabs[tab].contentMoved){
var tabContentElement = $(this.getTabContentElementId(this.tabs[tab]));
if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){
$(this.destElementId).appendChild(tabContentElement);
tabContentElement.container = this;
tabContentElement.statusBar = this.tabs[tab];
tabContentElement.tabObject = this.tabs[tab];
this.tabs[tab].container = this;
this.tabs[tab].show = function(){
this.container.showTabContent(this);
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]});
}
}
}
}
if (this.displayFirst) {
this.showTabContent($(this.displayFirst));
this.displayFirst = null;
}
},
getTabContentElementId : function(tab){
if(tab){
return tab.id+'_content';
}
return false;
},
tabMouseClick : function(event) {
var tab = Event.findElement(event, 'a');
// go directly to specified url or switch tab
if ((tab.href.indexOf('#') != tab.href.length-1)
&& !(Element.hasClassName(tab, 'ajax'))
) {
location.href = tab.href;
}
else {
this.showTabContent(tab);
}
Event.stop(event);
},
hideAllTabsContent : function(){
for(var tab in this.tabs){
this.hideTabContent(this.tabs[tab]);
}
},
// show tab, ready or not
showTabContentImmediately : function(tab) {
this.hideAllTabsContent();
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement) {
Element.show(tabContentElement);
Element.addClassName(tab, 'active');
// load shadow tabs, if any
if (tab.shadowTabs && tab.shadowTabs.length) {
for (var k in tab.shadowTabs) {
this.loadShadowTab($(tab.shadowTabs[k]));
}
}
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
this.activeTab = tab;
}
if (varienGlobalEvents) {
varienGlobalEvents.fireEvent('showTab', {tab:tab});
}
},
// the lazy show tab method
showTabContent : function(tab) {
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement) {
if (this.activeTab != tab) {
if (varienGlobalEvents) {
if (varienGlobalEvents.fireEvent('tabChangeBefore', $(this.getTabContentElementId(this.activeTab))).indexOf('cannotchange') != -1) {
return;
};
}
}
// wait for ajax request, if defined
var isAjax = Element.hasClassName(tab, 'ajax');
var isEmpty = tabContentElement.innerHTML=='' && tab.href.indexOf('#')!=tab.href.length-1;
var isNotLoaded = Element.hasClassName(tab, 'notloaded');
if ( isAjax && (isEmpty || isNotLoaded) )
{
new Ajax.Request(tab.href, {
parameters: {form_key: FORM_KEY},
evalScripts: true,
onSuccess: function(transport) {
try {
if (transport.responseText.isJSON()) {
var response = transport.responseText.evalJSON()
if (response.error) {
alert(response.message);
}
if(response.ajaxExpired && response.ajaxRedirect) {
setLocation(response.ajaxRedirect);
}
} else {
$(tabContentElement.id).update(transport.responseText);
this.showTabContentImmediately(tab)
}
}
catch (e) {
$(tabContentElement.id).update(transport.responseText);
this.showTabContentImmediately(tab)
}
}.bind(this)
});
}
else {
this.showTabContentImmediately(tab);
}
}
},
loadShadowTab : function(tab) {
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement && Element.hasClassName(tab, 'ajax') && Element.hasClassName(tab, 'notloaded')) {
new Ajax.Request(tab.href, {
parameters: {form_key: FORM_KEY},
evalScripts: true,
onSuccess: function(transport) {
try {
if (transport.responseText.isJSON()) {
var response = transport.responseText.evalJSON()
if (response.error) {
alert(response.message);
}
if(response.ajaxExpired && response.ajaxRedirect) {
setLocation(response.ajaxRedirect);
}
} else {
$(tabContentElement.id).update(transport.responseText);
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
}
}
catch (e) {
$(tabContentElement.id).update(transport.responseText);
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
}
}.bind(this)
});
}
},
hideTabContent : function(tab){
var tabContentElement = $(this.getTabContentElementId(tab));
if($(this.destElementId) && tabContentElement){
Element.hide(tabContentElement);
Element.removeClassName(tab, 'active');
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('hideTab', {tab:tab});
}
}
} | tonio-44/tikflak | shop/js/mage/adminhtml/tabs.js | JavaScript | gpl-2.0 | 9,985 |
/*
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2011-2015 ArkCORE <http://www.arkania.net/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.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, see <http://www.gnu.org/licenses/>.
*/
#include "DatabaseEnv.h"
#include "Log.h"
ResultSet::ResultSet(MYSQL_RES *result, MYSQL_FIELD *fields, uint64 rowCount, uint32 fieldCount) :
_rowCount(rowCount),
_fieldCount(fieldCount),
_result(result),
_fields(fields)
{
_currentRow = new Field[_fieldCount];
ASSERT(_currentRow);
}
PreparedResultSet::PreparedResultSet(MYSQL_STMT* stmt, MYSQL_RES *result, uint64 rowCount, uint32 fieldCount) :
m_rowCount(rowCount),
m_rowPosition(0),
m_fieldCount(fieldCount),
m_rBind(NULL),
m_stmt(stmt),
m_res(result),
m_isNull(NULL),
m_length(NULL)
{
if (!m_res)
return;
if (m_stmt->bind_result_done)
{
delete[] m_stmt->bind->length;
delete[] m_stmt->bind->is_null;
}
m_rBind = new MYSQL_BIND[m_fieldCount];
m_isNull = new my_bool[m_fieldCount];
m_length = new unsigned long[m_fieldCount];
memset(m_isNull, 0, sizeof(my_bool) * m_fieldCount);
memset(m_rBind, 0, sizeof(MYSQL_BIND) * m_fieldCount);
memset(m_length, 0, sizeof(unsigned long) * m_fieldCount);
//- This is where we store the (entire) resultset
if (mysql_stmt_store_result(m_stmt))
{
TC_LOG_WARN("sql.sql", "%s:mysql_stmt_store_result, cannot bind result from MySQL server. Error: %s", __FUNCTION__, mysql_stmt_error(m_stmt));
delete[] m_rBind;
delete[] m_isNull;
delete[] m_length;
return;
}
//- This is where we prepare the buffer based on metadata
uint32 i = 0;
MYSQL_FIELD* field = mysql_fetch_field(m_res);
while (field)
{
size_t size = Field::SizeForType(field);
m_rBind[i].buffer_type = field->type;
m_rBind[i].buffer = malloc(size);
memset(m_rBind[i].buffer, 0, size);
m_rBind[i].buffer_length = size;
m_rBind[i].length = &m_length[i];
m_rBind[i].is_null = &m_isNull[i];
m_rBind[i].error = NULL;
m_rBind[i].is_unsigned = field->flags & UNSIGNED_FLAG;
++i;
field = mysql_fetch_field(m_res);
}
//- This is where we bind the bind the buffer to the statement
if (mysql_stmt_bind_result(m_stmt, m_rBind))
{
TC_LOG_WARN("sql.sql", "%s:mysql_stmt_bind_result, cannot bind result from MySQL server. Error: %s", __FUNCTION__, mysql_stmt_error(m_stmt));
delete[] m_rBind;
delete[] m_isNull;
delete[] m_length;
return;
}
m_rowCount = mysql_stmt_num_rows(m_stmt);
m_rows.resize(uint32(m_rowCount));
while (_NextRow())
{
m_rows[uint32(m_rowPosition)] = new Field[m_fieldCount];
for (uint64 fIndex = 0; fIndex < m_fieldCount; ++fIndex)
{
if (!*m_rBind[fIndex].is_null)
m_rows[uint32(m_rowPosition)][fIndex].SetByteValue( m_rBind[fIndex].buffer,
m_rBind[fIndex].buffer_length,
m_rBind[fIndex].buffer_type,
*m_rBind[fIndex].length );
else
switch (m_rBind[fIndex].buffer_type)
{
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VAR_STRING:
m_rows[uint32(m_rowPosition)][fIndex].SetByteValue( "",
m_rBind[fIndex].buffer_length,
m_rBind[fIndex].buffer_type,
*m_rBind[fIndex].length );
break;
default:
m_rows[uint32(m_rowPosition)][fIndex].SetByteValue( 0,
m_rBind[fIndex].buffer_length,
m_rBind[fIndex].buffer_type,
*m_rBind[fIndex].length );
}
}
m_rowPosition++;
}
m_rowPosition = 0;
/// All data is buffered, let go of mysql c api structures
CleanUp();
}
ResultSet::~ResultSet()
{
CleanUp();
}
PreparedResultSet::~PreparedResultSet()
{
for (uint32 i = 0; i < uint32(m_rowCount); ++i)
delete[] m_rows[i];
}
bool ResultSet::NextRow()
{
MYSQL_ROW row;
if (!_result)
return false;
row = mysql_fetch_row(_result);
if (!row)
{
CleanUp();
return false;
}
for (uint32 i = 0; i < _fieldCount; i++)
_currentRow[i].SetStructuredValue(row[i], _fields[i].type);
return true;
}
bool PreparedResultSet::NextRow()
{
/// Only updates the m_rowPosition so upper level code knows in which element
/// of the rows vector to look
if (++m_rowPosition >= m_rowCount)
return false;
return true;
}
bool PreparedResultSet::_NextRow()
{
/// Only called in low-level code, namely the constructor
/// Will iterate over every row of data and buffer it
if (m_rowPosition >= m_rowCount)
return false;
int retval = mysql_stmt_fetch( m_stmt );
if (!retval || retval == MYSQL_DATA_TRUNCATED)
retval = true;
if (retval == MYSQL_NO_DATA)
retval = false;
return retval;
}
void ResultSet::CleanUp()
{
if (_currentRow)
{
delete [] _currentRow;
_currentRow = NULL;
}
if (_result)
{
mysql_free_result(_result);
_result = NULL;
}
}
void PreparedResultSet::CleanUp()
{
/// More of the in our code allocated sources are deallocated by the poorly documented mysql c api
if (m_res)
mysql_free_result(m_res);
FreeBindBuffer();
mysql_stmt_free_result(m_stmt);
delete[] m_rBind;
}
void PreparedResultSet::FreeBindBuffer()
{
for (uint32 i = 0; i < m_fieldCount; ++i)
free (m_rBind[i].buffer);
}
| sunshitwowsucks/ArkCORE-NG | src/server/shared/Database/QueryResult.cpp | C++ | gpl-2.0 | 6,901 |
Template.reassign_modal.helpers({
fields: function() {
var userOptions = null;
var showOrg = true;
var instance = WorkflowManager.getInstance();
var space = db.spaces.findOne(instance.space);
var flow = db.flows.findOne({
'_id': instance.flow
});
var curSpaceUser = db.space_users.findOne({
space: instance.space,
'user': Meteor.userId()
});
var organizations = db.organizations.find({
_id: {
$in: curSpaceUser.organizations
}
}).fetch();
if (space.admins.contains(Meteor.userId())) {
} else if (WorkflowManager.canAdmin(flow, curSpaceUser, organizations)) {
var currentStep = InstanceManager.getCurrentStep()
userOptions = ApproveManager.getNextStepUsers(instance, currentStep._id).getProperty("id").join(",")
showOrg = Session.get("next_step_users_showOrg")
} else {
userOptions = "0"
showOrg = false
}
var multi = false;
var c = InstanceManager.getCurrentStep();
if (c && c.step_type == "counterSign") {
multi = true;
}
return new SimpleSchema({
reassign_users: {
autoform: {
type: "selectuser",
userOptions: userOptions,
showOrg: showOrg,
multiple: multi
},
optional: true,
type: String,
label: TAPi18n.__("instance_reassign_user")
}
});
},
values: function() {
return {};
},
current_step_name: function() {
var s = InstanceManager.getCurrentStep();
var name;
if (s) {
name = s.name;
}
return name || '';
}
})
Template.reassign_modal.events({
'show.bs.modal #reassign_modal': function(event) {
var reassign_users = $("input[name='reassign_users']")[0];
reassign_users.value = "";
reassign_users.dataset.values = '';
$(reassign_users).change();
},
'click #reassign_help': function(event, template) {
Steedos.openWindow(t("reassign_help"));
},
'click #reassign_modal_ok': function(event, template) {
var val = AutoForm.getFieldValue("reassign_users", "reassign");
if (!val) {
toastr.error(TAPi18n.__("instance_reassign_error_users_required"));
return;
}
var reason = $("#reassign_modal_text").val();
var user_ids = val.split(",");
InstanceManager.reassignIns(user_ids, reason);
Modal.hide(template);
},
}) | steedos/apps | packages/steedos-workflow/client/views/instance/reassign_modal.js | JavaScript | gpl-2.0 | 2,218 |
<?php
namespace Kbize\Sdk\Response;
class ProjectAndBoards
{
/**
*
* {
* "projects":[
* {"name":"Project","id":"1","boards":[
* {"name":"Service\/Merchant Integrations","id":"4"},
* {"name":"Tech Operations","id":"3"},
* {"name":"Main development","id":"2"}
* ]}
* ]
* }
*/
public static function fromArrayResponse(array $response)
{
return new self($response['projects']);
}
private function __construct(array $data)
{
$this->data = $data;
}
public function projects()
{
$projects = [];
foreach($this->data as $project) {
$projects[] = [
'name' => $project['name'],
'id' => $project['id'],
];
}
return $projects;
}
public function boards($projectId)
{
$projects = [];
foreach($this->data as $project) {
if ($project['id'] == $projectId) {
return $project['boards'];
}
}
throw new \Exception("Project: `$projectId` does not exists"); //TODO:! custom exception
}
}
| silvadanilo/kbize | test/unit/Kbize/Sdk/Response/ProjectAndBoards.php | PHP | gpl-2.0 | 1,183 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.sql;
public class SQLTransactionRollbackException extends SQLTransientException {
private static final long serialVersionUID = 5246680841170837229L;
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to null, the SQLState string is set to null and the Error Code is set
* to 0.
*/
public SQLTransactionRollbackException() {
super();
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to null and
* the Error Code is set to 0.
*
* @param reason
* the string to use as the Reason string
*/
public SQLTransactionRollbackException(String reason) {
super(reason, null, 0);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to the given
* SQLState string and the Error Code is set to 0.
*
* @param reason
* the string to use as the Reason string
* @param sqlState
* the string to use as the SQLState string
*/
public SQLTransactionRollbackException(String reason, String sqlState) {
super(reason, sqlState, 0);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to the given
* SQLState string and the Error Code is set to the given error code value.
*
* @param reason
* the string to use as the Reason string
* @param sqlState
* the string to use as the SQLState string
* @param vendorCode
* the integer value for the error code
*/
public SQLTransactionRollbackException(String reason, String sqlState,
int vendorCode) {
super(reason, sqlState, vendorCode);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the null if cause == null or cause.toString() if cause!=null,and
* the cause Throwable object is set to the given cause Throwable object.
*
* @param cause
* the Throwable object for the underlying reason this
* SQLException
*/
public SQLTransactionRollbackException(Throwable cause) {
super(cause);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given and the cause Throwable object is set to the given cause
* Throwable object.
*
* @param reason
* the string to use as the Reason string
* @param cause
* the Throwable object for the underlying reason this
* SQLException
*/
public SQLTransactionRollbackException(String reason, Throwable cause) {
super(reason, cause);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to the given
* SQLState string and the cause Throwable object is set to the given cause
* Throwable object.
*
* @param reason
* the string to use as the Reason string
* @param sqlState
* the string to use as the SQLState string
* @param cause
* the Throwable object for the underlying reason this
* SQLException
*/
public SQLTransactionRollbackException(String reason, String sqlState,
Throwable cause) {
super(reason, sqlState, cause);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to the given
* SQLState string , the Error Code is set to the given error code value,
* and the cause Throwable object is set to the given cause Throwable
* object.
*
* @param reason
* the string to use as the Reason string
* @param sqlState
* the string to use as the SQLState string
* @param vendorCode
* the integer value for the error code
* @param cause
* the Throwable object for the underlying reason this
* SQLException
*/
public SQLTransactionRollbackException(String reason, String sqlState,
int vendorCode, Throwable cause) {
super(reason, sqlState, vendorCode, cause);
}
} | skyHALud/codenameone | Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/sql/src/main/java/java/sql/SQLTransactionRollbackException.java | Java | gpl-2.0 | 5,553 |