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 |
|---|---|---|---|---|---|
/*
* Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the Classpath exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.btrace.core.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* BTrace fields with this annotation are exposed as attributes of the dynamic JMX bean that wraps
* the BTrace class.
*
* @author A. Sundararajan
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Property {
// by default, the name of the attribute is same as the name
// of the field of the BTrace class.
String name() default "";
// description of this attribute
String description() default "";
}
| jbachorik/btrace | btrace-core/src/main/java/org/openjdk/btrace/core/annotations/Property.java | Java | gpl-2.0 | 1,873 |
<?php
/**
* Kunena Component
* @package Kunena.Template.Blue_Eagle
* @subpackage User
*
* @copyright (C) 2008 - 2016 Kunena Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @link http://www.kunena.org
**/
defined ( '_JEXEC' ) or die ();
JHtml::_('behavior.calendar');
JHtml::_('behavior.tooltip');
?>
<div id="kprofile-rightcoltop">
<div class="kprofile-rightcol2">
<?php
$this->displayTemplateFile('user', 'default', 'social');
?>
</div>
<div class="kprofile-rightcol1">
<ul>
<li><span class="kicon-profile kicon-profile-location"></span><strong><?php echo JText::_('COM_KUNENA_MYPROFILE_LOCATION'); ?>:</strong> <?php echo $this->locationlink; ?></li>
<!-- The gender determines the suffix on the span class- gender-male & gender-female -->
<li><span class="kicon-profile kicon-profile-gender-<?php echo $this->genderclass; ?>"></span><strong><?php echo JText::_('COM_KUNENA_MYPROFILE_GENDER'); ?>:</strong> <?php echo $this->gender; ?></li>
<li class="bd"><span class="kicon-profile kicon-profile-birthdate"></span><strong><?php echo JText::_('COM_KUNENA_MYPROFILE_BIRTHDATE'); ?>:</strong> <span title="<?php echo KunenaDate::getInstance($this->profile->birthdate)->toKunena('ago', 'GMT'); ?>"><?php echo KunenaDate::getInstance($this->profile->birthdate)->toKunena('date', 'GMT'); ?></span>
<!-- <a href="#" title=""><span class="bday-remind"></span></a> -->
</li>
</ul>
</div>
</div>
<div class="clrline"></div>
<div id="kprofile-rightcolbot">
<div class="kprofile-rightcol2">
<?php if ($this->email || !empty($this->profile->websiteurl)): ?>
<ul>
<?php if ($this->email): ?>
<li><span class="kicon-profile kicon-profile-email"></span><?php echo $this->email; ?></li>
<?php endif; ?>
<?php if (!empty($this->profile->websiteurl)): ?>
<?php // FIXME: we need a better way to add http/https ?>
<li><span class="kicon-profile kicon-profile-website"></span><a href="<?php echo $this->escape($this->websiteurl); ?>" target="_blank"><?php echo KunenaHtmlParser::parseText(trim($this->profile->websitename) ? $this->profile->websitename : $this->websiteurl); ?></a></li>
<?php endif; ?>
</ul>
<?php endif;?>
</div>
<div class="kprofile-rightcol1">
<h4><?php echo JText::_('COM_KUNENA_MYPROFILE_SIGNATURE'); ?></h4>
<div class="kmsgsignature"><div><?php echo $this->signatureHtml ?></div></div>
</div>
</div>
<div class="clrline"></div>
<div id="kprofile-tabs">
<dl class="tabs">
<?php if($this->showUserPosts) : ?>
<dt class="open" title="<?php echo JText::_('COM_KUNENA_USERPOSTS'); ?>"><?php echo JText::_('COM_KUNENA_USERPOSTS'); ?></dt>
<dd style="display: none;">
<?php $this->displayUserPosts(); ?>
</dd>
<?php endif; ?>
<?php if ($this->showSubscriptions) :?>
<dt class="closed" title="<?php echo JText::_('COM_KUNENA_SUBSCRIPTIONS'); ?>"><?php echo JText::_('COM_KUNENA_SUBSCRIPTIONS'); ?></dt>
<dd style="display: none;">
<?php $this->displayCategoriesSubscriptions(); ?>
<?php $this->displaySubscriptions(); ?>
</dd>
<?php endif; ?>
<?php if ($this->showFavorites) : ?>
<dt class="closed" title="<?php echo JText::_('COM_KUNENA_FAVORITES'); ?>"><?php echo JText::_('COM_KUNENA_FAVORITES'); ?></dt>
<dd style="display: none;">
<?php $this->displayFavorites(); ?>
</dd>
<?php endif; ?>
<?php if($this->showThankyou) : ?>
<dt class="closed" title="<?php echo JText::_('COM_KUNENA_THANK_YOU'); ?>"><?php echo JText::_('COM_KUNENA_THANK_YOU'); ?></dt>
<dd style="display: none;">
<?php $this->displayGotThankyou(); ?>
<?php $this->displaySaidThankyou(); ?>
</dd>
<?php endif; ?>
<?php if ($this->showUnapprovedPosts): ?>
<dt class="open" title="<?php echo JText::_('COM_KUNENA_MESSAGE_ADMINISTRATION'); ?>"><?php echo JText::_('COM_KUNENA_MESSAGE_ADMINISTRATION'); ?></dt>
<dd style="display: none;">
<?php $this->displayUnapprovedPosts(); ?>
</dd>
<?php endif; ?>
<?php if ($this->showAttachments): ?>
<dt class="closed" title="<?php echo JText::_('COM_KUNENA_MANAGE_ATTACHMENTS'); ?>"><?php echo JText::_('COM_KUNENA_MANAGE_ATTACHMENTS'); ?></dt>
<dd style="display: none;">
<?php $this->displayAttachments(); ?>
</dd>
<?php endif;?>
<?php if ($this->showBanManager): ?>
<dt class="closed" title="<?php echo JText::_('COM_KUNENA_BAN_BANMANAGER'); ?>"><?php echo JText::_('COM_KUNENA_BAN_BANMANAGER'); ?></dt>
<dd style="display: none;">
<?php $this->displayBanManager(); ?>
</dd>
<?php endif;?>
<?php if ($this->showBanHistory):?>
<dt class="closed" title="<?php echo JText::_('COM_KUNENA_BAN_BANHISTORY'); ?>"><?php echo JText::_('COM_KUNENA_BAN_BANHISTORY'); ?></dt>
<dd style="display: none;">
<?php $this->displayBanHistory(); ?>
</dd>
<?php endif;?>
<?php if ($this->showBanUser) : ?>
<dt class="closed" title="<?php echo $this->banInfo->id ? JText::_('COM_KUNENA_BAN_EDIT') : JText::_('COM_KUNENA_BAN_NEW' ); ?>"><?php echo $this->banInfo->id ? JText::_('COM_KUNENA_BAN_EDIT') : JText::_('COM_KUNENA_BAN_NEW' ); ?></dt>
<dd style="display: none;">
<?php $this->displayBanUser(); ?>
</dd>
<?php endif; ?>
</dl>
</div>
| githubupttik/upttik | components/com_kunena/template/blue_eagle/html/user/default_tab.php | PHP | gpl-2.0 | 5,180 |
<?php
/**
* @file
* Default theme implementation to display a term.
*
* Available variables:
* - $name: (deprecated) The unsanitized name of the term. Use $term_name
* instead.
* - $content: An array of items for the content of the term (fields and
* description). Use render($content) to print them all, or print a subset
* such as render($content['field_example']). Use
* hide($content['field_example']) to temporarily suppress the printing of a
* given element.
* - $term_url: Direct URL of the current term.
* - $term_name: Name of the current term.
* - $classes: String of classes that can be used to style contextually through
* CSS. It can be manipulated through the variable $classes_array from
* preprocess functions. The default values can be one or more of the following:
* - taxonomy-term: The current template type, i.e., "theming hook".
* - vocabulary-[vocabulary-name]: The vocabulary to which the term belongs to.
* For example, if the term is a "Tag" it would result in "vocabulary-tag".
*
* Other variables:
* - $term: Full term object. Contains data that may not be safe.
* - $view_mode: View mode, e.g. 'full', 'teaser'...
* - $page: Flag for the full page state.
* - $classes_array: Array of html class attribute values. It is flattened
* into a string within the variable $classes.
* - $zebra: Outputs either "even" or "odd". Useful for zebra striping in
* teaser listings.
* - $id: Position of the term. Increments each time it's output.
* - $is_front: Flags true when presented in the front page.
* - $logged_in: Flags true when the current user is a logged-in member.
* - $is_admin: Flags true when the current user is an administrator.
*
* @see template_preprocess()
* @see template_preprocess_taxonomy_term()
* @see template_process()
*
* @ingroup themeable
*/
?>
<?php
$output = "";
//$output .= "<h1>" . $term->tid . "</h1>";
$output .= "<!-- ARTIKEL START -->";
$output .= "<section id=\"taxonomy-term-" . $term->tid . "\" class=\"" . $classes . " aktivitetsside\">";
$output .= "<div class=\"container\">";
// Brødkrummesti
$output .= "<div class=\"row\">";
$output .= "<div class=\"grid-two-thirds\">";
$output .= "<p class=\"breadcrumbs\">" . theme('breadcrumb', array('breadcrumb'=>drupal_get_breadcrumb())) . " / " . $term_name . "</p>";
$output .= "</div>";
$output .= "</div>";
$output .= "<div class=\"row second\">";
$output .= "<div class=\"grid-two-thirds\">";
$output .= "<h1>Aktiviteter i kategorien \"" . $term_name . "\"</h1>";
// $output .= "<h1>" . $term_name . "</h1>";
$output .= "</div>";
$output .= "<div class=\"grid-third sociale-medier social-desktop\"></div>";
$output .= "</div>";
$output .= "<div class=\"row\">";
// $output .= "<div class=\"grid-two-thirds\">";
// $output .= "<!-- ARTIKEL TOP START -->";
// $output .= "<div class=\"artikel-top\">";
// $output .= "</div>";
// $output .= "<!-- ARTIKEL TOP SLUT -->";
// $output .= "<h1>Jaaaaaa, det virker!</h1>";
// $output .= render($content);
// DEL PÅ SOCIALE MEDIER
// include_once drupal_get_path('theme', 'ishoj') . '/includes/del-paa-sociale-medier.php';
// SENEST OPDATERET
// $output .= "<!-- SENEST OPDATERET START -->";
// $output .= "<p class=\"last-updated\">Senest opdateret " . format_date($node->changed, 'senest_redigeret') . "</p>";
// $output .= "<!-- SENEST OPDATERET SLUT -->";
// $output .= "</div>";
$output .= "<div class=\"activities node-visning\">";
$output .= "<div class=\"swiper-container-activities-aktivitetsside\">";
$output .= "<div class=\"swiper-wrapper\">";
$output .= views_embed_view('aktiviteter','aktivitet_aktiviteter_med_kategori', $term->tid);
$output .= "</div>";
$output .= "</div>";
$output .= "</div>";
// Højre kolonne
// Flyt (prepend) højrekolonne ind i klassen .view-aktiviteter
// $output .= "<div class=\"grid-third\">";
// $output .= "<h2>Jaaaa, man!!!</h2>";
// $output .= "</div>";
$output .= "</div>";
$output .= "</div>";
$output .= "</section>";
$output .= "<!-- ARTIKEL SLUT -->";
// DIMMER DEL SIDEN
$options = array('absolute' => TRUE);
// NODEVISNING
// $nid = $node->nid;
// $abs_url = url('node/' . $nid, $options);
// -----------
// TAXONOMIVISNING
$abs_url = url(substr($term_url, 1), $options);
include_once drupal_get_path('theme', 'ishoj') . '/includes/dimmer-del-siden.php';
?>
<!--<div id="taxonomy-term-<?php print $term->tid; ?>" class="<?php print $classes; ?>">-->
<?php// if (!$page): ?>
<!-- <h2><a href="<?php //print $term_url; ?>"><?php //print $term_name; ?></a></h2>-->
<?php //endif; ?>
<!-- <div class="content">-->
<?php// print render($content); ?>
<!-- </div>-->
<!--</div>-->
<?php
// BREAKING
print views_embed_view('kriseinformation', 'pagevisning');
// OUTPUT
print $output;
?>
| ishoj/ishoj.dk | public_html/sites/all/themes/ishoj/templates/taxonomy-term--aktivitetstype.tpl.php | PHP | gpl-2.0 | 5,453 |
// Copyright (C) 2007, 2008, 2009 EPITA Research and Development Laboratory (LRDE)
//
// This file is part of Olena.
//
// Olena 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.
//
// Olena 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 Olena. If not, see <http://www.gnu.org/licenses/>.
//
// As a special exception, you may use this file as part of a free
// software project without restriction. Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to produce
// an executable, this file does not by itself cause the resulting
// executable to be covered by the GNU General Public License. This
// exception does not however invalidate any other reasons why the
// executable file might be covered by the GNU General Public License.
#ifndef MLN_CANVAS_ALL_HH
# define MLN_CANVAS_ALL_HH
/// \file
///
/// File that includes all canvas-related routines.
namespace mln
{
/// Namespace of canvas.
namespace canvas
{
/// Implementation namespace of canvas namespace.
namespace impl {}
}
}
# include <mln/canvas/browsing/all.hh>
# include <mln/canvas/chamfer.hh>
# include <mln/canvas/distance_front.hh>
# include <mln/canvas/distance_geodesic.hh>
# include <mln/canvas/labeling/all.hh>
# include <mln/canvas/morpho/all.hh>
#endif // ! MLN_CANVAS_ALL_HH
| glazzara/olena | milena/mln/canvas/all.hh | C++ | gpl-2.0 | 1,796 |
<?php
/**
* pChart - a PHP class to build charts!
* Copyright (C) 2008 Jean-Damien POGOLOTTI
* Version 2.0
*
* http://pchart.sourceforge.net
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 1,2,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/>.
*/
spl_autoload_register('pChart_autoload');
function pChart_autoload($name){
$file = dirname(__FILE__).'/'.$name.'.php';
if(file_exists($file)) require_once($file);
}
/* Declare some script wide constants */
define ("SCALE_NORMAL", 1);
define ("SCALE_ADDALL", 2);
define ("SCALE_START0", 3);
define ("SCALE_ADDALLSTART0", 4);
define ("TARGET_GRAPHAREA", 1);
define ("TARGET_BACKGROUND", 2);
define ("ALIGN_TOP_LEFT", 1);
define ("ALIGN_TOP_CENTER", 2);
define ("ALIGN_TOP_RIGHT", 3);
define ("ALIGN_LEFT", 4);
define ("ALIGN_CENTER", 5);
define ("ALIGN_RIGHT", 6);
define ("ALIGN_BOTTOM_LEFT", 7);
define ("ALIGN_BOTTOM_CENTER", 8);
define ("ALIGN_BOTTOM_RIGHT", 9);
/**
* pChart class definition
*/
class pChart {
protected $palette;
/* Some static vars used in the class */
protected $XSize = NULL;
protected $YSize = NULL;
protected $Picture = NULL;
protected $ImageMap = NULL;
/* Error management */
protected $ErrorReporting = FALSE;
protected $ErrorInterface = "CLI";
protected $Errors = NULL;
protected $ErrorFontName = "Fonts/pf_arma_five.ttf";
protected $ErrorFontSize = 6;
/* vars related to the graphing area */
protected $GArea_X1 = NULL;
protected $GArea_Y1 = NULL;
protected $GArea_X2 = NULL;
protected $GArea_Y2 = NULL;
protected $GAreaXOffset = NULL;
protected $VMax = NULL;
protected $VMin = NULL;
protected $VXMax = NULL;
protected $VXMin = NULL;
protected $Divisions = NULL;
protected $XDivisions = NULL;
protected $DivisionHeight = NULL;
protected $XDivisionHeight = NULL;
protected $DivisionCount = NULL;
protected $XDivisionCount = NULL;
protected $DivisionRatio = NULL;
protected $XDivisionRatio = NULL;
protected $DivisionWidth = NULL;
protected $DataCount = NULL;
/* Text format related vars */
protected $FontName = NULL;
/** @var float $FontSize */
protected $FontSize = NULL;
protected $DateFormat = "d/m/Y";
/* Lines format related vars */
protected $LineWidth = 1;
protected $LineDotSize = 0;
/* Shadow settings */
private $shadowProperties;
/* Image Map settings */
protected $BuildMap = FALSE;
protected $MapFunction = NULL;
protected $tmpFolder = "tmp/";
protected $MapID = NULL;
/**
* @brief An abstract ICanvas onto which we draw the chart
*
* @todo This probably shouldn't be protected, I'm still working
* on how the modules are going to break down between the various
* chart types.
*/
protected $canvas = null;
/**
* Initializes the Graph and Canvas object
*/
public function __construct($XSize, $YSize, ICanvas $canvas) {
$this->palette = Palette::defaultPalette();
$this->XSize = $XSize;
$this->YSize = $YSize;
$this->setFontProperties("tahoma.ttf", 8);
$this->shadowProperties = ShadowProperties::FromDefaults();
$this->canvas = $canvas;
}
/**
* Set if warnings should be reported
*/
function reportWarnings($Interface = "CLI") {
$this->ErrorReporting = TRUE;
$this->ErrorInterface = $Interface;
}
/**
* Set the font properties
*
* Will be used for all following text operations.
*
* @param string $FontFile full path to the TTF font file
* @param float $FontSize
*/
function setFontProperties($FontFile, $FontSize) {
$this->FontName = $FontFile;
$this->FontSize = $FontSize;
}
/**
* Changes the color Palette
*
* @param Palette $newPalette
*/
public function setPalette(Palette $newPalette) {
$this->palette = $newPalette;
}
/**
* Set the shadow properties
*/
function setShadowProperties($XDistance = 1, $YDistance = 1, Color $color = null, $Alpha = 50, $Blur = 0) {
if($color == null) {
$color = new Color(60, 60, 60);
}
$this->shadowProperties = ShadowProperties::FromSettings(
$XDistance,
$YDistance,
$color,
$Alpha,
$Blur
);
}
/**
* Remove shadow option
*/
function clearShadow() {
$this->shadowProperties = ShadowProperties::FromDefaults();
}
/**
* Load Color Palette from file
*/
function loadColorPalette($FileName, $Delimiter = ",") {
$this->palette = Palette::fromFile($FileName, $Delimiter);
}
/**
* Set line style
*/
function setLineStyle($Width = 1, $DotSize = 0) {
$this->LineWidth = $Width;
$this->LineDotSize = $DotSize;
}
/**
* Set the graph area location
*/
function setGraphArea($X1, $Y1, $X2, $Y2) {
$this->GArea_X1 = $X1;
$this->GArea_Y1 = $Y1;
$this->GArea_X2 = $X2;
$this->GArea_Y2 = $Y2;
}
/**
* Prepare the graph area
*/
private function drawGraphArea(BackgroundStyle $style) {
$this->canvas->drawFilledRectangle(
new Point($this->GArea_X1, $this->GArea_Y1),
new Point($this->GArea_X2, $this->GArea_Y2),
$style->getBackgroundColor(),
$this->shadowProperties, FALSE
);
$this->canvas->drawRectangle(
new Point($this->GArea_X1, $this->GArea_Y1),
new Point($this->GArea_X2, $this->GArea_Y2),
$style->getBackgroundColor()->addRGBIncrement(-40),
$style->getBorderWidth(),
$style->getBorderDotSize(),
$this->shadowProperties
);
if($style->useStripe()) {
$color2 = $style->getBackgroundColor()->addRGBIncrement(-15);
$SkewWidth = $this->GArea_Y2 - $this->GArea_Y1 - 1;
for($i = $this->GArea_X1 - $SkewWidth; $i <= $this->GArea_X2; $i = $i + 4) {
$X1 = $i;
$Y1 = $this->GArea_Y2;
$X2 = $i + $SkewWidth;
$Y2 = $this->GArea_Y1;
if($X1 < $this->GArea_X1) {
$X1 = $this->GArea_X1;
$Y1 = $this->GArea_Y1 + $X2 - $this->GArea_X1 + 1;
}
if($X2 >= $this->GArea_X2) {
$Y2 = $this->GArea_Y1 + $X2 - $this->GArea_X2 + 1;
$X2 = $this->GArea_X2 - 1;
}
$this->canvas->drawLine(
new Point($X1, $Y1),
new Point($X2, $Y2 + 1),
$color2,
1,
0,
ShadowProperties::NoShadow()
);
}
}
}
public function drawGraphBackground(BackgroundStyle $style) {
$this->drawGraphArea($style);
$this->drawGraphAreaGradient($style);
}
/**
* Allow you to clear the scale : used if drawing multiple charts
*/
function clearScale() {
$this->VMin = NULL;
$this->VMax = NULL;
$this->VXMin = NULL;
$this->VXMax = NULL;
$this->Divisions = NULL;
$this->XDivisions = NULL;
}
/**
* Allow you to fix the scale, use this to bypass the automatic scaling
*/
function setFixedScale($VMin, $VMax, $Divisions = 5, $VXMin = 0, $VXMax = 0, $XDivisions = 5) {
$this->VMin = $VMin;
$this->VMax = $VMax;
$this->Divisions = $Divisions;
if(!$VXMin == 0) {
$this->VXMin = $VXMin;
$this->VXMax = $VXMax;
$this->XDivisions = $XDivisions;
}
}
/**
* Wrapper to the drawScale() function allowing a second scale to
* be drawn
*/
function drawRightScale(pData $data, ScaleStyle $style, $Angle = 0, $Decimals = 1, $WithMargin = FALSE, $SkipLabels = 1) {
$this->drawScale($data, $style, $Angle, $Decimals, $WithMargin, $SkipLabels, TRUE);
}
/**
* Compute and draw the scale
*/
function drawScale(pData $Data, ScaleStyle $style, $Angle = 0, $Decimals = 1, $WithMargin = FALSE, $SkipLabels = 1, $RightScale = FALSE) {
/* Validate the Data and DataDescription array */
$this->validateData("drawScale", $Data->getData());
$this->canvas->drawLine(
new Point($this->GArea_X1, $this->GArea_Y1),
new Point($this->GArea_X1, $this->GArea_Y2),
$style->getColor(),
$style->getLineWidth(),
$style->getLineDotSize(),
$this->shadowProperties
);
$this->canvas->drawLine(
new Point($this->GArea_X1, $this->GArea_Y2),
new Point($this->GArea_X2, $this->GArea_Y2),
$style->getColor(),
$style->getLineWidth(),
$style->getLineDotSize(),
$this->shadowProperties
);
if($this->VMin == NULL && $this->VMax == NULL) {
$Divisions = $this->calculateDivisions($Data, $style);
} else
$Divisions = $this->Divisions;
$this->DivisionCount = $Divisions;
$DataRange = $this->VMax - $this->VMin;
if($DataRange == 0) {
$DataRange = .1;
}
$this->DivisionHeight = ($this->GArea_Y2 - $this->GArea_Y1) / $Divisions;
$this->DivisionRatio = ($this->GArea_Y2 - $this->GArea_Y1) / $DataRange;
$this->GAreaXOffset = 0;
if(count($Data->getData()) > 1) {
if($WithMargin == FALSE)
$this->DivisionWidth = ($this->GArea_X2 - $this->GArea_X1) / (count($Data->getData()) - 1);
else {
$this->DivisionWidth = ($this->GArea_X2 - $this->GArea_X1) / (count($Data->getData()));
$this->GAreaXOffset = $this->DivisionWidth / 2;
}
} else {
$this->DivisionWidth = $this->GArea_X2 - $this->GArea_X1;
$this->GAreaXOffset = $this->DivisionWidth / 2;
}
$this->DataCount = count($Data->getData());
if($style->getDrawTicks() == FALSE)
return (0);
$YPos = $this->GArea_Y2;
$XMin = NULL;
for($i = 1; $i <= $Divisions + 1; $i++) {
if($RightScale)
$this->canvas->drawLine(
new Point($this->GArea_X2, $YPos),
new Point($this->GArea_X2 + 5, $YPos),
$style->getColor(),
$style->getLineWidth(),
$style->getLineDotSize(),
$this->shadowProperties
);
else
$this->canvas->drawLine(
new Point($this->GArea_X1, $YPos),
new Point($this->GArea_X1 - 5, $YPos),
$style->getColor(),
$style->getLineWidth(),
$style->getLineDotSize(),
$this->shadowProperties
);
$Value = $this->VMin + ($i - 1) * (($this->VMax - $this->VMin) / $Divisions);
$Value = round($Value * pow(10, $Decimals)) / pow(10, $Decimals);
$Value = $this->convertValueForDisplay(
$Value,
$Data->getDataDescription()->getYFormat(),
$Data->getDataDescription()->getYUnit()
);
$Position = imageftbbox($this->FontSize, 0, $this->FontName, $Value);
$TextWidth = $Position [2] - $Position [0];
if($RightScale) {
$this->canvas->drawText(
$this->FontSize, 0,
new Point($this->GArea_X2 + 10,
$YPos + ($this->FontSize / 2)),
$style->getColor(),
$this->FontName,
$Value,
ShadowProperties::NoShadow()
);
if($XMin < $this->GArea_X2 + 15 + $TextWidth || $XMin == NULL) {
$XMin = $this->GArea_X2 + 15 + $TextWidth;
}
} else {
$this->canvas->drawText(
$this->FontSize,
0,
new Point($this->GArea_X1 - 10 - $TextWidth,
$YPos + ($this->FontSize / 2)),
$style->getColor(),
$this->FontName,
$Value,
ShadowProperties::NoShadow()
);
if($XMin > $this->GArea_X1 - 10 - $TextWidth || $XMin == NULL) {
$XMin = $this->GArea_X1 - 10 - $TextWidth;
}
}
$YPos = $YPos - $this->DivisionHeight;
}
/* Write the Y Axis caption if set */
if($Data->getDataDescription()->getYAxisName() != '') {
$Position = imageftbbox($this->FontSize, 90, $this->FontName, $Data->getDataDescription()->getYAxisName());
$TextHeight = abs($Position [1]) + abs($Position [3]);
$TextTop = (($this->GArea_Y2 - $this->GArea_Y1) / 2) + $this->GArea_Y1 + ($TextHeight / 2);
if($RightScale) {
$this->canvas->drawText(
$this->FontSize, 90,
new Point($XMin + $this->FontSize,
$TextTop),
$style->getColor(), $this->FontName,
$Data->getDataDescription()->getYAxisName(),
ShadowProperties::NoShadow()
);
} else {
$this->canvas->drawText(
$this->FontSize, 90,
new Point($XMin - $this->FontSize,
$TextTop),
$style->getColor(), $this->FontName,
$Data->getDataDescription()->getYAxisName(),
ShadowProperties::NoShadow()
);
}
}
/* Horizontal Axis */
$XPos = $this->GArea_X1 + $this->GAreaXOffset;
$ID = 1;
$YMax = NULL;
foreach($Data->getData() as $Values) {
if($ID % $SkipLabels == 0) {
$this->canvas->drawLine(
new Point(floor($XPos), $this->GArea_Y2),
new Point(floor($XPos), $this->GArea_Y2 + 5),
$style->getColor(),
$style->getLineWidth(),
$style->getLineDotSize(),
$this->shadowProperties
);
$Value = $Values[$Data->getDataDescription()->getPosition()];
$Value = $this->convertValueForDisplay(
$Value,
$Data->getDataDescription()->getXFormat(),
$Data->getDataDescription()->getXUnit()
);
$Position = imageftbbox($this->FontSize, $Angle, $this->FontName, $Value);
$TextWidth = abs($Position [2]) + abs($Position [0]);
$TextHeight = abs($Position [1]) + abs($Position [3]);
if($Angle == 0) {
$YPos = $this->GArea_Y2 + 18;
$this->canvas->drawText(
$this->FontSize,
$Angle,
new Point(floor($XPos) - floor($TextWidth / 2),
$YPos),
$style->getColor(),
$this->FontName,
$Value,
ShadowProperties::NoShadow()
);
} else {
$YPos = $this->GArea_Y2 + 10 + $TextHeight;
if($Angle <= 90) {
$this->canvas->drawText(
$this->FontSize,
$Angle,
new Point(floor($XPos) - $TextWidth + 5,
$YPos),
$style->getColor(),
$this->FontName,
$Value,
ShadowProperties::NoShadow()
);
} else {
$this->canvas->drawText(
$this->FontSize,
$Angle,
new Point(floor($XPos) + $TextWidth + 5,
$YPos),
$style->getColor(),
$this->FontName,
$Value,
ShadowProperties::NoShadow()
);
}
}
if($YMax < $YPos || $YMax == NULL) {
$YMax = $YPos;
}
}
$XPos = $XPos + $this->DivisionWidth;
$ID++;
}
/* Write the X Axis caption if set */
if($Data->getDataDescription()->getXAxisName() != '') {
$Position = imageftbbox(
$this->FontSize, 90,
$this->FontName,
$Data->getDataDescription()->getXAxisName()
);
$TextWidth = abs($Position [2]) + abs($Position [0]);
$TextLeft = (($this->GArea_X2 - $this->GArea_X1) / 2) + $this->GArea_X1 + ($TextWidth / 2);
$this->canvas->drawText(
$this->FontSize, 0,
new Point($TextLeft,
$YMax + $this->FontSize + 5),
$style->getColor(), $this->FontName,
$Data->getDataDescription()->getXAxisName(),
ShadowProperties::NoShadow()
);
}
}
/**
* Calculate the number of divisions that the Y axis will be
* divided into. This is a function of the range of Y values the
* data covers, as well as the scale style. Divisions should have
* some minimum size in screen coordinates in order that the
* divisions are clearly visible, so this is also a function of
* the graph size in screen coordinates.
*
* This method returns the number of divisions, but it also has
* side-effects on some class data members. This needs to be
* refactored to make it clearer what is and isn't affected.
*/
private function calculateDivisions(pData $Data, ScaleStyle $style) {
if(isset ($Data->getDataDescription()->values[0])) {
/* Pointless temporary is necessary because you can't
* directly apply an array index to the return value
* of a function in PHP */
$dataArray = $Data->getData();
$this->VMin = $dataArray[0] [$Data->getDataDescription()->values[0]];
$this->VMax = $dataArray[0] [$Data->getDataDescription()->values[0]];
} else {
$this->VMin = 2147483647;
$this->VMax = -2147483647;
}
/* Compute Min and Max values */
if($style->getScaleMode() == SCALE_NORMAL
|| $style->getScaleMode() == SCALE_START0
) {
if($style->getScaleMode() == SCALE_START0) {
$this->VMin = 0;
}
foreach($Data->getData() as $Values) {
foreach($Data->getDataDescription()->values as $ColName) {
if(isset ($Values[$ColName])) {
$Value = $Values[$ColName];
if(is_numeric($Value)) {
if($this->VMax < $Value) {
$this->VMax = $Value;
}
if($this->VMin > $Value) {
$this->VMin = $Value;
}
}
}
}
}
} elseif($style->getScaleMode() == SCALE_ADDALL || $style->getScaleMode() == SCALE_ADDALLSTART0) /* Experimental */ {
if($style->getScaleMode() == SCALE_ADDALLSTART0) {
$this->VMin = 0;
}
foreach($Data->getData() as $Values) {
$Sum = 0;
foreach($Data->getDataDescription()->values as $ColName) {
$dataArray = $Data->getData();
if(isset ($Values[$ColName])) {
$Value = $Values[$ColName];
if(is_numeric($Value))
$Sum += $Value;
}
}
if($this->VMax < $Sum) {
$this->VMax = $Sum;
}
if($this->VMin > $Sum) {
$this->VMin = $Sum;
}
}
}
$this->VMax = ceil($this->VMax);
/* If all values are the same */
if($this->VMax == $this->VMin) {
if($this->VMax >= 0) {
$this->VMax++;
} else {
$this->VMin--;
}
}
$DataRange = $this->VMax - $this->VMin;
if($DataRange == 0) {
$DataRange = .1;
}
$this->calculateScales($Scale, $Divisions);
if(!isset ($Divisions))
$Divisions = 2;
if($Scale == 1 && $Divisions % 2 == 1)
$Divisions--;
return $Divisions;
}
/**
* Compute and draw the scale for X/Y charts
*/
function drawXYScale(pData $Data, ScaleStyle $style, $YSerieName, $XSerieName, $Angle = 0, $Decimals = 1) {
/* Validate the Data and DataDescription array */
$this->validateData("drawScale", $Data->getData());
$this->canvas->drawLine(
new Point($this->GArea_X1, $this->GArea_Y1),
new Point($this->GArea_X1, $this->GArea_Y2),
$style->getColor(),
$style->getLineWidth(),
$style->getLineDotSize(),
$this->shadowProperties
);
$this->canvas->drawLine(
new Point($this->GArea_X1, $this->GArea_Y2),
new Point($this->GArea_X2, $this->GArea_Y2),
$style->getColor(),
$style->getLineWidth(),
$style->getLineDotSize(),
$this->shadowProperties
);
/* Process Y scale */
if($this->VMin == NULL && $this->VMax == NULL) {
$this->VMin = $Data->getSeriesMin($YSerieName);
$this->VMax = $Data->getSeriesMax($YSerieName);
/** @todo The use of ceil() here is questionable if all
* the values are much less than 1, AIUI */
$this->VMax = ceil($this->VMax);
$DataRange = $this->VMax - $this->VMin;
if($DataRange == 0) {
$DataRange = .1;
}
self::computeAutomaticScaling(
$this->GArea_Y1,
$this->GArea_Y2,
$this->VMin,
$this->VMax,
$Divisions
);
} else
$Divisions = $this->Divisions;
$this->DivisionCount = $Divisions;
$DataRange = $this->VMax - $this->VMin;
if($DataRange == 0) {
$DataRange = .1;
}
$this->DivisionHeight = ($this->GArea_Y2 - $this->GArea_Y1) / $Divisions;
$this->DivisionRatio = ($this->GArea_Y2 - $this->GArea_Y1) / $DataRange;
$YPos = $this->GArea_Y2;
$XMin = NULL;
for($i = 1; $i <= $Divisions + 1; $i++) {
$this->canvas->drawLine(
new Point($this->GArea_X1, $YPos),
new Point($this->GArea_X1 - 5, $YPos),
$style->getColor(),
$style->getLineWidth(),
$style->getLineDotSize(),
$this->shadowProperties
);
$Value = $this->VMin + ($i - 1) * (($this->VMax - $this->VMin) / $Divisions);
$Value = round($Value * pow(10, $Decimals)) / pow(10, $Decimals);
$Value = $this->convertValueForDisplay(
$Value,
$Data->getDataDescription()->getYFormat(),
$Data->getDataDescription()->getYUnit()
);
$Position = imageftbbox($this->FontSize, 0, $this->FontName, $Value);
$TextWidth = $Position [2] - $Position [0];
$this->canvas->drawText(
$this->FontSize,
0,
new Point($this->GArea_X1 - 10 - $TextWidth,
$YPos + ($this->FontSize / 2)),
$style->getColor(),
$this->FontName,
$Value,
$this->shadowProperties
);
if($XMin > $this->GArea_X1 - 10 - $TextWidth || $XMin == NULL) {
$XMin = $this->GArea_X1 - 10 - $TextWidth;
}
$YPos = $YPos - $this->DivisionHeight;
}
/* Process X scale */
if($this->VXMin == NULL && $this->VXMax == NULL) {
$this->VXMax = $Data->getSeriesMax($XSerieName);
$this->VXMin = $Data->getSeriesMin($XSerieName);
$this->VXMax = ceil($this->VXMax);
$DataRange = $this->VMax - $this->VMin;
if($DataRange == 0) {
$DataRange = .1;
}
/* Compute automatic scaling */
self::computeAutomaticScaling(
$this->GArea_X1, $this->GArea_X2,
$this->VXMin, $this->VXMax,
$XDivisions
);
} else
$XDivisions = $this->XDivisions;
$this->XDivisionCount = $Divisions;
$this->DataCount = $Divisions + 2;
$XDataRange = $this->VXMax - $this->VXMin;
if($XDataRange == 0) {
$XDataRange = .1;
}
$this->DivisionWidth = ($this->GArea_X2 - $this->GArea_X1) / $XDivisions;
$this->XDivisionRatio = ($this->GArea_X2 - $this->GArea_X1) / $XDataRange;
$XPos = $this->GArea_X1;
$YMax = NULL;
for($i = 1; $i <= $XDivisions + 1; $i++) {
$this->canvas->drawLine(
new Point($XPos, $this->GArea_Y2),
new Point($XPos, $this->GArea_Y2 + 5),
$style->getColor(),
$style->getLineWidth(),
$style->getLineDotSize(),
$this->shadowProperties
);
$Value = $this->VXMin + ($i - 1) * (($this->VXMax - $this->VXMin) / $XDivisions);
$Value = round($Value * pow(10, $Decimals)) / pow(10, $Decimals);
$Value = $this->convertValueForDisplay(
$Value,
$Data->getDataDescription()->getYFormat(),
$Data->getDataDescription()->getYUnit()
);
$Position = imageftbbox($this->FontSize, $Angle, $this->FontName, $Value);
$TextWidth = abs($Position [2]) + abs($Position [0]);
$TextHeight = abs($Position [1]) + abs($Position [3]);
if($Angle == 0) {
$YPos = $this->GArea_Y2 + 18;
$this->canvas->drawText(
$this->FontSize,
$Angle,
new Point(floor($XPos) - floor($TextWidth / 2),
$YPos),
$style->getColor(),
$this->FontName,
$Value,
$this->shadowProperties
);
} else {
$YPos = $this->GArea_Y2 + 10 + $TextHeight;
if($Angle <= 90) {
$this->canvas->drawText(
$this->FontSize,
$Angle,
new Point(floor($XPos) - $TextWidth + 5,
$YPos),
$style->getColor(),
$this->FontName,
$Value,
$this->shadowProperties
);
} else {
$this->canvas->drawText(
$this->FontSize,
$Angle,
new Point(floor($XPos) + $TextWidth + 5,
$YPos),
$style->getColor(),
$this->FontName,
$Value,
$this->shadowProperties
);
}
}
if($YMax < $YPos || $YMax == NULL) {
$YMax = $YPos;
}
$XPos = $XPos + $this->DivisionWidth;
}
/* Write the Y Axis caption if set */
if($Data->getDataDescription()->getYAxisName() != '') {
$Position = imageftbbox(
$this->FontSize, 90, $this->FontName,
$Data->getDataDescription()->getYAxisName()
);
$TextHeight = abs($Position [1]) + abs($Position [3]);
$TextTop = (($this->GArea_Y2 - $this->GArea_Y1) / 2) + $this->GArea_Y1 + ($TextHeight / 2);
$this->canvas->drawText(
$this->FontSize,
90,
new Point($XMin - $this->FontSize,
$TextTop),
$style->getColor(),
$this->FontName,
$Data->getDataDescription()->getYAxisName(),
$this->shadowProperties
);
}
/* Write the X Axis caption if set */
$this->writeScaleXAxisCaption($Data, $style, $YMax);
}
private function drawGridMosaic(GridStyle $style, $divisionCount, $divisionHeight) {
$LayerHeight = $this->GArea_Y2 - $this->GArea_Y1;
$YPos = $LayerHeight - 1; //$this->GArea_Y2-1;
$LastY = $YPos;
for($i = 0; $i < $divisionCount; $i++) {
$LastY = $YPos;
$YPos = $YPos - $divisionHeight;
if($YPos <= 0) {
$YPos = 1;
}
if($i % 2 == 0) {
$this->canvas->drawFilledRectangle(
new Point($this->GArea_X1 + 1,
$this->GArea_Y1 + $YPos),
new Point($this->GArea_X2 - 1,
$this->GArea_Y1 + $LastY),
new Color(250, 250, 250),
ShadowProperties::NoShadow(),
false,
$style->getAlpha()
);
}
}
}
/**
* Write the X Axis caption on the scale, if set
*/
private function writeScaleXAxisCaption(pData $data, ScaleStyle $style, $YMax) {
if($data->getDataDescription()->getXAxisName() != '') {
$Position = imageftbbox($this->FontSize, 90, $this->FontName, $data->getDataDescription()->getXAxisName());
$TextWidth = abs($Position [2]) + abs($Position [0]);
$TextLeft = (($this->GArea_X2 - $this->GArea_X1) / 2) + $this->GArea_X1 + ($TextWidth / 2);
$this->canvas->drawText(
$this->FontSize,
0,
new Point($TextLeft,
$YMax + $this->FontSize + 5),
$style->getColor(),
$this->FontName,
$data->getDataDescription()->getXAxisName(),
$this->shadowProperties
);
}
}
/**
* Compute and draw the scale
*/
function drawGrid(GridStyle $style) {
/* Draw mosaic */
if($style->getMosaic()) {
$this->drawGridMosaic($style, $this->DivisionCount, $this->DivisionHeight);
}
/* Horizontal lines */
$YPos = $this->GArea_Y2 - $this->DivisionHeight;
for($i = 1; $i <= $this->DivisionCount; $i++) {
if($YPos > $this->GArea_Y1 && $YPos < $this->GArea_Y2)
$this->canvas->drawDottedLine(
new Point($this->GArea_X1, $YPos),
new Point($this->GArea_X2, $YPos),
$style->getLineWidth(),
$this->LineWidth,
$style->getColor(),
ShadowProperties::NoShadow()
);
/** @todo There's some inconsistency here. The parameter
* $lineWidth appears to be used to control the dot size,
* not the line width? This is the same way it's always
* been done, although now it's more obvious that there's
* a problem. */
$YPos = $YPos - $this->DivisionHeight;
}
/* Vertical lines */
if($this->GAreaXOffset == 0) {
$XPos = $this->GArea_X1 + $this->DivisionWidth + $this->GAreaXOffset;
$ColCount = $this->DataCount - 2;
} else {
$XPos = $this->GArea_X1 + $this->GAreaXOffset;
$ColCount = floor(($this->GArea_X2 - $this->GArea_X1) / $this->DivisionWidth);
}
for($i = 1; $i <= $ColCount; $i++) {
if($XPos > $this->GArea_X1 && $XPos < $this->GArea_X2)
$this->canvas->drawDottedLine(
new Point(floor($XPos), $this->GArea_Y1),
new Point(floor($XPos), $this->GArea_Y2),
$style->getLineWidth(),
$this->LineWidth,
$style->getcolor(),
$this->shadowProperties
);
$XPos = $XPos + $this->DivisionWidth;
}
}
/**
* retrieve the legends size
*/
public function getLegendBoxSize($DataDescription) {
if(!isset ($DataDescription->description))
return (-1);
/* <-10->[8]<-4->Text<-10-> */
$MaxWidth = 0;
$MaxHeight = 8;
foreach($DataDescription->description as $Value) {
$Position = imageftbbox($this->FontSize, 0, $this->FontName, $Value);
$TextWidth = $Position [2] - $Position [0];
$TextHeight = $Position [1] - $Position [7];
if($TextWidth > $MaxWidth) {
$MaxWidth = $TextWidth;
}
$MaxHeight = $MaxHeight + $TextHeight + 4;
}
$MaxHeight = $MaxHeight - 3;
$MaxWidth = $MaxWidth + 32;
return (array($MaxWidth, $MaxHeight));
}
/**
* Draw the data legends
*/
public function drawLegend($XPos, $YPos, $DataDescription, Color $color, Color $color2 = null, Color $color3 = null, $Border = TRUE) {
if($color2 == null) {
$color2 = $color->addRGBIncrement(-30);
}
if($color3 == null) {
$color3 = new Color(0, 0, 0);
}
/* Validate the Data and DataDescription array */
$this->validateDataDescription("drawLegend", $DataDescription);
if(!isset ($DataDescription->description))
return (-1);
/* <-10->[8]<-4->Text<-10-> */
$MaxWidth = 0;
$MaxHeight = 8;
foreach($DataDescription->description as $Key => $Value) {
$Position = imageftbbox($this->FontSize, 0, $this->FontName, $Value);
$TextWidth = $Position [2] - $Position [0];
$TextHeight = $Position [1] - $Position [7];
if($TextWidth > $MaxWidth) {
$MaxWidth = $TextWidth;
}
$MaxHeight = $MaxHeight + $TextHeight + 4;
}
$MaxHeight = $MaxHeight - 5;
$MaxWidth = $MaxWidth + 32;
if($Border) {
$this->canvas->drawFilledRoundedRectangle(
new Point($XPos + 1, $YPos + 1),
new Point($XPos + $MaxWidth + 1,
$YPos + $MaxHeight + 1),
5, $color2,
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
$this->canvas->drawFilledRoundedRectangle(
new Point($XPos, $YPos),
new Point($XPos + $MaxWidth,
$YPos + $MaxHeight),
5, $color,
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
}
$YOffset = 4 + $this->FontSize;
$ID = 0;
foreach($DataDescription->description as $Key => $Value) {
$this->canvas->drawFilledRoundedRectangle(
new Point($XPos + 10,
$YPos + $YOffset - 4),
new Point($XPos + 14,
$YPos + $YOffset - 4),
2,
$this->palette->getColor($ID),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
$this->canvas->drawText(
$this->FontSize,
0,
new Point($XPos + 22,
$YPos + $YOffset),
$color3,
$this->FontName,
$Value,
$this->shadowProperties
);
$Position = imageftbbox($this->FontSize, 0, $this->FontName, $Value);
$TextHeight = $Position [1] - $Position [7];
$YOffset = $YOffset + $TextHeight + 4;
$ID++;
}
}
/**
* Draw the graph title
*
* @todo Should we pass in a ShadowProperties object here? Or is
* this a public function?
*/
public function drawTitle($XPos, $YPos, $Value, Color $color, $XPos2 = -1, $YPos2 = -1, ShadowProperties $shadowProperties = null) {
if($shadowProperties == null) {
$shadowProperties = ShadowProperties::NoShadow();
}
if($XPos2 != -1) {
$Position = imageftbbox($this->FontSize, 0, $this->FontName, $Value);
$TextWidth = $Position [2] - $Position [0];
$XPos = floor(($XPos2 - $XPos - $TextWidth) / 2) + $XPos;
}
if($YPos2 != -1) {
$Position = imageftbbox($this->FontSize, 0, $this->FontName, $Value);
$TextHeight = $Position [5] - $Position [3];
$YPos = floor(($YPos2 - $YPos - $TextHeight) / 2) + $YPos;
}
$this->canvas->drawText(
$this->FontSize,
0,
new Point($XPos, $YPos),
$color,
$this->FontName,
$Value,
$shadowProperties
);
}
/**
* Draw a text box with text align & alpha properties
*
* @param $point1 Minimum corner of the box
* @param $point2 Maximum corner of the box
*
* @todo This should probably be a method on the ICanvas
* interface, since it doesn't have anything specifically to do
* with graphs
*/
public function drawTextBox(Point $point1, Point $point2, $Text, $Angle = 0, Color $color = null, $Align = ALIGN_LEFT, ShadowProperties $shadowProperties = null, Color $backgroundColor = null, $Alpha = 100) {
if($color == null) {
$color = new Color(255, 255, 255);
}
if($shadowProperties == null) {
$shadowProperties = ShadowProperties::NoShadow();
}
$Position = imageftbbox($this->FontSize, $Angle, $this->FontName, $Text);
$TextWidth = $Position [2] - $Position [0];
$TextHeight = $Position [5] - $Position [3];
$AreaWidth = $point2->getX() - $point1->getX();
$AreaHeight = $point2->getY() - $point1->getY();
if($backgroundColor != null)
$this->canvas->drawFilledRectangle(
$point1,
$point2,
$backgroundColor,
$shadowProperties, FALSE, $Alpha
);
if($Align == ALIGN_TOP_LEFT) {
$newPosition = $point1->addIncrement(1, $this->FontSize + 1);
}
if($Align == ALIGN_TOP_CENTER) {
$newPosition = $point1->addIncrement(
($AreaWidth / 2) - ($TextWidth / 2),
$this->FontSize + 1
);
}
if($Align == ALIGN_TOP_RIGHT) {
$newPosition = new Point($point2->getX() - $TextWidth - 1,
$point1->getY() + $this->FontSize + 1);
}
if($Align == ALIGN_LEFT) {
$newPosition = $point1->addIncrement(
1,
($AreaHeight / 2) - ($TextHeight / 2)
);
}
if($Align == ALIGN_CENTER) {
$newPosition = $point1->addIncrement(
($AreaWidth / 2) - ($TextWidth / 2),
($AreaHeight / 2) - ($TextHeight / 2)
);
}
if($Align == ALIGN_RIGHT) {
$newPosition = new Point($point2->getX() - $TextWidth - 1,
$point1->getY() + ($AreaHeight / 2) - ($TextHeight / 2));
}
if($Align == ALIGN_BOTTOM_LEFT) {
$newPosition = new Point($point1->getX() + 1,
$point2->getY() - 1);
}
if($Align == ALIGN_BOTTOM_CENTER) {
$newPosition = new Point($point1->getX() + ($AreaWidth / 2) - ($TextWidth / 2),
$point2->getY() - 1);
}
if($Align == ALIGN_BOTTOM_RIGHT) {
$newPosition = $point2->addIncrement(
-$TextWidth - 1,
-1
);
}
$this->canvas->drawText($this->FontSize, $Angle, $newPosition, $color, $this->FontName, $Text, $shadowProperties);
}
/**
* Compute and draw the scale
*
* @todo What is the method name a typo for? Threshold?
*/
function drawTreshold($Value, Color $color, $ShowLabel = FALSE, $ShowOnRight = FALSE, $TickWidth = 4, $FreeText = NULL) {
$Y = $this->GArea_Y2 - ($Value - $this->VMin) * $this->DivisionRatio;
if($Y <= $this->GArea_Y1 || $Y >= $this->GArea_Y2)
return (-1);
if($TickWidth == 0)
$this->canvas->drawLine(
new Point($this->GArea_X1, $Y),
new Point($this->GArea_X2, $Y),
$color,
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
else
$this->canvas->drawDottedLine(
new Point($this->GArea_X1, $Y),
new Point($this->GArea_X2, $Y),
$TickWidth,
$this->LineWidth,
$color,
$this->shadowProperties
);
if($ShowLabel) {
if($FreeText == NULL) {
$Label = $Value;
} else {
$Label = $FreeText;
}
if($ShowOnRight) {
$position = new Point($this->GArea_X2 + 2,
$Y + ($this->FontSize / 2));
} else {
$position = new Point($this->GArea_X1 + 2,
$Y - ($this->FontSize / 2));
}
$this->canvas->drawText(
$this->FontSize, 0,
$position,
$color,
$this->FontName,
$Label,
ShadowProperties::NoShadow()
);
}
}
/**
* This function put a label on a specific point
*/
function setLabel($Data, $DataDescription, $SerieName, $ValueName, $Caption, Color $color = null) {
if($color == null) {
$color = new Color(210, 210, 210);
}
/* Validate the Data and DataDescription array */
$this->validateDataDescription("setLabel", $DataDescription);
$this->validateData("setLabel", $Data);
$ShadowFactor = 100;
$Cp = 0;
$Found = FALSE;
foreach($Data as $Value) {
if($Value[$DataDescription->getPosition()] == $ValueName) {
$NumericalValue = $Value[$SerieName];
$Found = TRUE;
}
if(!$Found)
$Cp++;
}
$XPos = $this->GArea_X1 + $this->GAreaXOffset + ($this->DivisionWidth * $Cp) + 2;
$YPos = $this->GArea_Y2 - ($NumericalValue - $this->VMin) * $this->DivisionRatio;
$Position = imageftbbox($this->FontSize, 0, $this->FontName, $Caption);
$TextHeight = $Position [3] - $Position [5];
$TextWidth = $Position [2] - $Position [0] + 2;
$TextOffset = floor($TextHeight / 2);
// Shadow
$Poly = array($XPos + 1, $YPos + 1, $XPos + 9, $YPos - $TextOffset, $XPos + 8, $YPos + $TextOffset + 2);
$this->canvas->drawFilledPolygon(
$Poly,
3,
$color->addRGBIncrement(-$ShadowFactor)
);
$this->canvas->drawLine(
new Point($XPos, $YPos + 1),
new Point($XPos + 9, $YPos - $TextOffset - .2),
$color->addRGBIncrement(-$ShadowFactor),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
$this->canvas->drawLine(
new Point($XPos, $YPos + 1),
new Point($XPos + 9, $YPos + $TextOffset + 2.2),
$color->addRGBIncrement(-$ShadowFactor),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
$this->canvas->drawFilledRectangle(
new Point($XPos + 9,
$YPos - $TextOffset - .2),
new Point($XPos + 13 + $TextWidth,
$YPos + $TextOffset + 2.2),
$color->addRGBIncrement(-$ShadowFactor),
$this->shadowProperties
);
// Label background
$Poly = array($XPos, $YPos, $XPos + 8, $YPos - $TextOffset - 1, $XPos + 8, $YPos + $TextOffset + 1);
$this->canvas->drawFilledPolygon($Poly, 3, $color);
/** @todo We draw exactly the same line twice, with the same settings.
* Surely this is pointless? */
$this->canvas->drawLine(
new Point($XPos - 1, $YPos),
new Point($XPos + 8, $YPos - $TextOffset - 1.2),
$color,
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
$this->canvas->drawLine(
new Point($XPos - 1, $YPos),
new Point($XPos + 8, $YPos + $TextOffset + 1.2),
$color,
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
$this->canvas->drawFilledRectangle(
new Point($XPos + 8,
$YPos - $TextOffset - 1.2),
new Point($XPos + 12 + $TextWidth,
$YPos + $TextOffset + 1.2),
$color,
$this->shadowProperties
);
$this->canvas->drawText(
$this->FontSize,
0,
new Point($XPos + 10, $YPos + $TextOffset),
new Color(0, 0, 0),
$this->FontName,
$Caption,
ShadowProperties::NoShadow()
);
}
/**
* Linearly Scale a given value
*
* using it's own minima/maxima and the desired output minima/maxima
*/
function linearScale($value, $istart, $istop, $ostart, $ostop) {
$div = ($istop - $istart);
if($div == 0.0) $div = 1;
return $ostart + ($ostop - $ostart) * (($value - $istart) / $div);
}
/**
* This function draw a plot graph
*/
function drawPlotGraph($Data, $DataDescription, $BigRadius = 5, $SmallRadius = 2, Color $color2 = null, $Shadow = FALSE) {
/* Validate the Data and DataDescription array */
$this->validateDataDescription("drawPlotGraph", $DataDescription);
$this->validateData("drawPlotGraph", $Data);
$GraphID = 0;
$colorO = $color2;
foreach($DataDescription->values as $ColName) {
$ColorID = $DataDescription->getColumnIndex($ColName);
$color = $this->palette->getColor($ColorID);
$color2 = $colorO;
if(isset ($DataDescription->seriesSymbols[$ColName])) {
$Infos = getimagesize($DataDescription->seriesSymbols[$ColName]);
$ImageWidth = $Infos [0];
$ImageHeight = $Infos [1];
$Symbol = imagecreatefromgif($DataDescription->seriesSymbols[$ColName]);
}
$XPos = $this->GArea_X1 + $this->GAreaXOffset;
$Hsize = round($BigRadius / 2);
$color3 = null;
foreach($Data as $Values) {
$Value = $Values[$ColName];
$YPos = $this->GArea_Y2 - (($Value - $this->VMin) * $this->DivisionRatio);
/* Save point into the image map if option activated */
if($this->BuildMap)
$this->addToImageMap($XPos - $Hsize, $YPos - $Hsize, $XPos + 1 + $Hsize, $YPos + $Hsize + 1, $DataDescription->description[$ColName], $Values[$ColName].$DataDescription->getYUnit(), "Plot");
if(is_numeric($Value)) {
if(!isset ($DataDescription->seriesSymbols[$ColName])) {
if($Shadow) {
if($color3 != null) {
$this->canvas->drawFilledCircle(
new Point($XPos + 2,
$YPos + 2),
$BigRadius,
$color3,
$this->shadowProperties
);
} else {
$color3 = $this->palette->getColor($ColorID)->addRGBIncrement(-20);
$this->canvas->drawFilledCircle(
new Point($XPos + 2,
$YPos + 2),
$BigRadius,
$color3,
$this->shadowProperties
);
}
}
$this->canvas->drawFilledCircle(
new Point($XPos + 1,
$YPos + 1),
$BigRadius,
$color,
$this->shadowProperties
);
if($SmallRadius != 0) {
if($color2 != null) {
$this->canvas->drawFilledCircle(
new Point($XPos + 1,
$YPos + 1),
$SmallRadius,
$color2,
$this->shadowProperties
);
} else {
$color2 = $this->palette->getColor($ColorID)->addRGBIncrement(-15);
$this->canvas->drawFilledCircle(
new Point($XPos + 1,
$YPos + 1),
$SmallRadius,
$color2,
$this->shadowProperties
);
}
}
} else {
imagecopymerge($this->canvas->getPicture(), $Symbol, $XPos + 1 - $ImageWidth / 2, $YPos + 1 - $ImageHeight / 2, 0, 0, $ImageWidth, $ImageHeight, 100);
}
}
$XPos = $XPos + $this->DivisionWidth;
}
$GraphID++;
}
}
/**
* @brief This function draw a plot graph in an X/Y space
*/
function drawXYPlotGraph(pData $DataSet, $YSerieName, $XSerieName, $PaletteID = 0, $BigRadius = 5, $SmallRadius = 2, Color $color2 = null, $Shadow = TRUE, $SizeSerieName = '') {
$color = $this->palette->getColor($PaletteID);
$color3 = null;
$Data = $DataSet->getData();
foreach($Data as $Values) {
if(isset($Values[$YSerieName]) && isset ($Values[$XSerieName])) {
$X = $Values[$XSerieName];
$Y = $Values[$YSerieName];
$Y = $this->GArea_Y2 - (($Y - $this->VMin) * $this->DivisionRatio);
$X = $this->GArea_X1 + (($X - $this->VXMin) * $this->XDivisionRatio);
if(isset($Values[$SizeSerieName])) {
$br = $this->linearScale(
$Values[$SizeSerieName],
$DataSet->getSeriesMin($SizeSerieName),
$DataSet->getSeriesMax($SizeSerieName),
$SmallRadius,
$BigRadius
);
$sr = $br;
} else {
$br = $BigRadius;
$sr = $SmallRadius;
}
if($Shadow) {
if($color3 != null) {
$this->canvas->drawFilledCircle(
new Point($X + 2, $Y + 2),
$br,
$color3,
$this->shadowProperties
);
} else {
$color3 = $this->palette->getColor($PaletteID)->addRGBIncrement(-20);
$this->canvas->drawFilledCircle(
new Point($X + 2, $Y + 2),
$br,
$color3,
$this->shadowProperties
);
}
}
$this->canvas->drawFilledCircle(
new Point($X + 1, $Y + 1),
$br,
$color,
$this->shadowProperties
);
if($color2 != null) {
$this->canvas->drawFilledCircle(
new Point($X + 1, $Y + 1),
$sr,
$color2,
$this->shadowProperties
);
} else {
$color2 = $this->palette->getColor($PaletteID)->addRGBIncrement(20);
$this->canvas->drawFilledCircle(
new Point($X + 1, $Y + 1),
$sr,
$color2,
$this->shadowProperties
);
}
}
}
}
/**
* This function draw an area between two series
*/
function drawArea($Data, $Serie1, $Serie2, Color $color, $Alpha = 50) {
/* Validate the Data and DataDescription array */
$this->validateData("drawArea", $Data);
$LayerHeight = $this->GArea_Y2 - $this->GArea_Y1;
$XPos = $this->GAreaXOffset;
$LastXPos = -1;
$LastYPos1 = 0;
$LastYPos2 = 0;
foreach($Data as $Values) {
$Value1 = $Values[$Serie1];
$Value2 = $Values[$Serie2];
$YPos1 = $LayerHeight - (($Value1 - $this->VMin) * $this->DivisionRatio);
$YPos2 = $LayerHeight - (($Value2 - $this->VMin) * $this->DivisionRatio);
if($LastXPos != -1) {
$Points = array();
$Points [] = $LastXPos + $this->GArea_X1;
$Points [] = $LastYPos1 + $this->GArea_Y1;
$Points [] = $LastXPos + $this->GArea_X1;
$Points [] = $LastYPos2 + $this->GArea_Y1;
$Points [] = $XPos + $this->GArea_X1;
$Points [] = $YPos2 + $this->GArea_Y1;
$Points [] = $XPos + $this->GArea_X1;
$Points [] = $YPos1 + $this->GArea_Y1;
$this->canvas->drawFilledPolygon(
$Points,
4,
$color,
$Alpha
);
}
$LastYPos1 = $YPos1;
$LastYPos2 = $YPos2;
$LastXPos = $XPos;
$XPos = $XPos + $this->DivisionWidth;
}
}
/**
* This function write the values of the specified series
*/
function writeValues($Data, $DataDescription, $Series) {
/* Validate the Data and DataDescription array */
$this->validateDataDescription("writeValues", $DataDescription);
$this->validateData("writeValues", $Data);
if(!is_array($Series)) {
$Series = array($Series);
}
foreach($Series as $Serie) {
$ColorID = $DataDescription->getColumnIndex($Serie);
$XPos = $this->GArea_X1 + $this->GAreaXOffset;
foreach($Data as $Values) {
if(isset ($Values[$Serie]) && is_numeric($Values[$Serie])) {
$Value = $Values[$Serie];
$YPos = $this->GArea_Y2 - (($Value - $this->VMin) * $this->DivisionRatio);
$Positions = imagettfbbox($this->FontSize, 0, $this->FontName, $Value);
$Width = $Positions [2] - $Positions [6];
$XOffset = $XPos - ($Width / 2);
$YOffset = $YPos - 4;
$this->canvas->drawText(
$this->FontSize,
0,
new Point($XOffset, $YOffset),
$this->palette->getColor($ColorID),
$this->FontName,
$Value,
ShadowProperties::NoShadow()
);
}
$XPos = $XPos + $this->DivisionWidth;
}
}
}
/**
* @brief Draws a line graph where the data gives Y values for a
* series of regular positions along the X axis
*/
function drawLineGraph($Data, $DataDescription, $SerieName = "") {
/* Validate the Data and DataDescription array */
$this->validateDataDescription("drawLineGraph", $DataDescription);
$this->validateData("drawLineGraph", $Data);
$GraphID = 0;
foreach($DataDescription->values as $ColName) {
$ColorID = $DataDescription->getColumnIndex($ColName);
if($SerieName == "" || $SerieName == $ColName) {
$XPos = $this->GArea_X1 + $this->GAreaXOffset;
$XLast = -1;
$YLast = 0;
foreach($Data as $Values) {
if(isset ($Values[$ColName])) {
$Value = $Values[$ColName];
$YPos = $this->GArea_Y2 - (($Value - $this->VMin) * $this->DivisionRatio);
/* Save point into the image map if option activated */
if($this->BuildMap)
$this->addToImageMap($XPos - 3, $YPos - 3, $XPos + 3, $YPos + 3, $DataDescription->description[$ColName], $Values[$ColName].$DataDescription->getYUnit(), "Line");
if(!is_numeric($Value)) {
$XLast = -1;
}
if($XLast != -1)
$this->canvas->drawLine(
new Point($XLast, $YLast),
new Point($XPos, $YPos),
$this->palette->getColor($ColorID),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties,
new Point($this->GArea_X1,
$this->GArea_Y1),
new Point($this->GArea_X2,
$this->GArea_Y2)
);
$XLast = $XPos;
$YLast = $YPos;
if(!is_numeric($Value)) {
$XLast = -1;
}
}
$XPos = $XPos + $this->DivisionWidth;
}
$GraphID++;
}
}
}
/**
* @brief Draws a line graph where one series of data defines the
* X position and another the Y position
*/
function drawXYGraph($Data, $YSerieName, $XSerieName, $PaletteID = 0) {
$graphAreaMin = new Point($this->GArea_X1, $this->GArea_Y1);
$graphAreaMax = new Point($this->GArea_X2, $this->GArea_Y2);
$lastPoint = null;
foreach($Data as $Values) {
if(isset ($Values[$YSerieName]) && isset ($Values[$XSerieName])) {
$X = $Values[$XSerieName];
$Y = $Values[$YSerieName];
$Y = $this->GArea_Y2 - (($Y - $this->VMin) * $this->DivisionRatio);
$X = $this->GArea_X1 + (($X - $this->VXMin) * $this->XDivisionRatio);
$currentPoint = new Point($X, $Y);
if($lastPoint != null) {
$this->canvas->drawLine(
$lastPoint,
$currentPoint,
$this->palette->getColor($PaletteID),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties,
$graphAreaMin,
$graphAreaMax
);
}
$lastPoint = $currentPoint;
}
}
}
/**
* This function draw a cubic curve
*/
function drawCubicCurve(pData $data, $Accuracy = .1, $SerieName = "") {
/* Validate the Data and DataDescription array */
$this->validateDataDescription(
"drawCubicCurve",
$data->getDataDescription()
);
$this->validateData("drawCubicCurve", $data->getData());
$graphAreaMin = new Point($this->GArea_X1, $this->GArea_Y1);
$graphAreaMax = new Point($this->GArea_X2, $this->GArea_Y2);
$GraphID = 0;
foreach($data->getDataDescription()->values as $ColName) {
if($SerieName == "" || $SerieName == $ColName) {
/** @todo The next section of code has been duplicated by
* copy & paste */
$XIn = array();
$YIn = array();
$Yt = "";
$U = "";
$ColorID = $data->getDataDescription()->getColumnIndex($ColName);
$Index = 1;
$XLast = -1;
$YLast = 0;
$Missing = array();
$data->getXYMap($ColName, $XIn, $YIn, $Missing, $Index);
assert(count($XIn) == count($YIn));
assert($Index + 1 >= count($XIn));
$Yt [0] = 0;
$Yt [1] = 0;
$U [1] = 0;
$this->calculateCubicCurve($Yt, $XIn, $YIn, $U, $Index);
$Yt [$Index] = 0;
for($k = $Index - 1; $k >= 1; $k--)
$Yt [$k] = $Yt [$k] * $Yt [$k + 1] + $U [$k];
$XPos = $this->GArea_X1 + $this->GAreaXOffset;
for($X = 1; $X <= $Index; $X = $X + $Accuracy) {
/* I believe here we're searching for the integral
* value k such that $X lies between $XIn[k] and
* $XIn[k-1] */
$klo = 1;
$khi = $Index;
$k = $khi - $klo;
while($k > 1) {
$k = $khi - $klo;
If($XIn [$k] >= $X)
$khi = $k;
else
$klo = $k;
}
$klo = $khi - 1;
/* These assertions are to check my understanding
* of the code. If they fail, it is my fault and
* not a bug */
assert($khi = $klo + 1);
assert($XIn[$klo] < $X);
assert($X <= $XIn[$khi]);
$h = $XIn [$khi] - $XIn [$klo];
$a = ($XIn [$khi] - $X) / $h;
$b = ($X - $XIn [$klo]) / $h;
/**
* I believe this is the actual cubic Bezier
* calculation. In parametric form:
*
* B(t) = (1-t)^3 * B0
* + 3 (1-t)^2 * t * B1
* + 3 (1-t) * t^2 * B2
* + t^3 B3
*/
$Value = $a * $YIn [$klo] + $b * $YIn [$khi] + (($a * $a * $a - $a) * $Yt [$klo] + ($b * $b * $b - $b) * $Yt [$khi]) * ($h * $h) / 6;
$YPos = $this->GArea_Y2 - (($Value - $this->VMin) * $this->DivisionRatio);
if($XLast != -1 && !isset ($Missing [floor($X)]) && !isset ($Missing [floor($X + 1)]))
$this->canvas->drawLine(
new Point($XLast,
$YLast),
new Point($XPos,
$YPos),
$this->palette->getColor($ColorID),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties,
$graphAreaMin,
$graphAreaMax
);
$XLast = $XPos;
$YLast = $YPos;
$XPos = $XPos + $this->DivisionWidth * $Accuracy;
}
// Add potentialy missing values
$XPos = $XPos - $this->DivisionWidth * $Accuracy;
if($XPos < ($this->GArea_X2 - $this->GAreaXOffset)) {
$YPos = $this->GArea_Y2 - (($YIn [$Index] - $this->VMin) * $this->DivisionRatio);
$this->canvas->drawLine(
new Point($XLast,
$YLast),
new Point($this->GArea_X2 - $this->GAreaXOffset,
$YPos),
$this->palette->getColor($ColorID),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties,
$graphAreaMin,
$graphAreaMax
);
}
$GraphID++;
}
}
}
/**
* @todo I haven't figured out exactly what this bit of code does,
* it's just an attempt to reduce code duplication
*/
private function calculateCubicCurve(array & $Yt, array $XIn, array $YIn, array & $U, $Index) {
for($i = 2; $i <= $Index - 1; $i++) {
/* Typically $Sig will be 0.5, since each X value will be
* one unit past the last. If there is missing data then
* this ratio will change */
$Sig = ($XIn [$i] - $XIn [$i - 1]) / ($XIn [$i + 1] - $XIn [$i - 1]);
$p = $Sig * $Yt [$i - 1] + 2;
/* This Y value will nearly always be negative, thanks to
* $Sig being 0.5 */
$Yt [$i] = ($Sig - 1) / $p;
/** @todo No idea what the following code is doing */
$U [$i] = ($YIn [$i + 1] - $YIn [$i]) / ($XIn [$i + 1] - $XIn [$i])
- ($YIn [$i] - $YIn [$i - 1]) / ($XIn [$i] - $XIn [$i - 1]);
$U [$i] = (6 * $U [$i] / ($XIn [$i + 1] - $XIn [$i - 1]) - $Sig * $U [$i - 1]) / $p;
}
}
/**
* This function draw a filled cubic curve
*/
function drawFilledCubicCurve(pData $data, $Accuracy = .1, $Alpha = 100, $AroundZero = FALSE) {
/* Validate the Data and DataDescription array */
$this->validateDataDescription(
"drawFilledCubicCurve",
$data->getDataDescription()
);
$this->validateData("drawFilledCubicCurve", $data->getData());
$LayerWidth = $this->GArea_X2 - $this->GArea_X1;
$LayerHeight = $this->GArea_Y2 - $this->GArea_Y1;
$YZero = $LayerHeight - ((0 - $this->VMin) * $this->DivisionRatio);
if($YZero > $LayerHeight) {
$YZero = $LayerHeight;
}
$GraphID = 0;
foreach($data->getDataDescription()->values as $ColName) {
$XIn = array();
$YIn = array();
$Yt = array();
$U = array();
$ColorID = $data->getDataDescription()->getColumnIndex($ColName);
$numElements = 1;
$XLast = -1;
$Missing = array();
$data->getXYMap($ColName, $XIn, $YIn, $Missing, $numElements);
$Yt [0] = 0;
$Yt [1] = 0;
$U [1] = 0;
$this->calculateCubicCurve($Yt, $XIn, $YIn, $U, $numElements);
$Yt [$numElements] = 0;
for($k = $numElements - 1; $k >= 1; $k--)
$Yt [$k] = $Yt [$k] * $Yt [$k + 1] + $U [$k];
$Points = "";
$Points [] = $this->GAreaXOffset + $this->GArea_X1;
$Points [] = $LayerHeight + $this->GArea_Y1;
$YLast = NULL;
$XPos = $this->GAreaXOffset;
$PointsCount = 2;
for($X = 1; $X <= $numElements; $X = $X + $Accuracy) {
$klo = 1;
$khi = $numElements;
$k = $khi - $klo;
while($k > 1) {
$k = $khi - $klo;
If($XIn [$k] >= $X)
$khi = $k;
else
$klo = $k;
}
$klo = $khi - 1;
$h = $XIn [$khi] - $XIn [$klo];
$a = ($XIn [$khi] - $X) / $h;
$b = ($X - $XIn [$klo]) / $h;
$Value = $a * $YIn [$klo] + $b * $YIn [$khi] + (($a * $a * $a - $a) * $Yt [$klo] + ($b * $b * $b - $b) * $Yt [$khi]) * ($h * $h) / 6;
$YPos = $LayerHeight - (($Value - $this->VMin) * $this->DivisionRatio);
if($YLast != NULL && $AroundZero && !isset ($Missing [floor($X)]) && !isset ($Missing [floor($X + 1)])) {
$aPoints = "";
$aPoints [] = $XLast + $this->GArea_X1;
$aPoints [] = min($YLast + $this->GArea_Y1, $this->GArea_Y2);
$aPoints [] = $XPos + $this->GArea_X1;
$aPoints [] = min($YPos + $this->GArea_Y1, $this->GArea_Y2);
$aPoints [] = $XPos + $this->GArea_X1;
$aPoints [] = $YZero + $this->GArea_Y1;
$aPoints [] = $XLast + $this->GArea_X1;
$aPoints [] = $YZero + $this->GArea_Y1;
$this->canvas->drawFilledPolygon(
$aPoints,
4,
$this->palette->getColor($ColorID),
$alpha
);
}
if(!isset ($Missing [floor($X)]) || $YLast == NULL) {
$PointsCount++;
$Points [] = $XPos + $this->GArea_X1;
$Points [] = min($YPos + $this->GArea_Y1, $this->GArea_Y2);
} else {
$PointsCount++;
$Points [] = $XLast + $this->GArea_X1;
$Points [] = min(
$LayerHeight + $this->GArea_Y1,
$this->GArea_Y2
);
;
}
$YLast = $YPos;
$XLast = $XPos;
$XPos = $XPos + $this->DivisionWidth * $Accuracy;
}
// Add potentialy missing values
$XPos = $XPos - $this->DivisionWidth * $Accuracy;
if($XPos < ($LayerWidth - $this->GAreaXOffset)) {
$YPos = $LayerHeight - (($YIn [$numElements] - $this->VMin) * $this->DivisionRatio);
if($YLast != NULL && $AroundZero) {
$aPoints = "";
$aPoints [] = $XLast + $this->GArea_X1;
$aPoints [] = max($YLast + $this->GArea_Y1, $this->GArea_Y1);
$aPoints [] = $LayerWidth - $this->GAreaXOffset + $this->GArea_X1;
$aPoints [] = max($YPos + $this->GArea_Y1, $this->GArea_Y1);
$aPoints [] = $LayerWidth - $this->GAreaXOffset + $this->GArea_X1;
$aPoints [] = max($YZero + $this->GArea_Y1, $this->GArea_Y1);
$aPoints [] = $XLast + $this->GArea_X1;
$aPoints [] = max($YZero + $this->GArea_Y1, $this->GArea_Y1);
$this->canvas->drawFilledPolygon(
$aPoints,
4,
$this->palette->getColor($ColorID),
$alpha
);
}
if($YIn [$klo] != "" && $YIn [$khi] != "" || $YLast == NULL) {
$PointsCount++;
$Points [] = $LayerWidth
- $this->GAreaXOffset
+ $this->GArea_X1;
$Points [] = $YPos + $this->GArea_Y1;
}
}
$Points [] = $LayerWidth - $this->GAreaXOffset + $this->GArea_X1;
$Points [] = $LayerHeight + $this->GArea_Y1;
if(!$AroundZero) {
$this->canvas->drawFilledPolygon(
$Points,
$PointsCount,
$this->palette->getColor($ColorID),
$Alpha
);
}
$this->drawCubicCurve($data, $Accuracy, $ColName);
$GraphID++;
}
}
/**
* This function draw a filled line graph
*/
function drawFilledLineGraph($Data, $DataDescription, $Alpha = 100, $AroundZero = FALSE) {
$Empty = -2147483647;
/* Validate the Data and DataDescription array */
$this->validateDataDescription("drawFilledLineGraph", $DataDescription);
$this->validateData("drawFilledLineGraph", $Data);
$LayerWidth = $this->GArea_X2 - $this->GArea_X1;
$LayerHeight = $this->GArea_Y2 - $this->GArea_Y1;
$GraphID = 0;
foreach($DataDescription->values as $ColName) {
$ColorID = $DataDescription->getColumnIndex($ColName);
$aPoints = array();
$aPoints [] = $this->GAreaXOffset + $this->GArea_X1;
$aPoints [] = $LayerHeight + $this->GArea_Y1;
$XPos = $this->GAreaXOffset;
$XLast = -1;
$PointsCount = 2;
$YZero = $LayerHeight - ((0 - $this->VMin) * $this->DivisionRatio);
if($YZero > $LayerHeight) {
$YZero = $LayerHeight;
}
$YLast = $Empty;
foreach(array_keys($Data) as $Key) {
$Value = $Data [$Key] [$ColName];
$YPos = $LayerHeight - (($Value - $this->VMin) * $this->DivisionRatio);
/* Save point into the image map if option activated */
if($this->BuildMap)
$this->addToImageMap($XPos - 3, $YPos - 3, $XPos + 3, $YPos + 3, $DataDescription->description[$ColName], $Data [$Key] [$ColName].$DataDescription->getYUnit(), "FLine");
if(!is_numeric($Value)) {
$PointsCount++;
$aPoints [] = $XLast + $this->GArea_X1;
$aPoints [] = $LayerHeight + $this->GArea_Y1;
$YLast = $Empty;
} else {
$PointsCount++;
if($YLast != $Empty) {
$aPoints [] = $XPos + $this->GArea_X1;
$aPoints [] = $YPos + $this->GArea_Y1;
} else {
$PointsCount++;
$aPoints [] = $XPos + $this->GArea_X1;
$aPoints [] = $LayerHeight + $this->GArea_Y1;
$aPoints [] = $XPos + $this->GArea_X1;
$aPoints [] = $YPos + $this->GArea_Y1;
}
if($YLast != $Empty && $AroundZero) {
$Points = "";
$Points [] = $XLast + $this->GArea_X1;
$Points [] = $YLast + $this->GArea_Y1;
$Points [] = $XPos + $this->GArea_X1;
$Points [] = $YPos + $this->GArea_Y1;
$Points [] = $XPos + $this->GArea_X1;
$Points [] = $YZero + $this->GArea_Y1;
$Points [] = $XLast + $this->GArea_X1;
$Points [] = $YZero + $this->GArea_Y1;
$this->canvas->drawFilledPolygon(
$Points,
4,
$this->palette->getColor($ColorID),
$Alpha
);
}
$YLast = $YPos;
}
$XLast = $XPos;
$XPos = $XPos + $this->DivisionWidth;
}
$aPoints [] = $LayerWidth - $this->GAreaXOffset + $this->GArea_X1;
$aPoints [] = $LayerHeight + $this->GArea_Y1;
if($AroundZero == FALSE) {
$this->canvas->drawFilledPolygon(
$aPoints,
$PointsCount,
$this->palette->getColor($ColorID),
$Alpha
);
}
$GraphID++;
$this->drawLineGraph($Data, $DataDescription, $ColName);
}
}
/**
* This function draws a bar graph
*/
function drawOverlayBarGraph($Data, $DataDescription, $Alpha = 50) {
/* Validate the Data and DataDescription array */
$this->validateDataDescription("drawOverlayBarGraph", $DataDescription);
$this->validateData("drawOverlayBarGraph", $Data);
$LayerHeight = $this->GArea_Y2 - $this->GArea_Y1;
$GraphID = 0;
foreach($DataDescription->values as $ColName) {
$ColorID = $DataDescription->getColumnIndex($ColName);
$XWidth = $this->DivisionWidth / 4;
$XPos = $this->GAreaXOffset;
$YZero = $LayerHeight - ((0 - $this->VMin) * $this->DivisionRatio);
foreach(array_keys($Data) as $Key) {
if(isset ($Data [$Key] [$ColName])) {
$Value = $Data [$Key] [$ColName];
if(is_numeric($Value)) {
$YPos = $LayerHeight - (($Value - $this->VMin) * $this->DivisionRatio);
$this->canvas->drawFilledRectangle(
new Point(floor($XPos - $XWidth + $this->GArea_X1),
floor($YPos + $this->GArea_Y1)),
new Point(floor($XPos + $XWidth + $this->GArea_X1),
floor($YZero + $this->GArea_Y1)),
$this->palette->getColor($GraphID),
ShadowProperties::NoShadow(),
false,
$Alpha
);
$X1 = floor($XPos - $XWidth + $this->GArea_X1);
$Y1 = floor($YPos + $this->GArea_Y1) + .2;
$X2 = floor($XPos + $XWidth + $this->GArea_X1);
$Y2 = $this->GArea_Y2 - ((0 - $this->VMin) * $this->DivisionRatio);
if($X1 <= $this->GArea_X1) {
$X1 = $this->GArea_X1 + 1;
}
if($X2 >= $this->GArea_X2) {
$X2 = $this->GArea_X2 - 1;
}
/* Save point into the image map if option activated */
if($this->BuildMap)
$this->addToImageMap($X1, min($Y1, $Y2), $X2, max($Y1, $Y2), $DataDescription->description[$ColName], $Data [$Key] [$ColName].$DataDescription->getYUnit(), "oBar");
$this->canvas->drawLine(
new Point($X1,
$Y1),
new Point($X2,
$Y1),
$this->palette->getColor($ColorID),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties,
new Point($this->GArea_X1,
$this->GArea_Y1),
new Point($this->GArea_X2,
$this->GArea_Y2)
);
}
}
$XPos = $XPos + $this->DivisionWidth;
}
$GraphID++;
}
}
/**
* This function draw a bar graph
*/
function drawBarGraph($Data, $DataDescription, $Alpha = 100) {
/* Validate the Data and DataDescription array */
$this->validateDataDescription("drawBarGraph", $DataDescription);
$this->validateData("drawBarGraph", $Data);
$Series = count($DataDescription->values);
$SeriesWidth = $this->DivisionWidth / ($Series + 1);
$SerieXOffset = $this->DivisionWidth / 2 - $SeriesWidth / 2;
$YZero = $this->GArea_Y2 - ((0 - $this->VMin) * $this->DivisionRatio);
if($YZero > $this->GArea_Y2) {
$YZero = $this->GArea_Y2;
}
$SerieID = 0;
foreach($DataDescription->values as $ColName) {
$ColorID = $DataDescription->getColumnIndex($ColName);
$XPos = $this->GArea_X1 + $this->GAreaXOffset - $SerieXOffset + $SeriesWidth * $SerieID;
foreach(array_keys($Data) as $Key) {
if(isset ($Data [$Key] [$ColName])) {
if(is_numeric($Data [$Key] [$ColName])) {
$Value = $Data [$Key] [$ColName];
$YPos = $this->GArea_Y2 - (($Value - $this->VMin) * $this->DivisionRatio);
/* Save point into the image map if option activated */
if($this->BuildMap) {
$this->addToImageMap($XPos + 1, min($YZero, $YPos), $XPos + $SeriesWidth - 1, max($YZero, $YPos), $DataDescription->description[$ColName], $Data [$Key] [$ColName].$DataDescription->getYUnit(), "Bar");
}
if($Alpha == 100) {
$this->canvas->drawRectangle(
new Point($XPos + 1, $YZero),
new Point($XPos + $SeriesWidth - 1,
$YPos),
new Color(25, 25, 25),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
}
$this->canvas->drawFilledRectangle(
new Point($XPos + 1,
$YZero),
new Point($XPos + $SeriesWidth - 1,
$YPos),
$this->palette->getColor($ColorID),
$this->shadowProperties,
TRUE, $Alpha
);
}
}
$XPos = $XPos + $this->DivisionWidth;
}
$SerieID++;
}
}
/**
* This function draw a stacked bar graph
*/
function drawStackedBarGraph($Data, $DataDescription, $Alpha = 50, $Contiguous = FALSE) {
/* Validate the Data and DataDescription array */
$this->validateDataDescription("drawBarGraph", $DataDescription);
$this->validateData("drawBarGraph", $Data);
if($Contiguous)
$SeriesWidth = $this->DivisionWidth;
else
$SeriesWidth = $this->DivisionWidth * .8;
$YZero = $this->GArea_Y2 - ((0 - $this->VMin) * $this->DivisionRatio);
if($YZero > $this->GArea_Y2) {
$YZero = $this->GArea_Y2;
}
$SerieID = 0;
$LastValue = "";
foreach($DataDescription->values as $ColName) {
$ColorID = $DataDescription->getColumnIndex($ColName);
$XPos = $this->GArea_X1 + $this->GAreaXOffset - $SeriesWidth / 2;
foreach(array_keys($Data) as $Key) {
if(isset ($Data [$Key] [$ColName])) {
if(is_numeric($Data [$Key] [$ColName])) {
$Value = $Data [$Key] [$ColName];
if(isset ($LastValue [$Key])) {
$YPos = $this->GArea_Y2 - ((($Value + $LastValue [$Key]) - $this->VMin) * $this->DivisionRatio);
$YBottom = $this->GArea_Y2 - (($LastValue [$Key] - $this->VMin) * $this->DivisionRatio);
$LastValue [$Key] += $Value;
} else {
$YPos = $this->GArea_Y2 - (($Value - $this->VMin) * $this->DivisionRatio);
$YBottom = $YZero;
$LastValue [$Key] = $Value;
}
/* Save point into the image map if option activated */
if($this->BuildMap)
$this->addToImageMap($XPos + 1, min($YBottom, $YPos), $XPos + $SeriesWidth - 1, max($YBottom, $YPos), $DataDescription->description[$ColName], $Data [$Key] [$ColName].$DataDescription->getYUnit(), "sBar");
$this->canvas->drawFilledRectangle(
new Point($XPos + 1,
$YBottom),
new Point($XPos + $SeriesWidth - 1,
$YPos),
$this->palette->getColor($ColorID),
$this->shadowProperties,
TRUE,
$Alpha
);
}
}
$XPos = $XPos + $this->DivisionWidth;
}
$SerieID++;
}
}
/**
* This function draw a limits bar graphs
*/
function drawLimitsGraph($Data, $DataDescription, Color $color = null) {
if($color == null) {
$color = new Color(0, 0, 0);
}
/* Validate the Data and DataDescription array */
$this->validateDataDescription("drawLimitsGraph", $DataDescription);
$this->validateData("drawLimitsGraph", $Data);
$XWidth = $this->DivisionWidth / 4;
$XPos = $this->GArea_X1 + $this->GAreaXOffset;
$graphAreaMin = new Point($this->GArea_X1, $this->GArea_Y1);
$graphAreaMax = new Point($this->GArea_X2, $this->GArea_Y2);
foreach(array_keys($Data) as $Key) {
$Min = $Data [$Key] [$DataDescription->values[0]];
$Max = $Data [$Key] [$DataDescription->values[0]];
$GraphID = 0;
$MaxID = 0;
$MinID = 0;
foreach($DataDescription->values as $ColName) {
if(isset ($Data [$Key] [$ColName])) {
if($Data [$Key] [$ColName] > $Max && is_numeric($Data [$Key] [$ColName])) {
$Max = $Data [$Key] [$ColName];
$MaxID = $GraphID;
}
}
if(isset ($Data [$Key] [$ColName]) && is_numeric($Data [$Key] [$ColName])) {
if($Data [$Key] [$ColName] < $Min) {
$Min = $Data [$Key] [$ColName];
$MinID = $GraphID;
}
$GraphID++;
}
}
$YPos = $this->GArea_Y2 - (($Max - $this->VMin) * $this->DivisionRatio);
$X1 = floor($XPos - $XWidth);
$Y1 = floor($YPos) - .2;
$X2 = floor($XPos + $XWidth);
if($X1 <= $this->GArea_X1) {
$X1 = $this->GArea_X1 + 1;
}
if($X2 >= $this->GArea_X2) {
$X2 = $this->GArea_X2 - 1;
}
$YPos = $this->GArea_Y2 - (($Min - $this->VMin) * $this->DivisionRatio);
$Y2 = floor($YPos) + .2;
$this->canvas->drawLine(
new Point(floor($XPos) - .2, $Y1 + 1),
new Point(floor($XPos) - .2, $Y2 - 1),
$color,
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties,
$graphAreaMin,
$graphAreaMax
);
$this->canvas->drawLine(
new Point(floor($XPos) + .2, $Y1 + 1),
new Point(floor($XPos) + .2, $Y2 - 1),
$color,
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties,
$graphAreaMin,
$graphAreaMax
);
$this->canvas->drawLine(
new Point($X1,
$Y1),
new Point($X2,
$Y1),
$this->palette->getColor($MaxID),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
$this->canvas->drawLine(
new Point($X1,
$Y2),
new Point($X2,
$Y2),
$this->palette->getColor($MinID),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
$XPos = $XPos + $this->DivisionWidth;
}
}
/**
* This function draw radar axis centered on the graph area
*/
function drawRadarAxis($Data, $DataDescription, $Mosaic = TRUE, $BorderOffset = 10, Color $colorA = null, Color $colorS = null, $MaxValue = -1) {
if($colorA == null) {
$colorA = new Color(60, 60, 60);
}
if($colorS == null) {
$colorS = new Color(200, 200, 200);
}
/* Validate the Data and DataDescription array */
$this->validateDataDescription("drawRadarAxis", $DataDescription);
$this->validateData("drawRadarAxis", $Data);
/* Draw radar axis */
$Points = count($Data);
$Radius = ($this->GArea_Y2 - $this->GArea_Y1) / 2 - $BorderOffset;
$XCenter = ($this->GArea_X2 - $this->GArea_X1) / 2 + $this->GArea_X1;
$YCenter = ($this->GArea_Y2 - $this->GArea_Y1) / 2 + $this->GArea_Y1;
/* Search for the max value */
if($MaxValue == -1) {
foreach($DataDescription->values as $ColName) {
foreach(array_keys($Data) as $Key) {
if(isset ($Data [$Key] [$ColName]))
if($Data [$Key] [$ColName] > $MaxValue) {
$MaxValue = $Data [$Key] [$ColName];
}
}
}
}
$LastX2 = 0;
$LastY1 = 0;
$LastY2 = 0;
/* Draw the mosaic */
if($Mosaic) {
$RadiusScale = $Radius / $MaxValue;
for($t = 1; $t <= $MaxValue - 1; $t++) {
$TRadius = $RadiusScale * $t;
$LastX1 = -1;
for($i = 0; $i <= $Points; $i++) {
$Angle = -90 + $i * 360 / $Points;
$X1 = cos($Angle * M_PI / 180) * $TRadius + $XCenter;
$Y1 = sin($Angle * M_PI / 180) * $TRadius + $YCenter;
$X2 = cos($Angle * M_PI / 180) * ($TRadius + $RadiusScale) + $XCenter;
$Y2 = sin($Angle * M_PI / 180) * ($TRadius + $RadiusScale) + $YCenter;
if($t % 2 == 1 && $LastX1 != -1) {
$Plots = "";
$Plots [] = $X1;
$Plots [] = $Y1;
$Plots [] = $X2;
$Plots [] = $Y2;
$Plots [] = $LastX2;
$Plots [] = $LastY2;
$Plots [] = $LastX1;
$Plots [] = $LastY1;
$this->canvas->drawFilledPolygon(
$Plots,
(count($Plots) + 1) / 2,
new Color(250, 250, 250)
);
}
$LastX1 = $X1;
$LastY1 = $Y1;
$LastX2 = $X2;
$LastY2 = $Y2;
}
}
}
/* Draw the spider web */
$LastY = 0;
for($t = 1; $t <= $MaxValue; $t++) {
$TRadius = ($Radius / $MaxValue) * $t;
$LastX = -1;
for($i = 0; $i <= $Points; $i++) {
$Angle = -90 + $i * 360 / $Points;
$X = cos($Angle * M_PI / 180) * $TRadius + $XCenter;
$Y = sin($Angle * M_PI / 180) * $TRadius + $YCenter;
if($LastX != -1)
$this->canvas->drawDottedLine(
new Point($LastX, $LastY),
new Point($X, $Y),
4, 1, $colorS,
$this->shadowProperties
);
$LastX = $X;
$LastY = $Y;
}
}
/* Draw the axis */
for($i = 0; $i <= $Points; $i++) {
$Angle = -90 + $i * 360 / $Points;
$X = cos($Angle * M_PI / 180) * $Radius + $XCenter;
$Y = sin($Angle * M_PI / 180) * $Radius + $YCenter;
$this->canvas->drawLine(
new Point($XCenter, $YCenter),
new Point($X, $Y),
$colorA,
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
$XOffset = 0;
$YOffset = 0;
if(isset ($Data [$i] [$DataDescription->getPosition()])) {
$Label = $Data [$i] [$DataDescription->getPosition()];
$Positions = imagettfbbox($this->FontSize, 0, $this->FontName, $Label);
$Width = $Positions [2] - $Positions [6];
$Height = $Positions [3] - $Positions [7];
if($Angle >= 0 && $Angle <= 90)
$YOffset = $Height;
if($Angle > 90 && $Angle <= 180) {
$YOffset = $Height;
$XOffset = -$Width;
}
if($Angle > 180 && $Angle <= 270) {
$XOffset = -$Width;
}
$this->canvas->drawText(
$this->FontSize,
0,
new Point($X + $XOffset, $Y + $YOffset),
$colorA,
$this->FontName,
$Label,
ShadowProperties::NoShadow()
);
}
}
/* Write the values */
for($t = 1; $t <= $MaxValue; $t++) {
$TRadius = ($Radius / $MaxValue) * $t;
$Angle = -90 + 360 / $Points;
$X1 = $XCenter;
$Y1 = $YCenter - $TRadius;
$X2 = cos($Angle * M_PI / 180) * $TRadius + $XCenter;
$Y2 = sin($Angle * M_PI / 180) * $TRadius + $YCenter;
$XPos = floor(($X2 - $X1) / 2) + $X1;
$YPos = floor(($Y2 - $Y1) / 2) + $Y1;
$Positions = imagettfbbox($this->FontSize, 0, $this->FontName, $t);
$X = $XPos - ($X + $Positions [2] - $X + $Positions [6]) / 2;
$Y = $YPos + $this->FontSize;
$this->canvas->drawFilledRoundedRectangle(
new Point($X + $Positions [6] - 2,
$Y + $Positions [7] - 1),
new Point($X + $Positions [2] + 4,
$Y + $Positions [3] + 1),
2,
new Color(240, 240, 240),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
$this->canvas->drawRoundedRectangle(
new Point($X + $Positions [6] - 2,
$Y + $Positions [7] - 1),
new Point($X + $Positions [2] + 4,
$Y + $Positions [3] + 1),
2,
new Color(220, 220, 220),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
$this->canvas->drawText(
$this->FontSize,
0,
new Point($X, $Y),
$colorA,
$this->FontName,
$t,
ShadowProperties::NoShadow()
);
}
}
private function calculateMaxValue($Data, $DataDescription) {
$MaxValue = -1;
foreach($DataDescription->values as $ColName) {
foreach(array_keys($Data) as $Key) {
if(isset ($Data [$Key] [$ColName]))
if($Data [$Key] [$ColName] > $MaxValue && is_numeric($Data[$Key][$ColName])) {
$MaxValue = $Data [$Key] [$ColName];
}
}
}
return $MaxValue;
}
/**
* This function draw a radar graph centered on the graph area
*/
function drawRadar($Data, $DataDescription, $BorderOffset = 10, $MaxValue = -1) {
/* Validate the Data and DataDescription array */
$this->validateDataDescription("drawRadar", $DataDescription);
$this->validateData("drawRadar", $Data);
$Points = count($Data);
$Radius = ($this->GArea_Y2 - $this->GArea_Y1) / 2 - $BorderOffset;
$XCenter = ($this->GArea_X2 - $this->GArea_X1) / 2 + $this->GArea_X1;
$YCenter = ($this->GArea_Y2 - $this->GArea_Y1) / 2 + $this->GArea_Y1;
/* Search for the max value */
if($MaxValue == -1) {
$MaxValue = $this->calculateMaxValue($Data, $DataDescription);
}
$GraphID = 0;
$YLast = 0;
foreach($DataDescription->values as $ColName) {
$ColorID = $DataDescription->getColumnIndex($ColName);
$Angle = -90;
$XLast = -1;
foreach(array_keys($Data) as $Key) {
if(isset ($Data [$Key] [$ColName])) {
$Value = $Data [$Key] [$ColName];
$Strength = ($Radius / $MaxValue) * $Value;
$XPos = cos($Angle * M_PI / 180) * $Strength + $XCenter;
$YPos = sin($Angle * M_PI / 180) * $Strength + $YCenter;
if($XLast != -1)
$this->canvas->drawLine(
new Point($XLast,
$YLast),
new Point($XPos,
$YPos),
$this->palette->getColor($ColorID),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
if($XLast == -1) {
$FirstX = $XPos;
$FirstY = $YPos;
}
$Angle = $Angle + (360 / $Points);
$XLast = $XPos;
$YLast = $YPos;
}
}
$this->canvas->drawLine(
new Point($XPos,
$YPos),
new Point($FirstX,
$FirstY),
$this->palette->getColor($ColorID),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
$GraphID++;
}
}
/**
* This function draw a radar graph centered on the graph area
*/
function drawFilledRadar($Data, $DataDescription, $Alpha = 50, $BorderOffset = 10, $MaxValue = -1) {
/* Validate the Data and DataDescription array */
$this->validateDataDescription("drawFilledRadar", $DataDescription);
$this->validateData("drawFilledRadar", $Data);
$Points = count($Data);
$Radius = ($this->GArea_Y2 - $this->GArea_Y1) / 2 - $BorderOffset;
$XCenter = ($this->GArea_X2 - $this->GArea_X1) / 2;
$YCenter = ($this->GArea_Y2 - $this->GArea_Y1) / 2;
/* Search for the max value */
if($MaxValue == -1) {
$MaxValue = $this->calculateMaxValue($Data, $DataDescription);
}
$GraphID = 0;
foreach($DataDescription->values as $ColName) {
$ColorID = $DataDescription->getColumnIndex($ColName);
$Angle = -90;
$XLast = -1;
$Plots = array();
foreach(array_keys($Data) as $Key) {
if(isset ($Data [$Key] [$ColName])) {
$Value = $Data [$Key] [$ColName];
if(!is_numeric($Value)) {
$Value = 0;
}
$Strength = ($Radius / $MaxValue) * $Value;
$XPos = cos($Angle * M_PI / 180) * $Strength + $XCenter;
$YPos = sin($Angle * M_PI / 180) * $Strength + $YCenter;
$Plots [] = $XPos + $this->GArea_X1;
$Plots [] = $YPos + $this->GArea_Y1;
$Angle = $Angle + (360 / $Points);
$XLast = $XPos;
}
}
if(isset ($Plots [0])) {
$Plots [] = $Plots [0];
$Plots [] = $Plots [1];
$this->canvas->drawFilledPolygon(
$Plots,
(count($Plots) + 1) / 2,
$this->palette->getColor($ColorID),
$Alpha
);
for($i = 0; $i <= count($Plots) - 4; $i = $i + 2)
$this->canvas->drawLine(
new Point($Plots [$i],
$Plots [$i + 1]),
new Point($Plots [$i + 2],
$Plots [$i + 3]),
$this->palette->getColor($ColorID),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
}
$GraphID++;
}
}
/**
* This function can be used to set the background color
*/
function drawBackground(Color $color) {
$C_Background = $this->canvas->allocateColor($color);
imagefilledrectangle($this->canvas->getPicture(), 0, 0, $this->XSize, $this->YSize, $C_Background);
}
private function drawGradient(Point $point1, Point $point2, Color $color, $decay) {
/* Positive gradient */
if($decay > 0) {
$YStep = ($point2->getY() - $point1->getY() - 2) / $decay;
for($i = 0; $i <= $decay; $i++) {
$color = $color->addRGBIncrement(-1);
$Yi1 = $point1->getY() + ($i * $YStep);
$Yi2 = ceil($Yi1 + ($i * $YStep) + $YStep);
if($Yi2 >= $Yi2) {
$Yi2 = $point2->getY() - 1;
}
$this->canvas->drawFilledRectangle(
new Point($point1->getX(), $Yi1),
new Point($point2->getX(), $Yi2),
$color,
ShadowProperties::NoShadow()
);
}
}
/* Negative gradient */
if($decay < 0) {
$YStep = ($point2->getY() - $point1->getY() - 2) / -$decay;
$Yi1 = $point1->getY();
$Yi2 = $point1->getY() + $YStep;
for($i = -$decay; $i >= 0; $i--) {
$color = $color->addRGBIncrement(1);
$this->canvas->drawFilledRectangle(
new Point($point1->getX(), $Yi1),
new Point($point2->getX(), $Yi2),
$color,
ShadowProperties::NoShadow()
);
$Yi1 += $YStep;
$Yi2 += $YStep;
if($Yi2 >= $Yi2) {
$Yi2 = $point2->getY() - 1;
}
}
}
}
/**
* This function can be used to set the background color
*/
private function drawGraphAreaGradient(BackgroundStyle $style) {
if(!$style->useGradient()) {
return;
}
$this->drawGradient(
new Point($this->GArea_X1 + 1, $this->GArea_Y1 + 1),
new Point($this->GArea_X2 - 1, $this->GArea_Y2),
$style->getGradientStartColor(),
$style->getGradientDecay()
);
}
public function drawBackgroundGradient(Color $color, $decay) {
$this->drawGradient(
new Point(0, 0),
new Point($this->XSize, $this->YSize),
$color,
$decay
);
}
/**
* This function will draw an ellipse
*/
function drawEllipse($Xc, $Yc, $Height, $Width, Color $color) {
$this->canvas->drawCircle(new Point($Xc, $Yc), $Height, $color, $this->shadowProperties, $Width);
}
/**
* This function will draw a filled ellipse
*/
function drawFilledEllipse($Xc, $Yc, $Height, $Width, Color $color) {
$this->canvas->drawFilledCircle(new Point($Xc, $Yc), $Height, $color, $this->shadowProperties, $Width);
}
/**
* Load a PNG file and draw it over the chart
*/
function drawFromPNG($FileName, $X, $Y, $Alpha = 100) {
$this->drawFromPicture(1, $FileName, $X, $Y, $Alpha);
}
/**
* Load a GIF file and draw it over the chart
*/
function drawFromGIF($FileName, $X, $Y, $Alpha = 100) {
$this->drawFromPicture(2, $FileName, $X, $Y, $Alpha);
}
/**
* Load a JPEG file and draw it over the chart
*/
function drawFromJPG($FileName, $X, $Y, $Alpha = 100) {
$this->drawFromPicture(3, $FileName, $X, $Y, $Alpha);
}
/**
* Generic loader function for external pictures
*/
function drawFromPicture($PicType, $FileName, $X, $Y, $Alpha = 100) {
if(file_exists($FileName)) {
$Infos = getimagesize($FileName);
$Width = $Infos [0];
$Height = $Infos [1];
if($PicType == 1) {
$Raster = imagecreatefrompng($FileName);
}
if($PicType == 2) {
$Raster = imagecreatefromgif($FileName);
}
if($PicType == 3) {
$Raster = imagecreatefromjpeg($FileName);
}
imagecopymerge($this->canvas->getPicture(), $Raster, $X, $Y, 0, 0, $Width, $Height, $Alpha);
imagedestroy($Raster);
}
}
/**
* Add a border to the picture
*
* @todo This hasn't been updated to the new API yet
*/
function addBorder($Size = 3, $R = 0, $G = 0, $B = 0) {
$Width = $this->XSize + 2 * $Size;
$Height = $this->YSize + 2 * $Size;
$Resampled = imagecreatetruecolor($Width, $Height);
$C_Background = imagecolorallocate($Resampled, $R, $G, $B);
imagefilledrectangle($Resampled, 0, 0, $Width, $Height, $C_Background);
imagecopy($Resampled, $this->canvas->getPicture(), $Size, $Size, 0, 0, $this->XSize, $this->YSize);
imagedestroy($this->canvas->getPicture());
$this->XSize = $Width;
$this->YSize = $Height;
$this->canvas->setPicture(imagecreatetruecolor($this->XSize, $this->YSize));
$C_White = $this->canvas->allocate(new Color(255, 255, 255));
imagefilledrectangle($this->canvas->getPicture(), 0, 0, $this->XSize, $this->YSize, $C_White);
imagecolortransparent($this->canvas->getPicture(), $C_White);
imagecopy($this->canvas->getPicture(), $Resampled, 0, 0, 0, 0, $this->XSize, $this->YSize);
}
/**
* Render the current picture to a file
*/
function Render($FileName) {
if($this->ErrorReporting)
$this->printErrors($this->ErrorInterface);
/* Save image map if requested */
if($this->BuildMap)
$this->SaveImageMap();
if($FileName) {
imagepng($this->canvas->getPicture(), $FileName);
} else {
imagepng($this->canvas->getPicture());
}
}
/**
* Render the current picture to STDOUT
*/
function Stroke() {
if($this->ErrorReporting)
$this->printErrors("GD");
/* Save image map if requested */
if($this->BuildMap)
$this->SaveImageMap();
header('Content-type: image/png');
imagepng($this->canvas->getPicture());
}
/**
* Validate data contained in the description array
*
* @todo Should this be a method on DataDescription?
*/
protected function validateDataDescription($FunctionName, DataDescription $DataDescription, $DescriptionRequired = TRUE) {
if($DataDescription->getPosition() == '') {
$this->Errors [] = "[Warning] ".$FunctionName." - Y Labels are not set.";
$DataDescription->setPosition("Name");
}
if($DescriptionRequired) {
if(!isset ($DataDescription->description)) {
$this->Errors [] = "[Warning] ".$FunctionName." - Series descriptions are not set.";
foreach($DataDescription->values as $key => $Value) {
$DataDescription->description[$Value] = $Value;
}
}
if(count($DataDescription->description) < count($DataDescription->values)) {
$this->Errors [] = "[Warning] ".$FunctionName." - Some series descriptions are not set.";
foreach($DataDescription->values as $key => $Value) {
if(!isset ($DataDescription->description[$Value]))
$DataDescription->description[$Value] = $Value;
}
}
}
}
/**
* Validate data contained in the data array
*/
protected function validateData($FunctionName, $Data) {
$DataSummary = array();
foreach($Data as $key => $Values) {
foreach($Values as $key2 => $Value) {
if(!isset ($DataSummary [$key2]))
$DataSummary [$key2] = 1;
else
$DataSummary [$key2]++;
}
}
if(empty($DataSummary))
$this->Errors [] = "[Warning] ".$FunctionName." - No data set.";
foreach($DataSummary as $key => $Value) {
if($Value < max($DataSummary)) {
$this->Errors [] = "[Warning] ".$FunctionName." - Missing data in serie ".$key.".";
}
}
}
/**
* Print all error messages on the CLI or graphically
*/
function printErrors($Mode = "CLI") {
if(count($this->Errors) == 0)
return (0);
if($Mode == "CLI") {
foreach($this->Errors as $key => $Value)
echo $Value."\r\n";
} elseif($Mode == "GD") {
$MaxWidth = 0;
foreach($this->Errors as $key => $Value) {
$Position = imageftbbox($this->ErrorFontSize, 0, $this->ErrorFontName, $Value);
$TextWidth = $Position [2] - $Position [0];
if($TextWidth > $MaxWidth) {
$MaxWidth = $TextWidth;
}
}
$this->canvas->drawFilledRoundedRectangle(
new Point($this->XSize - ($MaxWidth + 20),
$this->YSize - (20 + (($this->ErrorFontSize + 4) * count($this->Errors)))),
new Point($this->XSize - 10,
$this->YSize - 10),
6,
new Color(233, 185, 185),
$this->lineWidth,
$this->lineDotSize,
$this->shadowProperties
);
$this->canvas->drawRoundedRectangle(
new Point($this->XSize - ($MaxWidth + 20),
$this->YSize - (20 + (($this->ErrorFontSize + 4) * count($this->Errors)))),
new Point($this->XSize - 10,
$this->YSize - 10),
6,
new Color(193, 145, 145),
$this->LineWidth,
$this->LineDotSize,
$this->shadowProperties
);
$YPos = $this->YSize - (18 + (count($this->Errors) - 1) * ($this->ErrorFontSize + 4));
foreach($this->Errors as $key => $Value) {
$this->canvas->drawText(
$this->ErrorFontSize,
0,
new Point($this->XSize - ($MaxWidth + 15),
$YPos),
new Color(133, 85, 85),
$this->ErrorFontName,
$Value,
ShadowProperties::NoShadow()
);
$YPos = $YPos + ($this->ErrorFontSize + 4);
}
}
}
/**
* Activate the image map creation process
*/
function setImageMap($Mode = TRUE, $GraphID = "MyGraph") {
$this->BuildMap = $Mode;
$this->MapID = $GraphID;
}
/**
* Add a box into the image map
*/
function addToImageMap($X1, $Y1, $X2, $Y2, $SerieName, $Value, $CallerFunction) {
if($this->MapFunction == NULL || $this->MapFunction == $CallerFunction) {
$this->ImageMap [] = round($X1).",".round($Y1).",".round($X2).",".round($Y2).",".$SerieName.",".$Value;
$this->MapFunction = $CallerFunction;
}
}
/**
* Load and cleanup the image map from disk
*/
function getImageMap($MapName, $Flush = TRUE) {
/* Strip HTML query strings */
$Values = $this->tmpFolder.$MapName;
$Value = explode("\?", $Values);
$FileName = $Value [0];
if(file_exists($FileName)) {
$Handle = fopen($FileName, "r");
$MapContent = fread($Handle, filesize($FileName));
fclose($Handle);
echo $MapContent;
if($Flush)
unlink($FileName);
exit ();
} else {
header("HTTP/1.0 404 Not Found");
exit ();
}
}
/**
* Save the image map to the disk
*/
function SaveImageMap() {
if(!$this->BuildMap) {
return (-1);
}
if($this->ImageMap == NULL) {
$this->Errors [] = "[Warning] SaveImageMap - Image map is empty.";
return (-1);
}
$Handle = fopen($this->tmpFolder.$this->MapID, 'w');
if(!$Handle) {
$this->Errors [] = "[Warning] SaveImageMap - Cannot save the image map.";
return (-1);
} else {
foreach($this->ImageMap as $Value)
fwrite($Handle, htmlentities($Value)."\r");
}
fclose($Handle);
}
/**
* Set date format for axis labels
*/
function setDateFormat($Format) {
$this->DateFormat = $Format;
}
/**
* Convert TS to a date format string
*/
function ToDate($Value) {
return (date($this->DateFormat, $Value));
}
/**
* Check if a number is a full integer (for scaling)
*/
static private function isRealInt($Value) {
if($Value == floor($Value))
return (TRUE);
return (FALSE);
}
/**
* @todo I don't know what this does yet, I'm refactoring...
*/
public function calculateScales(& $Scale, & $Divisions) {
/* Compute automatic scaling */
$ScaleOk = FALSE;
$Factor = 1;
$MinDivHeight = 25;
$MaxDivs = ($this->GArea_Y2 - $this->GArea_Y1) / $MinDivHeight;
if($this->VMax <= $this->VMin) {
throw new Exception("Impossible to calculate scales when VMax <= VMin");
}
if($this->VMin == 0 && $this->VMax == 0) {
$this->VMin = 0;
$this->VMax = 2;
$Scale = 1;
$Divisions = 2;
} elseif($MaxDivs > 1) {
while(!$ScaleOk) {
$Scale1 = ($this->VMax - $this->VMin) / $Factor;
$Scale2 = ($this->VMax - $this->VMin) / $Factor / 2;
if($Scale1 > 1 && $Scale1 <= $MaxDivs && !$ScaleOk) {
$ScaleOk = TRUE;
$Divisions = floor($Scale1);
$Scale = 1;
}
if($Scale2 > 1 && $Scale2 <= $MaxDivs && !$ScaleOk) {
$ScaleOk = TRUE;
$Divisions = floor($Scale2);
$Scale = 2;
}
if(!$ScaleOk) {
if($Scale2 > 1) {
$Factor = $Factor * 10;
}
if($Scale2 < 1) {
$Factor = $Factor / 10;
}
}
}
if(floor($this->VMax / $Scale / $Factor) != $this->VMax / $Scale / $Factor) {
$GridID = floor($this->VMax / $Scale / $Factor) + 1;
$this->VMax = $GridID * $Scale * $Factor;
$Divisions++;
}
if(floor($this->VMin / $Scale / $Factor) != $this->VMin / $Scale / $Factor) {
$GridID = floor($this->VMin / $Scale / $Factor);
$this->VMin = $GridID * $Scale * $Factor;
$Divisions++;
}
} else /* Can occur for small graphs */
$Scale = 1;
}
/*
* Returns the resource
*/
public function getPicture() {
return $this->canvas->getPicture();
}
static private function computeAutomaticScaling($minCoord, $maxCoord, &$minVal, &$maxVal, &$Divisions) {
$ScaleOk = FALSE;
$Factor = 1;
$Scale = 1;
$MinDivHeight = 25;
$MaxDivs = ($maxCoord - $minCoord) / $MinDivHeight;
$minVal = (float) $minVal;
$maxVal = (float) $maxVal;
// when min and max are the them spread out the value
if($minVal == $maxVal) {
$ispos = $minVal > 0;
$maxVal += $maxVal/2;
$minVal -= $minVal/2;
if($minVal < 0 && $ispos) $minVal = 0;
}
if($minVal == 0 && $maxVal == 0) {
$minVal = 0;
$maxVal = 2;
$Divisions = 2;
} elseif($MaxDivs > 1) {
while(!$ScaleOk) {
if($Factor == 0) throw new Exception('Division by zero whne calculating scales (should not happen)');
$Scale1 = ($maxVal - $minVal) / $Factor;
$Scale2 = ($maxVal - $minVal) / $Factor / 2;
if($Scale1 > 1 && $Scale1 <= $MaxDivs && !$ScaleOk) {
$ScaleOk = TRUE;
$Divisions = floor($Scale1);
$Scale = 1;
}
if($Scale2 > 1 && $Scale2 <= $MaxDivs && !$ScaleOk) {
$ScaleOk = TRUE;
$Divisions = floor($Scale2);
$Scale = 2;
}
if(!$ScaleOk) {
if($Scale2 >= 1) {
$Factor = $Factor * 10.0;
}
if($Scale2 < 1) {
$Factor = $Factor / 10.0;
}
}
}
if(floor($maxVal / $Scale / $Factor) != $maxVal / $Scale / $Factor) {
$GridID = floor($maxVal / $Scale / $Factor) + 1;
$maxVal = $GridID * $Scale * $Factor;
$Divisions++;
}
if(floor($minVal / $Scale / $Factor) != $minVal / $Scale / $Factor) {
$GridID = floor($minVal / $Scale / $Factor);
$minVal = $GridID * $Scale * $Factor;
$Divisions++;
}
}
if(!isset ($Divisions)) {
$Divisions = 2;
}
if(self::isRealInt(($maxVal - $minVal) / ($Divisions - 1))) {
$Divisions--;
}
elseif(self::isRealInt(($maxVal - $minVal) / ($Divisions + 1))) {
$Divisions++;
}
}
static private function convertValueForDisplay($value, $format, $unit) {
if($format == "number")
return $value.$unit;
if($format == "time")
return ConversionHelpers::ToTime($value);
if($format == "date")
return date('Y-m-d', $value); //todo: might be wrong, needs to go into converseion helper and needs a test
if($format == "metric")
return ConversionHelpers::ToMetric($value);
if($format == "currency")
return ConversionHelpers::ToCurrency($value);
}
}
/**
*
* @param $Message
*/
function RaiseFatal($Message) {
echo "[FATAL] ".$Message."\r\n";
exit ();
}
| Lorpotin/Dokuwiki-Gamification | lib/plugins/statistics/inc/pchart/pChart.php | PHP | gpl-2.0 | 122,890 |
<?php
$french = array(
'gccollab_stats:title' => "Statistiques de GCconnex",
'gccollab_stats:unknown' => "Inconnu",
'gccollab_stats:membercount' => "Membres inscrits",
'gccollab_stats:loading' => "Chargement des données...",
'gccollab_stats:registration:title' => "Inscription des membres",
'gccollab_stats:types:title' => "Types de membres",
'gccollab_stats:federal:title' => "Gouvernement fédéral",
'gccollab_stats:provincial:title' => "Provinciaux/territoriaux",
'gccollab_stats:student:title' => "Étudiants",
'gccollab_stats:academic:title' => "Universitaires",
'gccollab_stats:other:title' => "Autres",
'gccollab_stats:membertype' => "Type de membre",
'gccollab_stats:other' => "Autre membre",
'gccollab_stats:date' => "Date :",
'gccollab_stats:signups' => "Inscriptions :",
'gccollab_stats:total' => "Total :",
'gccollab_stats:users' => "utilisateurs",
'gccollab_stats:department' => "Département",
'gccollab_stats:province' => "Province / Territoire",
'gccollab_stats:wireposts:title' => "Messages sur le fil",
'gccollab_stats:wireposts:amount' => "Nombre de messages sur le fil",
'gccollab_stats:blogposts:title' => "Billets de blogue",
'gccollab_stats:blogposts:amount' => "Nombre de billets de blogue",
'gccollab_stats:comments:title' => "Commentaires",
'gccollab_stats:comments:amount' => "Nombre de commentaires",
'gccollab_stats:groups:label' => "Groupes :",
'gccollab_stats:groups:amount' => "Nombre de groupes",
'gccollab_stats:groupscreated:title' => "Groupes créés",
'gccollab_stats:groupscreated:amount' => "Nombre de groupes créés",
'gccollab_stats:groupsjoined:title' => "Groupes rejoints",
'gccollab_stats:groupsjoined:amount' => "Nombre de groupes rejoints",
'gccollab_stats:likes:title' => "Mentions « j\'aime »",
'gccollab_stats:likes:amount' => "Nombre de mentions « j\'aime »",
'gccollab_stats:messages:title' => "Messages",
'gccollab_stats:messages:amount' => "Nombre de messages",
'gccollab_stats:ministrymessage' => "Cliquez sur les colonnes pour afficher les ministères de la province ou du territoire",
'gccollab_stats:schoolmessage' => "Cliquez sur les colonnes pour afficher les différentes écoles",
'gccollab_stats:zoommessage' => "- Cliquez et glissez pour faire un zoom avant",
'gccollab_stats:pinchmessage' => "Pincer le graphique pour le zoomer",
);
add_translation("fr", $french);
| pscrevs/gcconnex | mod/gccollab_stats/languages/fr.php | PHP | gpl-2.0 | 2,506 |
<?php
/**
* The Footer widget areas.
*
* @package ECVET STEP Themes
* @subpackage ECVET STEP One
* @since ECVET STEP One 1.0
*/
?>
<?php
/* The footer widget area is triggered if any of the areas
* have widgets. So let's check that first.
*
* If none of the sidebars have widgets, then let's bail early.
*/
if ( ! is_active_sidebar( 'sidebar-2' )
&& ! is_active_sidebar( 'sidebar-3' )
&& ! is_active_sidebar( 'sidebar-4' )
&& ! is_active_sidebar( 'sidebar-5' )
)
return;
// If we get this far, we have widgets. Let do this.
?>
<div id="footer-sidebar" class="container">
<div id="supplementary" <?php ecvetstep_footer_sidebar_class(); ?>>
<?php if ( is_active_sidebar( 'sidebar-2' ) ) : ?>
<div id="first" class="widget-area" role="complementary">
<?php dynamic_sidebar( 'sidebar-2' ); ?>
</div><!-- #first .widget-area -->
<?php endif; ?>
<?php if ( is_active_sidebar( 'sidebar-3' ) ) : ?>
<div id="second" class="widget-area" role="complementary">
<?php dynamic_sidebar( 'sidebar-3' ); ?>
</div><!-- #second .widget-area -->
<?php endif; ?>
<?php if ( is_active_sidebar( 'sidebar-4' ) ) : ?>
<div id="third" class="widget-area" role="complementary">
<?php dynamic_sidebar( 'sidebar-4' ); ?>
</div><!-- #third .widget-area -->
<?php endif; ?>
<?php if ( is_active_sidebar( 'sidebar-5' ) ) : ?>
<div id="fourth" class="widget-area" role="complementary">
<?php dynamic_sidebar( 'sidebar-5' ); ?>
</div><!-- #third .widget-area -->
<?php endif; ?>
</div><!-- #supplementary -->
</div><!-- #footer-sidebar --> | EcvetStep/ecvet-step.eu | wp-content/themes/ecvet-step/sidebar-footer.php | PHP | gpl-2.0 | 1,753 |
/* Copyright (C) 2008 AbiSource Corporation B.V.
*
* 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 <boost/lexical_cast.hpp>
#include "ServiceErrorCodes.h"
namespace abicollab {
namespace service {
SOAP_ERROR error(const soa::SoapFault& fault)
{
if (!fault.string())
return SOAP_ERROR_GENERIC;
try {
return static_cast<SOAP_ERROR>(boost::lexical_cast<int>(fault.string()->value()));
} catch (boost::bad_lexical_cast&) {
return SOAP_ERROR_GENERIC;
}
}
}
} | hfiguiere/abiword | plugins/collab/backends/service/xp/ServiceErrorCodes.cpp | C++ | gpl-2.0 | 1,153 |
<?php
namespace Google\AdsApi\AdWords\v201705\cm;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class ManualCpcBiddingScheme extends \Google\AdsApi\AdWords\v201705\cm\BiddingScheme
{
/**
* @var boolean $enhancedCpcEnabled
*/
protected $enhancedCpcEnabled = null;
/**
* @param string $BiddingSchemeType
* @param boolean $enhancedCpcEnabled
*/
public function __construct($BiddingSchemeType = null, $enhancedCpcEnabled = null)
{
parent::__construct($BiddingSchemeType);
$this->enhancedCpcEnabled = $enhancedCpcEnabled;
}
/**
* @return boolean
*/
public function getEnhancedCpcEnabled()
{
return $this->enhancedCpcEnabled;
}
/**
* @param boolean $enhancedCpcEnabled
* @return \Google\AdsApi\AdWords\v201705\cm\ManualCpcBiddingScheme
*/
public function setEnhancedCpcEnabled($enhancedCpcEnabled)
{
$this->enhancedCpcEnabled = $enhancedCpcEnabled;
return $this;
}
}
| renshuki/dfp-manager | vendor/googleads/googleads-php-lib/src/Google/AdsApi/AdWords/v201705/cm/ManualCpcBiddingScheme.php | PHP | gpl-2.0 | 1,018 |
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2007. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/workaround.hpp>
#ifdef BOOST_WINDOWS
//[doc_windows_shared_memory2
#include <boost/interprocess/windows_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
#include <cstring>
int main ()
{
using namespace boost::interprocess;
try{
//Open already created shared memory object.
windows_shared_memory shm(open_only, "shared_memory", read_only);
//Map the whole shared memory in this process
mapped_region region (shm, read_only);
//Check that memory was initialized to 1
const char *mem = static_cast<char*>(region.get_address());
for(std::size_t i = 0; i < 1000; ++i){
if(*mem++ != 1){
std::cout << "Error checking memory!" << std::endl;
return 1;
}
}
std::cout << "Test successful!" << std::endl;
}
catch(interprocess_exception &ex){
std::cout << "Unexpected exception: " << ex.what() << std::endl;
return 1;
}
return 0;
}
//]
#else //#ifdef BOOST_WINDOWS
int main()
{ return 0; }
#endif//#ifdef BOOST_WINDOWS
#include <boost/interprocess/detail/config_end.hpp>
| scs/uclinux | lib/boost/boost_1_38_0/libs/interprocess/example/doc_windows_shared_memory2.cpp | C++ | gpl-2.0 | 1,665 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_privacy
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/** @var PrivacyViewRequest $this */
// Include the component HTML helpers.
JHtml::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_privacy/helpers/html');
JHtml::_('behavior.formvalidator');
JHtml::_('behavior.keepalive');
$js = <<< JS
Joomla.submitbutton = function(task) {
if (task === 'request.cancel' || document.formvalidator.isValid(document.getElementById('item-form'))) {
Joomla.submitform(task, document.getElementById('item-form'));
}
};
JS;
JFactory::getDocument()->addScriptDeclaration($js);
?>
<form action="<?php echo JRoute::_('index.php?option=com_privacy&view=request&id=' . (int) $this->item->id); ?>" method="post" name="adminForm" id="item-form" class="form-validate">
<div class="row-fluid">
<div class="span6">
<h3><?php echo JText::_('COM_PRIVACY_HEADING_REQUEST_INFORMATION'); ?></h3>
<dl class="dl-horizontal">
<dt><?php echo JText::_('JGLOBAL_EMAIL'); ?>:</dt>
<dd><?php echo $this->item->email; ?></dd>
<dt><?php echo JText::_('JSTATUS'); ?>:</dt>
<dd><?php echo JHtml::_('PrivacyHtml.helper.statusLabel', $this->item->status); ?></dd>
<dt><?php echo JText::_('COM_PRIVACY_FIELD_REQUEST_TYPE_LABEL'); ?>:</dt>
<dd><?php echo JText::_('COM_PRIVACY_HEADING_REQUEST_TYPE_TYPE_' . $this->item->request_type); ?></dd>
<dt><?php echo JText::_('COM_PRIVACY_FIELD_REQUESTED_AT_LABEL'); ?>:</dt>
<dd><?php echo JHtml::_('date', $this->item->requested_at, JText::_('DATE_FORMAT_LC6')); ?></dd>
</dl>
</div>
<div class="span6">
<h3><?php echo JText::_('COM_PRIVACY_HEADING_ACTION_LOG'); ?></h3>
<?php if (empty($this->actionlogs)) : ?>
<div class="alert alert-no-items">
<?php echo JText::_('JGLOBAL_NO_MATCHING_RESULTS'); ?>
</div>
<?php else : ?>
<table class="table table-striped table-hover">
<thead>
<th>
<?php echo JText::_('COM_ACTIONLOGS_ACTION'); ?>
</th>
<th>
<?php echo JText::_('COM_ACTIONLOGS_DATE'); ?>
</th>
<th>
<?php echo JText::_('COM_ACTIONLOGS_NAME'); ?>
</th>
</thead>
<tbody>
<?php foreach ($this->actionlogs as $i => $item) : ?>
<tr class="row<?php echo $i % 2; ?>">
<td>
<?php echo ActionlogsHelper::getHumanReadableLogMessage($item); ?>
</td>
<td>
<?php echo JHtml::_('date', $item->log_date, JText::_('DATE_FORMAT_LC6')); ?>
</td>
<td>
<?php echo $item->name; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif;?>
</div>
</div>
<input type="hidden" name="task" value="" />
<?php echo JHtml::_('form.token'); ?>
</form>
| mvanvu/joomla-cms | administrator/components/com_privacy/views/request/tmpl/default.php | PHP | gpl-2.0 | 2,937 |
<?php
namespace FluidTYPO3\Flux\Tests\Unit\Transformation;
/*
* This file is part of the FluidTYPO3/Flux project under GPLv2 or later.
*
* For the full copyright and license information, please read the
* LICENSE.md file that was distributed with this source code.
*/
use FluidTYPO3\Flux\Form;
use FluidTYPO3\Flux\Tests\Unit\AbstractTestCase;
use FluidTYPO3\Flux\Transformation\FormDataTransformer;
/**
* Transforms data according to settings defined in the Form instance.
*
* @package FluidTYPO3\Flux
*/
class FormDataTransformerTest extends AbstractTestCase {
/**
* @test
* @dataProvider getValuesAndTransformations
* @param mixed $value
* @param string $transformation
* @param mixed $expected
*/
public function testTransformation($value, $transformation, $expected) {
$instance = $this->getMock('FluidTYPO3\\Flux\\Transformation\\FormDataTransformer', array('loadObjectsFromRepository'));
$instance->expects($this->any())->method('loadObjectsFromRepository')->willReturn(array());
$instance->injectObjectManager($this->objectManager);
$form = Form::create();
$form->createField('Input', 'field')->setTransform($transformation);
$transformed = $instance->transformAccordingToConfiguration(array('field' => $value), $form);
$this->assertTrue($transformed !== $expected, 'Transformation type ' . $transformation . ' failed; values are still identical');
}
/**
* @return array
*/
public function getValuesAndTransformations() {
return array(
array(array('1', '2', '3'), 'integer', array(1, 2, 3)),
array('0', 'integer', 0),
array('0.12', 'float', 0.12),
array('1,2,3', 'array', array(1, 2, 3)),
array('123,321', 'InvalidClass', '123'),
array(date('Ymd'), 'DateTime', new \DateTime(date('Ymd'))),
array('1', 'TYPO3\\CMS\\Extbase\\Domain\\Model\\FrontendUser', NULL),
array('1,2', 'TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage<TYPO3\\CMS\\Extbase\\Domain\\Model\\FrontendUser>', NULL),
array('1,2', 'TYPO3\\CMS\\Extbase\\Persistence\\ObjectStorage<\\Invalid>', NULL),
);
}
/**
* @test
*/
public function supportsFindByIdentifiers() {
$instance = new FormDataTransformer();
$identifiers = array('foobar', 'foobar2');
$repository = $this->getMock('TYPO3\\CMS\\Extbase\\Domain\\Repository\\FrontendUserGroupRepository', array('findByUid'),
array(), '', FALSE);
$repository->expects($this->exactly(2))->method('findByUid')->will($this->returnArgument(0));
$result = $this->callInaccessibleMethod($instance, 'loadObjectsFromRepository', $repository, $identifiers);
$this->assertEquals($result, array('foobar', 'foobar2'));
}
}
| famelo/TYPO3-Base | typo3conf/ext/flux/Tests/Unit/Transformation/FormDataTransformerTest.php | PHP | gpl-2.0 | 2,629 |
/* $Id: KeyboardImpl.cpp $ */
/** @file
* VirtualBox COM class implementation
*/
/*
* Copyright (C) 2006-2012 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.
*/
#include "KeyboardImpl.h"
#include "ConsoleImpl.h"
#include "AutoCaller.h"
#include "Logging.h"
#include <VBox/com/array.h>
#include <VBox/vmm/pdmdrv.h>
#include <iprt/asm.h>
#include <iprt/cpp/utils.h>
// defines
////////////////////////////////////////////////////////////////////////////////
// globals
////////////////////////////////////////////////////////////////////////////////
/** @name Keyboard device capabilities bitfield
* @{ */
enum
{
/** The keyboard device does not wish to receive keystrokes. */
KEYBOARD_DEVCAP_DISABLED = 0,
/** The keyboard device does wishes to receive keystrokes. */
KEYBOARD_DEVCAP_ENABLED = 1
};
/**
* Keyboard driver instance data.
*/
typedef struct DRVMAINKEYBOARD
{
/** Pointer to the keyboard object. */
Keyboard *pKeyboard;
/** Pointer to the driver instance structure. */
PPDMDRVINS pDrvIns;
/** Pointer to the keyboard port interface of the driver/device above us. */
PPDMIKEYBOARDPORT pUpPort;
/** Our keyboard connector interface. */
PDMIKEYBOARDCONNECTOR IConnector;
/** The capabilities of this device. */
uint32_t u32DevCaps;
} DRVMAINKEYBOARD, *PDRVMAINKEYBOARD;
/** Converts PDMIVMMDEVCONNECTOR pointer to a DRVMAINVMMDEV pointer. */
#define PPDMIKEYBOARDCONNECTOR_2_MAINKEYBOARD(pInterface) ( (PDRVMAINKEYBOARD) ((uintptr_t)pInterface - RT_OFFSETOF(DRVMAINKEYBOARD, IConnector)) )
// constructor / destructor
////////////////////////////////////////////////////////////////////////////////
Keyboard::Keyboard()
: mParent(NULL)
{
}
Keyboard::~Keyboard()
{
}
HRESULT Keyboard::FinalConstruct()
{
RT_ZERO(mpDrv);
mpVMMDev = NULL;
mfVMMDevInited = false;
return BaseFinalConstruct();
}
void Keyboard::FinalRelease()
{
uninit();
BaseFinalRelease();
}
// public methods
////////////////////////////////////////////////////////////////////////////////
/**
* Initializes the keyboard object.
*
* @returns COM result indicator
* @param parent handle of our parent object
*/
HRESULT Keyboard::init(Console *aParent)
{
LogFlowThisFunc(("aParent=%p\n", aParent));
ComAssertRet(aParent, E_INVALIDARG);
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
AssertReturn(autoInitSpan.isOk(), E_FAIL);
unconst(mParent) = aParent;
unconst(mEventSource).createObject();
HRESULT rc = mEventSource->init(static_cast<IKeyboard*>(this));
AssertComRCReturnRC(rc);
/* Confirm a successful initialization */
autoInitSpan.setSucceeded();
return S_OK;
}
/**
* Uninitializes the instance and sets the ready flag to FALSE.
* Called either from FinalRelease() or by the parent when it gets destroyed.
*/
void Keyboard::uninit()
{
LogFlowThisFunc(("\n"));
/* Enclose the state transition Ready->InUninit->NotReady */
AutoUninitSpan autoUninitSpan(this);
if (autoUninitSpan.uninitDone())
return;
for (unsigned i = 0; i < KEYBOARD_MAX_DEVICES; ++i)
{
if (mpDrv[i])
mpDrv[i]->pKeyboard = NULL;
mpDrv[i] = NULL;
}
mpVMMDev = NULL;
mfVMMDevInited = true;
unconst(mParent) = NULL;
unconst(mEventSource).setNull();
}
/**
* Sends a scancode to the keyboard.
*
* @returns COM status code
* @param scancode The scancode to send
*/
STDMETHODIMP Keyboard::PutScancode(LONG scancode)
{
com::SafeArray<LONG> scancodes(1);
scancodes[0] = scancode;
return PutScancodes(ComSafeArrayAsInParam(scancodes), NULL);
}
/**
* Sends a list of scancodes to the keyboard.
*
* @returns COM status code
* @param scancodes Pointer to the first scancode
* @param count Number of scancodes
* @param codesStored Address of variable to store the number
* of scancodes that were sent to the keyboard.
This value can be NULL.
*/
STDMETHODIMP Keyboard::PutScancodes(ComSafeArrayIn(LONG, scancodes),
ULONG *codesStored)
{
if (ComSafeArrayInIsNull(scancodes))
return E_INVALIDARG;
AutoCaller autoCaller(this);
if (FAILED(autoCaller.rc())) return autoCaller.rc();
com::SafeArray<LONG> keys(ComSafeArrayInArg(scancodes));
AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
CHECK_CONSOLE_DRV(mpDrv[0]);
/* Send input to the last enabled device. Relies on the fact that
* the USB keyboard is always initialized after the PS/2 keyboard.
*/
PPDMIKEYBOARDPORT pUpPort = NULL;
for (int i = KEYBOARD_MAX_DEVICES - 1; i >= 0 ; --i)
{
if (mpDrv[i] && (mpDrv[i]->u32DevCaps & KEYBOARD_DEVCAP_ENABLED))
{
pUpPort = mpDrv[i]->pUpPort;
break;
}
}
/* No enabled keyboard - throw the input away. */
if (!pUpPort)
{
if (codesStored)
*codesStored = (uint32_t)keys.size();
return S_OK;
}
int vrc = VINF_SUCCESS;
uint32_t sent;
for (sent = 0; (sent < keys.size()) && RT_SUCCESS(vrc); sent++)
vrc = pUpPort->pfnPutEvent(pUpPort, (uint8_t)keys[sent]);
if (codesStored)
*codesStored = sent;
/* Only signal the keys in the event which have been actually sent. */
com::SafeArray<LONG> keysSent(sent);
memcpy(keysSent.raw(), keys.raw(), sent*sizeof(LONG));
VBoxEventDesc evDesc;
evDesc.init(mEventSource, VBoxEventType_OnGuestKeyboard, ComSafeArrayAsInParam(keys));
evDesc.fire(0);
if (RT_FAILURE(vrc))
return setError(VBOX_E_IPRT_ERROR,
tr("Could not send all scan codes to the virtual keyboard (%Rrc)"),
vrc);
return S_OK;
}
/**
* Sends Control-Alt-Delete to the keyboard. This could be done otherwise
* but it's so common that we'll be nice and supply a convenience API.
*
* @returns COM status code
*
*/
STDMETHODIMP Keyboard::PutCAD()
{
static com::SafeArray<LONG> cadSequence(8);
cadSequence[0] = 0x1d; // Ctrl down
cadSequence[1] = 0x38; // Alt down
cadSequence[2] = 0xe0; // Del down 1
cadSequence[3] = 0x53; // Del down 2
cadSequence[4] = 0xe0; // Del up 1
cadSequence[5] = 0xd3; // Del up 2
cadSequence[6] = 0xb8; // Alt up
cadSequence[7] = 0x9d; // Ctrl up
return PutScancodes(ComSafeArrayAsInParam(cadSequence), NULL);
}
STDMETHODIMP Keyboard::COMGETTER(EventSource)(IEventSource ** aEventSource)
{
CheckComArgOutPointerValid(aEventSource);
AutoCaller autoCaller(this);
if (FAILED(autoCaller.rc())) return autoCaller.rc();
// no need to lock - lifetime constant
mEventSource.queryInterfaceTo(aEventSource);
return S_OK;
}
//
// private methods
//
/**
* @interface_method_impl{PDMIBASE,pfnQueryInterface}
*/
DECLCALLBACK(void *) Keyboard::drvQueryInterface(PPDMIBASE pInterface, const char *pszIID)
{
PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
PDRVMAINKEYBOARD pDrv = PDMINS_2_DATA(pDrvIns, PDRVMAINKEYBOARD);
PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
PDMIBASE_RETURN_INTERFACE(pszIID, PDMIKEYBOARDCONNECTOR, &pDrv->IConnector);
return NULL;
}
/**
* Destruct a keyboard driver instance.
*
* @returns VBox status.
* @param pDrvIns The driver instance data.
*/
DECLCALLBACK(void) Keyboard::drvDestruct(PPDMDRVINS pDrvIns)
{
PDRVMAINKEYBOARD pData = PDMINS_2_DATA(pDrvIns, PDRVMAINKEYBOARD);
LogFlow(("Keyboard::drvDestruct: iInstance=%d\n", pDrvIns->iInstance));
PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
if (pData->pKeyboard)
{
AutoWriteLock kbdLock(pData->pKeyboard COMMA_LOCKVAL_SRC_POS);
for (unsigned cDev = 0; cDev < KEYBOARD_MAX_DEVICES; ++cDev)
if (pData->pKeyboard->mpDrv[cDev] == pData)
{
pData->pKeyboard->mpDrv[cDev] = NULL;
break;
}
pData->pKeyboard->mpVMMDev = NULL;
}
}
DECLCALLBACK(void) keyboardLedStatusChange(PPDMIKEYBOARDCONNECTOR pInterface,
PDMKEYBLEDS enmLeds)
{
PDRVMAINKEYBOARD pDrv = PPDMIKEYBOARDCONNECTOR_2_MAINKEYBOARD(pInterface);
pDrv->pKeyboard->getParent()->onKeyboardLedsChange(!!(enmLeds & PDMKEYBLEDS_NUMLOCK),
!!(enmLeds & PDMKEYBLEDS_CAPSLOCK),
!!(enmLeds & PDMKEYBLEDS_SCROLLLOCK));
}
/**
* @interface_method_impl{PDMIKEYBOARDCONNECTOR,pfnSetActive}
*/
DECLCALLBACK(void) Keyboard::keyboardSetActive(PPDMIKEYBOARDCONNECTOR pInterface, bool fActive)
{
PDRVMAINKEYBOARD pDrv = PPDMIKEYBOARDCONNECTOR_2_MAINKEYBOARD(pInterface);
if (fActive)
pDrv->u32DevCaps |= KEYBOARD_DEVCAP_ENABLED;
else
pDrv->u32DevCaps &= ~KEYBOARD_DEVCAP_ENABLED;
}
/**
* Construct a keyboard driver instance.
*
* @copydoc FNPDMDRVCONSTRUCT
*/
DECLCALLBACK(int) Keyboard::drvConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg,
uint32_t fFlags)
{
PDRVMAINKEYBOARD pData = PDMINS_2_DATA(pDrvIns, PDRVMAINKEYBOARD);
LogFlow(("Keyboard::drvConstruct: iInstance=%d\n", pDrvIns->iInstance));
PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
/*
* Validate configuration.
*/
if (!CFGMR3AreValuesValid(pCfg, "Object\0"))
return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
("Configuration error: Not possible to attach anything to this driver!\n"),
VERR_PDM_DRVINS_NO_ATTACH);
/*
* IBase.
*/
pDrvIns->IBase.pfnQueryInterface = Keyboard::drvQueryInterface;
pData->IConnector.pfnLedStatusChange = keyboardLedStatusChange;
pData->IConnector.pfnSetActive = keyboardSetActive;
/*
* Get the IKeyboardPort interface of the above driver/device.
*/
pData->pUpPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIKEYBOARDPORT);
if (!pData->pUpPort)
{
AssertMsgFailed(("Configuration error: No keyboard port interface above!\n"));
return VERR_PDM_MISSING_INTERFACE_ABOVE;
}
/*
* Get the Keyboard object pointer and update the mpDrv member.
*/
void *pv;
int rc = CFGMR3QueryPtr(pCfg, "Object", &pv);
if (RT_FAILURE(rc))
{
AssertMsgFailed(("Configuration error: No/bad \"Object\" value! rc=%Rrc\n", rc));
return rc;
}
pData->pKeyboard = (Keyboard *)pv; /** @todo Check this cast! */
unsigned cDev;
for (cDev = 0; cDev < KEYBOARD_MAX_DEVICES; ++cDev)
if (!pData->pKeyboard->mpDrv[cDev])
{
pData->pKeyboard->mpDrv[cDev] = pData;
break;
}
if (cDev == KEYBOARD_MAX_DEVICES)
return VERR_NO_MORE_HANDLES;
return VINF_SUCCESS;
}
/**
* Keyboard driver registration record.
*/
const PDMDRVREG Keyboard::DrvReg =
{
/* u32Version */
PDM_DRVREG_VERSION,
/* szName */
"MainKeyboard",
/* szRCMod */
"",
/* szR0Mod */
"",
/* pszDescription */
"Main keyboard driver (Main as in the API).",
/* fFlags */
PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
/* fClass. */
PDM_DRVREG_CLASS_KEYBOARD,
/* cMaxInstances */
~0U,
/* cbInstance */
sizeof(DRVMAINKEYBOARD),
/* pfnConstruct */
Keyboard::drvConstruct,
/* pfnDestruct */
Keyboard::drvDestruct,
/* pfnRelocate */
NULL,
/* pfnIOCtl */
NULL,
/* pfnPowerOn */
NULL,
/* pfnReset */
NULL,
/* pfnSuspend */
NULL,
/* pfnResume */
NULL,
/* pfnAttach */
NULL,
/* pfnDetach */
NULL,
/* pfnPowerOff */
NULL,
/* pfnSoftReset */
NULL,
/* u32EndVersion */
PDM_DRVREG_VERSION
};
/* vi: set tabstop=4 shiftwidth=4 expandtab: */
| yuyuyu101/VirtualBox-NetBSD | src/VBox/Main/src-client/KeyboardImpl.cpp | C++ | gpl-2.0 | 12,529 |
/*
* Firemox is a turn based strategy simulator
* Copyright (C) 2003-2007 Fabrice Daugan
*
* 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 net.sf.firemox.clickable.ability;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.sf.firemox.clickable.target.card.MCard;
import net.sf.firemox.event.MEventListener;
import net.sf.firemox.test.And;
import net.sf.firemox.test.InZone;
import net.sf.firemox.test.Test;
import net.sf.firemox.test.TestFactory;
import net.sf.firemox.test.TestOn;
import net.sf.firemox.token.TrueFalseAuto;
/**
* @author <a href="mailto:fabdouglas@users.sourceforge.net">Fabrice Daugan </a>
* @since 0.93
*/
public class TriggeredAbilitySet extends TriggeredAbility {
/**
* Create a new instance of this class.
* <ul>
* Structure of InputStream : Data[size]
* <li>super [ActivatedAbility]</li>
* <li>when [Test]</li>
* </ul>
*
* @param input
* file containing this ability
* @param card
* referenced card
* @throws IOException
* if error occurred during the reading process from the specified
* input stream
*/
public TriggeredAbilitySet(InputStream input, MCard card) throws IOException {
super(input, card);
final Test when = TestFactory.readNextTest(input);
final List<MEventListener> events = new ArrayList<MEventListener>();
when.extractTriggeredEvents(events, card, And.append(new InZone(eventComing
.getIdPlace(), TestOn.THIS), when));
linkedAbilities = new ArrayList<Ability>(events.size());
for (MEventListener event : events) {
linkedAbilities.add(new NestedAbility(event));
}
}
/**
*
*/
private class NestedAbility extends TriggeredAbility {
/**
* Create a new instance of this class.
*
* @param event
*/
protected NestedAbility(MEventListener event) {
super(TriggeredAbilitySet.this, event);
this.playAsSpell = TrueFalseAuto.FALSE;
}
}
@Override
public Ability clone(MCard container) {
final Collection<Ability> linkedAbilities = new ArrayList<Ability>(
this.linkedAbilities.size());
for (Ability ability : linkedAbilities) {
linkedAbilities.add(ability.clone(container));
}
final TriggeredAbility clone = new TriggeredAbility(this, eventComing
.clone(container));
clone.playAsSpell = TrueFalseAuto.FALSE;
clone.linkedAbilities = linkedAbilities;
return clone;
}
}
| JoeyLeeuwinga/Firemox | src/main/java/net/sf/firemox/clickable/ability/TriggeredAbilitySet.java | Java | gpl-2.0 | 3,258 |
var requestQueue = new Request.Queue({
concurrent: monitorData.length,
stopOnFailure: false
});
function Monitor(monitorData) {
this.id = monitorData.id;
this.connKey = monitorData.connKey;
this.url = monitorData.url;
this.status = null;
this.alarmState = STATE_IDLE;
this.lastAlarmState = STATE_IDLE;
this.streamCmdParms = 'view=request&request=stream&connkey='+this.connKey;
if ( auth_hash ) {
this.streamCmdParms += '&auth='+auth_hash;
}
this.streamCmdTimer = null;
this.type = monitorData.type;
this.refresh = monitorData.refresh;
this.start = function(delay) {
if ( this.streamCmdQuery ) {
this.streamCmdTimer = this.streamCmdQuery.delay(delay, this);
} else {
console.log("No streamCmdQuery");
}
};
this.eventHandler = function(event) {
console.log(event);
};
this.onclick = function(evt) {
var el = evt.currentTarget;
var tag = 'watch';
var id = el.getAttribute("data-monitor-id");
var width = el.getAttribute("data-width");
var height = el.getAttribute("data-height");
var url = '?view=watch&mid='+id;
var name = 'zmWatch'+id;
evt.preventDefault();
createPopup(url, name, tag, width, height);
};
this.setup_onclick = function() {
var el = document.getElementById('imageFeed'+this.id);
if ( el ) el.addEventListener('click', this.onclick, false);
};
this.disable_onclick = function() {
document.getElementById('imageFeed'+this.id).removeEventListener('click', this.onclick );
};
this.setStateClass = function(element, stateClass) {
if ( !element.hasClass( stateClass ) ) {
if ( stateClass != 'alarm' ) {
element.removeClass('alarm');
}
if ( stateClass != 'alert' ) {
element.removeClass('alert');
}
if ( stateClass != 'idle' ) {
element.removeClass('idle');
}
element.addClass(stateClass);
}
};
this.onError = function(text, error) {
console.log('onerror: ' + text + ' error:'+error);
// Requeue, but want to wait a while.
var streamCmdTimeout = 10*statusRefreshTimeout;
this.streamCmdTimer = this.streamCmdQuery.delay(streamCmdTimeout, this);
};
this.onFailure = function(xhr) {
console.log('onFailure: ' + this.connKey);
console.log(xhr);
if ( ! requestQueue.hasNext("cmdReq"+this.id) ) {
console.log("Not requeuing because there is one already");
requestQueue.addRequest("cmdReq"+this.id, this.streamCmdReq);
}
if ( 0 ) {
// Requeue, but want to wait a while.
if ( this.streamCmdTimer ) {
this.streamCmdTimer = clearTimeout( this.streamCmdTimer );
}
var streamCmdTimeout = 1000*statusRefreshTimeout;
this.streamCmdTimer = this.streamCmdQuery.delay( streamCmdTimeout, this, true );
requestQueue.resume();
}
console.log("done failure");
};
this.getStreamCmdResponse = function(respObj, respText) {
if ( this.streamCmdTimer ) {
this.streamCmdTimer = clearTimeout( this.streamCmdTimer );
}
var stream = $j('#liveStream'+this.id)[0];
if ( respObj.result == 'Ok' ) {
if ( respObj.status ) {
this.status = respObj.status;
this.alarmState = this.status.state;
var stateClass = "";
if ( this.alarmState == STATE_ALARM ) {
stateClass = "alarm";
} else if ( this.alarmState == STATE_ALERT ) {
stateClass = "alert";
} else {
stateClass = "idle";
}
if ( (!COMPACT_MONTAGE) && (this.type != 'WebSite') ) {
$('fpsValue'+this.id).set('text', this.status.fps);
$('stateValue'+this.id).set('text', stateStrings[this.alarmState]);
this.setStateClass($('monitorState'+this.id), stateClass);
}
this.setStateClass($('monitor'+this.id), stateClass);
/*Stream could be an applet so can't use moo tools*/
stream.className = stateClass;
var isAlarmed = ( this.alarmState == STATE_ALARM || this.alarmState == STATE_ALERT );
var wasAlarmed = ( this.lastAlarmState == STATE_ALARM || this.lastAlarmState == STATE_ALERT );
var newAlarm = ( isAlarmed && !wasAlarmed );
var oldAlarm = ( !isAlarmed && wasAlarmed );
if ( newAlarm ) {
if ( false && SOUND_ON_ALARM ) {
// Enable the alarm sound
$('alarmSound').removeClass('hidden');
}
if ( POPUP_ON_ALARM ) {
windowToFront();
}
}
if ( false && SOUND_ON_ALARM ) {
if ( oldAlarm ) {
// Disable alarm sound
$('alarmSound').addClass('hidden');
}
}
if ( this.status.auth ) {
if ( this.status.auth != auth_hash ) {
// Try to reload the image stream.
if ( stream ) {
stream.src = stream.src.replace(/auth=\w+/i, 'auth='+this.status.auth);
}
console.log("Changed auth from " + auth_hash + " to " + this.status.auth);
auth_hash = this.status.auth;
}
} // end if have a new auth hash
} // end if has state
} else {
console.error(respObj.message);
// Try to reload the image stream.
if ( stream ) {
if ( stream.src ) {
console.log('Reloading stream: ' + stream.src);
stream.src = stream.src.replace(/rand=\d+/i, 'rand='+Math.floor((Math.random() * 1000000) ));
} else {
}
} else {
console.log('No stream to reload?');
}
} // end if Ok or not
var streamCmdTimeout = statusRefreshTimeout;
// The idea here is if we are alarmed, do updates faster.
// However, there is a timeout in the php side which isn't getting modified,
// so this may cause a problem. Also the server may only be able to update so fast.
//if ( this.alarmState == STATE_ALARM || this.alarmState == STATE_ALERT ) {
//streamCmdTimeout = streamCmdTimeout/5;
//}
this.streamCmdTimer = this.streamCmdQuery.delay(streamCmdTimeout, this);
this.lastAlarmState = this.alarmState;
};
this.streamCmdQuery = function(resent) {
if ( resent ) {
console.log(this.connKey+": timeout: Resending");
this.streamCmdReq.cancel();
}
//console.log("Starting CmdQuery for " + this.connKey );
if ( this.type != 'WebSite' ) {
this.streamCmdReq.send(this.streamCmdParms+"&command="+CMD_QUERY);
}
};
if ( this.type != 'WebSite' ) {
this.streamCmdReq = new Request.JSON( {
url: this.url,
method: 'get',
timeout: AJAX_TIMEOUT,
onSuccess: this.getStreamCmdResponse.bind(this),
onTimeout: this.streamCmdQuery.bind(this, true),
onError: this.onError.bind(this),
onFailure: this.onFailure.bind(this),
link: 'cancel'
} );
console.log("queueing for " + this.id + " " + this.connKey + " timeout is: " + AJAX_TIMEOUT);
requestQueue.addRequest("cmdReq"+this.id, this.streamCmdReq);
}
} // end function Monitor
/**
* called when the layoutControl select element is changed, or the page
* is rendered
* @param {*} element - the event data passed by onchange callback
*/
function selectLayout(element) {
console.log(element);
layout = $j(element).val();
if ( layout_id = parseInt(layout) ) {
layout = layouts[layout];
for ( var i = 0, length = monitors.length; i < length; i++ ) {
monitor = monitors[i];
// Need to clear the current positioning, and apply the new
monitor_frame = $j('#monitorFrame'+monitor.id);
if ( ! monitor_frame ) {
console.log("Error finding frame for " + monitor.id);
continue;
}
// Apply default layout options, like float left
if ( layout.Positions['default'] ) {
styles = layout.Positions['default'];
for ( style in styles ) {
monitor_frame.css(style, styles[style]);
}
} else {
console.log("No default styles to apply" + layout.Positions);
} // end if default styles
if ( layout.Positions['mId'+monitor.id] ) {
styles = layout.Positions['mId'+monitor.id];
for ( style in styles ) {
monitor_frame.css(style, styles[style]);
console.log("Applying " + style + ' : ' + styles[style]);
}
} else {
console.log("No Monitor styles to apply");
} // end if specific monitor style
} // end foreach monitor
} // end if a stored layout
if ( ! layout ) {
return;
}
Cookie.write('zmMontageLayout', layout_id, {duration: 10*365});
if ( layouts[layout_id].Name != 'Freeform' ) { // 'montage_freeform.css' ) {
Cookie.write( 'zmMontageScale', '', {duration: 10*365} );
$('scale').set('value', '');
$('width').set('value', 'auto');
for ( var i = 0, length = monitors.length; i < length; i++ ) {
var monitor = monitors[i];
var streamImg = $('liveStream'+monitor.id);
if ( streamImg ) {
if ( streamImg.nodeName == 'IMG' ) {
var src = streamImg.src;
src = src.replace(/width=[\.\d]+/i, 'width=0' );
if ( src != streamImg.src ) {
streamImg.src = '';
streamImg.src = src;
}
} else if ( streamImg.nodeName == 'APPLET' || streamImg.nodeName == 'OBJECT' ) {
// APPLET's and OBJECTS need to be re-initialized
}
streamImg.style.width = '100%';
}
} // end foreach monitor
}
} // end function selectLayout(element)
/**
* called when the widthControl|heightControl select elements are changed
*/
function changeSize() {
var width = $('width').get('value');
var height = $('height').get('value');
for ( var i = 0, length = monitors.length; i < length; i++ ) {
var monitor = monitors[i];
// Scale the frame
monitor_frame = $j('#monitorFrame'+monitor.id);
if ( !monitor_frame ) {
console.log("Error finding frame for " + monitor.id);
continue;
}
if ( width ) {
monitor_frame.css('width', width);
}
if ( height ) {
monitor_frame.css('height', height);
}
/*Stream could be an applet so can't use moo tools*/
var streamImg = $('liveStream'+monitor.id);
if ( streamImg ) {
if ( streamImg.nodeName == 'IMG' ) {
var src = streamImg.src;
streamImg.src = '';
src = src.replace(/width=[\.\d]+/i, 'width='+width);
src = src.replace(/height=[\.\d]+/i, 'height='+height);
src = src.replace(/rand=\d+/i, 'rand='+Math.floor((Math.random() * 1000000) ));
streamImg.src = src;
}
streamImg.style.width = width ? width : null;
streamImg.style.height = height ? height : null;
//streamImg.style.height = '';
}
}
$('scale').set('value', '');
Cookie.write('zmMontageScale', '', {duration: 10*365});
Cookie.write('zmMontageWidth', width, {duration: 10*365});
Cookie.write('zmMontageHeight', height, {duration: 10*365});
//selectLayout('#zmMontageLayout');
} // end function changeSize()
/**
* called when the scaleControl select element is changed
*/
function changeScale() {
var scale = $('scale').get('value');
$('width').set('value', 'auto');
$('height').set('value', 'auto');
Cookie.write('zmMontageScale', scale, {duration: 10*365});
Cookie.write('zmMontageWidth', '', {duration: 10*365});
Cookie.write('zmMontageHeight', '', {duration: 10*365});
if ( !scale ) {
selectLayout('#zmMontageLayout');
return;
}
for ( var i = 0, length = monitors.length; i < length; i++ ) {
var monitor = monitors[i];
var newWidth = ( monitorData[i].width * scale ) / SCALE_BASE;
var newHeight = ( monitorData[i].height * scale ) / SCALE_BASE;
// Scale the frame
monitor_frame = $j('#monitorFrame'+monitor.id);
if ( !monitor_frame ) {
console.log("Error finding frame for " + monitor.id);
continue;
}
if ( newWidth ) {
monitor_frame.css('width', newWidth);
}
// We don't set the frame height because it has the status bar as well
//if ( height ) {
////monitor_frame.css('height', height+'px');
//}
/*Stream could be an applet so can't use moo tools*/
var streamImg = $j('#liveStream'+monitor.id)[0];
if ( streamImg ) {
if ( streamImg.nodeName == 'IMG' ) {
var src = streamImg.src;
streamImg.src = '';
//src = src.replace(/rand=\d+/i,'rand='+Math.floor((Math.random() * 1000000) ));
src = src.replace(/scale=[\.\d]+/i, 'scale='+scale);
src = src.replace(/width=[\.\d]+/i, 'width='+newWidth);
src = src.replace(/height=[\.\d]+/i, 'height='+newHeight);
streamImg.src = src;
}
streamImg.style.width = newWidth + "px";
streamImg.style.height = newHeight + "px";
}
}
}
function toGrid(value) {
return Math.round(value / 80) * 80;
}
// Makes monitorFrames draggable.
function edit_layout(button) {
// Turn off the onclick on the image.
for ( var i = 0, length = monitors.length; i < length; i++ ) {
var monitor = monitors[i];
monitor.disable_onclick();
};
$j('#monitors .monitorFrame').draggable({
cursor: 'crosshair',
//revert: 'invalid'
});
$j('#SaveLayout').show();
$j('#EditLayout').hide();
} // end function edit_layout
function save_layout(button) {
var form = button.form;
var name = form.elements['Name'].value;
if ( !name ) {
name = form.elements['zmMontageLayout'].options[form.elements['zmMontageLayout'].selectedIndex].text;
}
if ( name=='Freeform' || name=='2 Wide' || name=='3 Wide' || name=='4 Wide' || name=='5 Wide' ) {
alert('You cannot edit the built in layouts. Please give the layout a new name.');
return;
}
// In fixed positioning, order doesn't matter. In floating positioning, it does.
var Positions = {};
for ( var i = 0, length = monitors.length; i < length; i++ ) {
var monitor = monitors[i];
monitor_frame = $j('#monitorFrame'+monitor.id);
Positions['mId'+monitor.id] = {
width: monitor_frame.css('width'),
height: monitor_frame.css('height'),
top: monitor_frame.css('top'),
bottom: monitor_frame.css('bottom'),
left: monitor_frame.css('left'),
right: monitor_frame.css('right'),
position: monitor_frame.css('position'),
float: monitor_frame.css('float'),
};
} // end foreach monitor
form.Positions.value = JSON.stringify(Positions);
form.submit();
} // end function save_layout
function cancel_layout(button) {
$j('#SaveLayout').hide();
$j('#EditLayout').show();
for ( var i = 0, length = monitors.length; i < length; i++ ) {
var monitor = monitors[i];
monitor.setup_onclick();
//monitor_feed = $j('#imageFeed'+monitor.id);
//monitor_feed.click(monitor.onclick);
};
selectLayout('#zmMontageLayout');
}
function reloadWebSite(ndx) {
document.getElementById('imageFeed'+ndx).innerHTML = document.getElementById('imageFeed'+ndx).innerHTML;
}
var monitors = new Array();
function initPage() {
jQuery(document).ready(function() {
jQuery("#hdrbutton").click(function() {
jQuery("#flipMontageHeader").slideToggle("slow");
jQuery("#hdrbutton").toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up');
Cookie.write( 'zmMontageHeaderFlip', jQuery('#hdrbutton').hasClass('glyphicon-menu-up') ? 'up' : 'down', {duration: 10*365} );
});
});
if ( Cookie.read('zmMontageHeaderFlip') == 'down' ) {
// The chosen dropdowns require the selects to be visible, so once chosen has initialized, we can hide the header
jQuery("#flipMontageHeader").slideToggle("fast");
jQuery("#hdrbutton").toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up');
}
for ( var i = 0, length = monitorData.length; i < length; i++ ) {
monitors[i] = new Monitor(monitorData[i]);
// Start the fps and status updates. give a random delay so that we don't assault the server
var delay = Math.round( (Math.random()+0.5)*statusRefreshTimeout );
monitors[i].start(delay);
var interval = monitors[i].refresh;
if ( monitors[i].type == 'WebSite' && interval > 0 ) {
setInterval(reloadWebSite, interval*1000, i);
}
monitors[i].setup_onclick();
}
selectLayout('#zmMontageLayout');
}
// Kick everything off
window.addEventListener('DOMContentLoaded', initPage);
| Simpler1/ZoneMinder | web/skins/classic/views/js/montage.js | JavaScript | gpl-2.0 | 16,321 |
from miasm2.core.asmblock import disasmEngine
from miasm2.arch.aarch64.arch import mn_aarch64
cb_aarch64_funcs = []
def cb_aarch64_disasm(*args, **kwargs):
for func in cb_aarch64_funcs:
func(*args, **kwargs)
class dis_aarch64b(disasmEngine):
attrib = "b"
def __init__(self, bs=None, **kwargs):
super(dis_aarch64b, self).__init__(
mn_aarch64, self.attrib, bs,
dis_bloc_callback = cb_aarch64_disasm,
**kwargs)
class dis_aarch64l(disasmEngine):
attrib = "l"
def __init__(self, bs=None, **kwargs):
super(dis_aarch64l, self).__init__(
mn_aarch64, self.attrib, bs,
dis_bloc_callback = cb_aarch64_disasm,
**kwargs)
| stephengroat/miasm | miasm2/arch/aarch64/disasm.py | Python | gpl-2.0 | 731 |
/************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
*
* Use is subject to license terms.
*
* 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. You can also
* obtain a copy of the License at http://odftoolkit.org/docs/license.txt
*
* 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.
*
************************************************************************/
/*
* This file is automatically generated.
* Don't edit manually.
*/
package org.odftoolkit.odfdom.dom.attribute.table;
import org.odftoolkit.odfdom.dom.OdfDocumentNamespace;
import org.odftoolkit.odfdom.pkg.OdfAttribute;
import org.odftoolkit.odfdom.pkg.OdfFileDom;
import org.odftoolkit.odfdom.pkg.OdfName;
/**
* DOM implementation of OpenDocument attribute {@odf.attribute table:script}.
*
*/
public class TableScriptAttribute extends OdfAttribute {
public static final OdfName ATTRIBUTE_NAME = OdfName.newName(OdfDocumentNamespace.TABLE, "script");
/**
* Create the instance of OpenDocument attribute {@odf.attribute table:script}.
*
* @param ownerDocument The type is <code>OdfFileDom</code>
*/
public TableScriptAttribute(OdfFileDom ownerDocument) {
super(ownerDocument, ATTRIBUTE_NAME);
}
/**
* Returns the attribute name.
*
* @return the <code>OdfName</code> for {@odf.attribute table:script}.
*/
@Override
public OdfName getOdfName() {
return ATTRIBUTE_NAME;
}
/**
* @return Returns the name of this attribute.
*/
@Override
public String getName() {
return ATTRIBUTE_NAME.getLocalName();
}
/**
* Returns the default value of {@odf.attribute table:script}.
*
* @return the default value as <code>String</code> dependent of its element name
* return <code>null</code> if the default value does not exist
*/
@Override
public String getDefault() {
return null;
}
/**
* Default value indicator. As the attribute default value is dependent from its element, the attribute has only a default, when a parent element exists.
*
* @return <code>true</code> if {@odf.attribute table:script} has an element parent
* otherwise return <code>false</code> as undefined.
*/
@Override
public boolean hasDefault() {
return false;
}
/**
* @return Returns whether this attribute is known to be of type ID (i.e. xml:id ?)
*/
@Override
public boolean isId() {
return false;
}
}
| jbjonesjr/geoproponis | external/odfdom-java-0.8.10-incubating-sources/org/odftoolkit/odfdom/dom/attribute/table/TableScriptAttribute.java | Java | gpl-2.0 | 2,957 |
<?
/**[N]**
* JIBAS Education Community
* Jaringan Informasi Bersama Antar Sekolah
*
* @version: 3.2 (September 03, 2013)
* @notes: JIBAS Education Community will be managed by Yayasan Indonesia Membaca (http://www.indonesiamembaca.net)
*
* Copyright (C) 2009 Yayasan Indonesia Membaca (http://www.indonesiamembaca.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 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
**[N]**/ ?>
<?
require_once('../../include/sessionchecker.php');
require_once('../../include/common.php');
require_once('../../include/sessioninfo.php');
require_once('../../include/config.php');
require_once('../../include/db_functions.php');
$op="";
if (isset($_REQUEST[op]))
$op=$_REQUEST[op];
$page='t';
if (isset($_REQUEST[page]))
$page = $_REQUEST[page];
OpenDb();
$sql="SELECT * FROM jbsvcr.galerifoto WHERE idguru='".SI_USER_ID()."'";
$result=QueryDb($sql);
$num=@mysql_num_rows($result);
$cnt=1;
while ($row=@mysql_fetch_array($result))
{
$ket[$cnt]=$row[keterangan];
$nama[$cnt]=$row[nama];
$fn[$cnt]=$row[filename];
$rep[$cnt]=$row[replid];
$cnt++;
}
CloseDb();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" href="../../script/TinySlideshow/style.css" />
<link href="../../style/style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="../../script/contentslider.css" />
<script type="text/javascript" language="javascript" src="../../style/lytebox.js"></script>
<script type="text/javascript" language="javascript" src="../../script/tools.js"></script>
<link rel="stylesheet" href="../../style/lytebox.css" type="text/css" media="screen" />
<script type="text/javascript" src="../../script/contentslider.js"></script>
<script language="javascript" src="../../script/ajax.js"></script>
<script src="SpryTabbedPanels.js" type="text/javascript"></script>
<script language="javascript" >
function get_fresh(){
document.location.href="galerifoto_ss.php";
}
function over(id){
var actmenu = document.getElementById('actmenu').value;
if (actmenu==id)
return false;
if (actmenu=='t')
document.getElementById('tabimages').src='../../images/s_over.png';
else
document.getElementById('tabimages').src='../../images/t_over.png';
}
function out(id){
var actmenu = document.getElementById('actmenu').value;
if (actmenu==id)
return false;
if (actmenu=='t')
document.getElementById('tabimages').src='../../images/t.png';
else
document.getElementById('tabimages').src='../../images/s.png';
}
function show(id){
if (id=='t'){
document.getElementById('actmenu').value='t';
document.getElementById('tabimages').src='../../images/t.png';
document.getElementById('slice_t').style.display='';
document.getElementById('salideshow').style.display='none';
} else {
document.getElementById('actmenu').value='s';
document.getElementById('tabimages').src='../../images/s.png';
document.getElementById('slice_t').style.display='none';
document.getElementById('salideshow').style.display='';
}
}
</script>
<style type="text/css">
<!--
.style1 {
font-size: 0.7px;
font-family: Verdana;
}
.style3 {font-size: 12px}
-->
</style>
<link href="SpryTabbedPanels.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="100%" border="0" cellspacing="5">
<tr>
<td align="left"><font size="4" style="background-color:#ffcc66"> </font> <font size="4" color="Gray">Galeri Foto</font><br />
<a href="../../home.php" target="framecenter">Home</a> > <strong>Galeri Foto</strong><br />
<br /></td>
<td align="right" valign="bottom">
<a href="galerifoto.php"><img src="../../images/ico/thumbnail.gif" border="0"> Thumbnails</a>
<a href="#" onClick="newWindow('tambahfoto.php?pagesource=ss','TambahFoto','550','207','resizable=1,scrollbars=0,status=0,toolbar=0');"><img src="../../images/ico/tambah.png" border="0" /> Tambah Foto</a><br>
</td>
</tr>
<tr>
<td align="left" colspan='2'>
<table border='0' width='100%'>
<tr>
<td width='25%'> </td>
<td width='*'>
<? if ($num>0)
{ ?>
<ul id="slideshow">
<? for ($i = 1; $i <= $num; $i++)
{
$fphoto = "$FILESHARE_ADDR/galeriguru/photos/".$fn[$i];
$fthumb = "$FILESHARE_ADDR/galeriguru/thumbnails/".$fn[$i]; ?>
<li>
<h3><?=$nama[$i]?></h3>
<span><?=$fphoto?></span>
<p><?=$ket[$i]?></p>
<a href="#"><img src="<?=$fthumb?>" height="480" alt="" /></a>
</li>
<? } ?>
</ul>
<div id="wrapper" >
<div id="fullsize" style="width: 800px; height: 600px;">
<div id="imgprev" class="imgnav" title="Previous Image"></div>
<div id="imglink"></div>
<div id="imgnext" class="imgnav" title="Next Image"></div>
<div id="image"></div>
<div id="information">
<h3></h3>
<p></p>
</div>
</div>
<div id="thumbnails" style="visibility: hidden;">
<div id="slideleft" title="Slide Left"></div>
<div id="slidearea">
<div id="slider"></div>
</div>
<div id="slideright" title="Slide Right"></div>
</div>
</div>
<script type="text/javascript" src="../../script/TinySlideshow/compressed.js"></script>
<script type="text/javascript">
$('slideshow').style.display='none';
$('wrapper').style.display='block';
var slideshow=new TINY.slideshow("slideshow");
window.onload=function(){
slideshow.auto=true;
slideshow.speed=5;
slideshow.link="linkhover";
slideshow.info="information";
slideshow.thumbs="slider";
slideshow.left="slideleft";
slideshow.right="slideright";
slideshow.scrollSpeed=4;
slideshow.height=480;
slideshow.spacing=5;
slideshow.active="#fff";
slideshow.init("slideshow","image","imgprev","imgnext","imglink");
}
</script>
<? } else { ?>
<table width="100%" border="0" cellspacing="0" align="center">
<tr>
<td><div align="center"><em>Tidak ada foto</em></div></td>
</tr>
</table>
<? } ?>
</td>
<td width='25%'> </td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html> | nurulimamnotes/sistem-informasi-sekolah | jibas/infosiswa/buletin/galerifoto/galerifoto_ss.php | PHP | gpl-2.0 | 7,300 |
/*
Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.myblockchain.clusterj.tie;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.myblockchain.clusterj.ClusterJUserException;
import com.myblockchain.clusterj.core.store.Blob;
import com.myblockchain.clusterj.core.store.Column;
import com.myblockchain.clusterj.core.store.Operation;
import com.myblockchain.clusterj.core.store.ResultData;
import com.myblockchain.clusterj.core.store.Table;
import com.myblockchain.clusterj.core.util.I18NHelper;
import com.myblockchain.clusterj.core.util.Logger;
import com.myblockchain.clusterj.core.util.LoggerFactoryService;
import com.myblockchain.clusterj.tie.DbImpl.BufferManager;
import com.myblockchain.ndbjtie.ndbapi.NdbBlob;
import com.myblockchain.ndbjtie.ndbapi.NdbOperation;
/**
*
*/
class OperationImpl implements Operation {
/** My message translator */
static final I18NHelper local = I18NHelper
.getInstance(OperationImpl.class);
/** My logger */
static final Logger logger = LoggerFactoryService.getFactory()
.getInstance(OperationImpl.class);
private NdbOperation ndbOperation;
protected List<Column> storeColumns = new ArrayList<Column>();
protected ClusterTransactionImpl clusterTransaction;
/** The size of the receive buffer for this operation (may be zero for non-read operations) */
protected int bufferSize;
/** The maximum column id for this operation (may be zero for non-read operations) */
protected int maximumColumnId;
/** The offsets into the buffer for each column (may be null for non-read operations) */
protected int[] offsets;
/** The lengths of fields in the buffer for each column (may be null for non-read operations) */
protected int[] lengths;
/** The maximum length of any column in this operation */
protected int maximumColumnLength;
protected BufferManager bufferManager;
/** Constructor used for insert and delete operations that do not need to read data.
*
* @param operation the operation
* @param transaction the transaction
*/
public OperationImpl(NdbOperation operation, ClusterTransactionImpl transaction) {
this.ndbOperation = operation;
this.clusterTransaction = transaction;
this.bufferManager = clusterTransaction.getBufferManager();
}
/** Constructor used for read operations. The table is used to obtain data used
* to lay out memory for the result.
* @param storeTable the table
* @param operation the operation
* @param transaction the transaction
*/
public OperationImpl(Table storeTable, NdbOperation operation, ClusterTransactionImpl transaction) {
this(operation, transaction);
TableImpl tableImpl = (TableImpl)storeTable;
this.maximumColumnId = tableImpl.getMaximumColumnId();
this.bufferSize = tableImpl.getBufferSize();
this.offsets = tableImpl.getOffsets();
this.lengths = tableImpl.getLengths();
this.maximumColumnLength = tableImpl.getMaximumColumnLength();
}
public void equalBigInteger(Column storeColumn, BigInteger value) {
ByteBuffer buffer = Utility.convertValue(storeColumn, value);
int returnCode = ndbOperation.equal(storeColumn.getName(), buffer);
handleError(returnCode, ndbOperation);
}
public void equalBoolean(Column storeColumn, boolean booleanValue) {
byte value = (booleanValue?(byte)0x01:(byte)0x00);
int returnCode = ndbOperation.equal(storeColumn.getName(), value);
handleError(returnCode, ndbOperation);
}
public void equalByte(Column storeColumn, byte value) {
int storeValue = Utility.convertByteValueForStorage(storeColumn, value);
int returnCode = ndbOperation.equal(storeColumn.getName(), storeValue);
handleError(returnCode, ndbOperation);
}
public void equalBytes(Column storeColumn, byte[] value) {
if (logger.isDetailEnabled()) logger.detail("Column: " + storeColumn.getName() + " columnId: " + storeColumn.getColumnId() + " data length: " + value.length);
ByteBuffer buffer = Utility.convertValue(storeColumn, value);
int returnCode = ndbOperation.equal(storeColumn.getName(), buffer);
handleError(returnCode, ndbOperation);
}
public void equalDecimal(Column storeColumn, BigDecimal value) {
ByteBuffer buffer = Utility.convertValue(storeColumn, value);
int returnCode = ndbOperation.equal(storeColumn.getName(), buffer);
handleError(returnCode, ndbOperation);
}
public void equalDouble(Column storeColumn, double value) {
ByteBuffer buffer = Utility.convertValue(storeColumn, value);
int returnCode = ndbOperation.equal(storeColumn.getName(), buffer);
handleError(returnCode, ndbOperation);
}
public void equalFloat(Column storeColumn, float value) {
ByteBuffer buffer = Utility.convertValue(storeColumn, value);
int returnCode = ndbOperation.equal(storeColumn.getName(), buffer);
handleError(returnCode, ndbOperation);
}
public void equalInt(Column storeColumn, int value) {
int returnCode = ndbOperation.equal(storeColumn.getName(), value);
handleError(returnCode, ndbOperation);
}
public void equalShort(Column storeColumn, short value) {
int storeValue = Utility.convertShortValueForStorage(storeColumn, value);
int returnCode = ndbOperation.equal(storeColumn.getName(), storeValue);
handleError(returnCode, ndbOperation);
}
public void equalLong(Column storeColumn, long value) {
long storeValue = Utility.convertLongValueForStorage(storeColumn, value);
int returnCode = ndbOperation.equal(storeColumn.getName(), storeValue);
handleError(returnCode, ndbOperation);
}
public void equalString(Column storeColumn, String value) {
ByteBuffer stringStorageBuffer = Utility.encode(value, storeColumn, bufferManager);
int returnCode = ndbOperation.equal(storeColumn.getName(), stringStorageBuffer);
bufferManager.clearStringStorageBuffer();
handleError(returnCode, ndbOperation);
}
public void getBlob(Column storeColumn) {
NdbBlob ndbBlob = ndbOperation.getBlobHandleM(storeColumn.getColumnId());
handleError(ndbBlob, ndbOperation);
}
public Blob getBlobHandle(Column storeColumn) {
NdbBlob blobHandle = ndbOperation.getBlobHandleM(storeColumn.getColumnId());
handleError(blobHandle, ndbOperation);
return new BlobImpl(blobHandle);
}
/** Specify the columns to be used for the operation.
* For now, just save the columns. When resultData is called, pass the columns
* to the ResultData constructor and then execute the operation.
*
*/
public void getValue(Column storeColumn) {
storeColumns.add(storeColumn);
}
public void postExecuteCallback(Runnable callback) {
clusterTransaction.postExecuteCallback(callback);
}
/** Construct a new ResultData using the saved column data and then execute the operation.
*
*/
public ResultData resultData() {
return resultData(true);
}
/** Construct a new ResultData and if requested, execute the operation.
*
*/
public ResultData resultData(boolean execute) {
if (logger.isDetailEnabled()) logger.detail("storeColumns: " + Arrays.toString(storeColumns.toArray()));
ResultDataImpl result;
if (execute) {
result = new ResultDataImpl(ndbOperation, storeColumns, maximumColumnId, bufferSize,
offsets, lengths, bufferManager, false);
clusterTransaction.executeNoCommit(false, true);
} else {
result = new ResultDataImpl(ndbOperation, storeColumns, maximumColumnId, bufferSize,
offsets, lengths, bufferManager, true);
}
return result;
}
public void setBigInteger(Column storeColumn, BigInteger value) {
ByteBuffer buffer = Utility.convertValue(storeColumn, value);
int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), buffer);
handleError(returnCode, ndbOperation);
}
public void setBoolean(Column storeColumn, Boolean value) {
byte byteValue = (value?(byte)0x01:(byte)0x00);
setByte(storeColumn, byteValue);
}
public void setByte(Column storeColumn, byte value) {
int storeValue = Utility.convertByteValueForStorage(storeColumn, value);
int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), storeValue);
handleError(returnCode, ndbOperation);
}
public void setBytes(Column storeColumn, byte[] value) {
// TODO use the string storage buffer instead of allocating a new buffer for each value
int length = value.length;
if (length > storeColumn.getLength()) {
throw new ClusterJUserException(local.message("ERR_Data_Too_Long",
storeColumn.getName(), storeColumn.getLength(), length));
}
ByteBuffer buffer = Utility.convertValue(storeColumn, value);
int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), buffer);
handleError(returnCode, ndbOperation);
}
public void setDecimal(Column storeColumn, BigDecimal value) {
ByteBuffer buffer = Utility.convertValue(storeColumn, value);
int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), buffer);
handleError(returnCode, ndbOperation);
}
public void setDouble(Column storeColumn, Double value) {
int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), value);
handleError(returnCode, ndbOperation);
}
public void setFloat(Column storeColumn, Float value) {
int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), value);
handleError(returnCode, ndbOperation);
}
public void setInt(Column storeColumn, Integer value) {
int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), value);
handleError(returnCode, ndbOperation);
}
public void setLong(Column storeColumn, long value) {
long storeValue = Utility.convertLongValueForStorage(storeColumn, value);
int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), storeValue);
handleError(returnCode, ndbOperation);
}
public void setNull(Column storeColumn) {
int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), null);
handleError(returnCode, ndbOperation);
}
public void setShort(Column storeColumn, Short value) {
int storeValue = Utility.convertShortValueForStorage(storeColumn, value);
int returnCode = ndbOperation.setValue(storeColumn.getName(), storeValue);
handleError(returnCode, ndbOperation);
}
public void setString(Column storeColumn, String value) {
ByteBuffer stringStorageBuffer = Utility.encode(value, storeColumn, bufferManager);
int length = stringStorageBuffer.remaining() - storeColumn.getPrefixLength();
if (length > storeColumn.getLength()) {
throw new ClusterJUserException(local.message("ERR_Data_Too_Long",
storeColumn.getName(), storeColumn.getLength(), length));
}
int returnCode = ndbOperation.setValue(storeColumn.getColumnId(), stringStorageBuffer);
bufferManager.clearStringStorageBuffer();
handleError(returnCode, ndbOperation);
}
public int errorCode() {
return ndbOperation.getNdbError().code();
}
protected void handleError(int returnCode, NdbOperation ndbOperation) {
if (returnCode == 0) {
return;
} else {
Utility.throwError(returnCode, ndbOperation.getNdbError());
}
}
protected static void handleError(Object object, NdbOperation ndbOperation) {
if (object != null) {
return;
} else {
Utility.throwError(null, ndbOperation.getNdbError());
}
}
public void beginDefinition() {
// nothing to do
}
public void endDefinition() {
// nothing to do
}
public int getErrorCode() {
return ndbOperation.getNdbError().code();
}
public int getClassification() {
return ndbOperation.getNdbError().classification();
}
public int getMysqlCode() {
return ndbOperation.getNdbError().myblockchain_code();
}
public int getStatus() {
return ndbOperation.getNdbError().status();
}
public void freeResourcesAfterExecute() {
}
}
| MrDunne/myblockchain | storage/ndb/clusterj/clusterj-tie/src/main/java/com/mysql/clusterj/tie/OperationImpl.java | Java | gpl-2.0 | 13,552 |
package mica
import "fmt"
// LinkToCompressed represents a link from a reference sequence to a
// compressed original sequence. It serves as a bridge from a BLAST hit in
// the coarse database to the corresponding original sequence that is
// redundant to the specified residue range in the reference sequence.
type LinkToCompressed struct {
OrgSeqId uint32
CoarseStart, CoarseEnd uint16
Next *LinkToCompressed
}
func NewLinkToCompressed(
orgSeqId uint32, coarseStart, coarseEnd uint16) *LinkToCompressed {
return &LinkToCompressed{
OrgSeqId: orgSeqId,
CoarseStart: coarseStart,
CoarseEnd: coarseEnd,
Next: nil,
}
}
func (lk LinkToCompressed) String() string {
return fmt.Sprintf("original sequence id: %d, coarse range: (%d, %d)",
lk.OrgSeqId, lk.CoarseStart, lk.CoarseEnd)
}
| jameslz/MICA | link_to_compressed.go | GO | gpl-2.0 | 843 |
// renderimpl.cpp
// this file is part of Context Free
// ---------------------
// Copyright (C) 2006-2008 Mark Lentczner - markl@glyphic.com
// Copyright (C) 2006-2014 John Horigan - john@glyphic.com
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// John Horigan can be contacted at john@glyphic.com or at
// John Horigan, 1209 Villa St., Mountain View, CA 94041-1123, USA
//
// Mark Lentczner can be contacted at markl@glyphic.com or at
// Mark Lentczner, 1209 Villa St., Mountain View, CA 94041-1123, USA
//
//
#include "renderimpl.h"
#include <iterator>
#include <string>
#include <algorithm>
#include <stack>
#include <cassert>
#include <functional>
#ifdef _WIN32
#include <float.h>
#include <math.h>
#define isfinite _finite
#else
#include <math.h>
#endif
#include "shapeSTL.h"
#include "primShape.h"
#include "builder.h"
#include "astreplacement.h"
#include "CmdInfo.h"
#include "tiledCanvas.h"
using namespace std;
using namespace AST;
//#define DEBUG_SIZES
unsigned int RendererImpl::MoveFinishedAt = 0; // when this many, move to file
unsigned int RendererImpl::MoveUnfinishedAt = 0; // when this many, move to files
unsigned int RendererImpl::MaxMergeFiles = 0; // maximum number of files to merge at once
const double SHAPE_BORDER = 1.0; // multiplier of shape size when calculating bounding box
const double FIXED_BORDER = 8.0; // fixed extra border, in pixels
RendererImpl::RendererImpl(CFDGImpl* cfdg,
int width, int height, double minSize,
int variation, double border)
: RendererAST(width, height), m_cfdg(cfdg), m_canvas(nullptr), mColorConflict(false),
m_maxShapes(500000000), mVariation(variation), m_border(border),
mScaleArea(0.0), mScale(0.0), m_currScale(0.0), m_currArea(0.0),
m_minSize(minSize), mFrameTimeBounds(1.0, -Renderer::Infinity, Renderer::Infinity),
circleCopy(primShape::circle), squareCopy(primShape::square), triangleCopy(primShape::triangle),
shapeMap{}
{
if (MoveFinishedAt == 0) {
#ifndef DEBUG_SIZES
size_t mem = m_cfdg->system()->getPhysicalMemory();
if (mem == 0) {
MoveFinishedAt = MoveUnfinishedAt = 2000000;
} else {
MoveFinishedAt = MoveUnfinishedAt = static_cast<unsigned int>(mem / (sizeof(FinishedShape) * 4));
}
MaxMergeFiles = 200; // maximum number of files to merge at once
#else
MoveFinishedAt = 1000; // when this many, move to file
MoveUnfinishedAt = 200; // when this many, move to files
MaxMergeFiles = 4; // maximum number of files to merge at once
#endif
}
mCFstack.reserve(8000);
shapeMap = { { CommandInfo(&circleCopy), CommandInfo(&squareCopy), CommandInfo(&triangleCopy)} };
m_cfdg->hasParameter(CFG::FrameTime, mCurrentTime, nullptr);
m_cfdg->hasParameter(CFG::Frame, mCurrentFrame, nullptr);
}
void
RendererImpl::colorConflict(const yy::location& w)
{
if (mColorConflict) return;
CfdgError err(w, "Conflicting color change");
system()->syntaxError(err);
mColorConflict = true;
}
void
RendererImpl::init()
{
// Performs RendererImpl initializations that are needed before rendering
// and before each frame of an animation
mCurrentSeed.seed(static_cast<unsigned long long>(mVariation));
mCurrentSeed();
Shape dummy;
for (const rep_ptr& rep: m_cfdg->mCFDGcontents.mBody) {
if (const ASTdefine* def = dynamic_cast<const ASTdefine*> (rep.get()))
def->traverse(dummy, false, this);
}
mFinishedFileCount = 0;
mUnfinishedFileCount = 0;
mFixedBorderX = mFixedBorderY = 0.0;
mShapeBorder = 1.0;
mTotalArea = 0.0;
m_minArea = 0.3;
m_outputSoFar = m_stats.shapeCount = m_stats.toDoCount = 0;
double minSize = m_minSize;
m_cfdg->hasParameter(CFG::MinimumSize, minSize, this);
minSize = (minSize <= 0.0) ? 0.3 : minSize;
m_minArea = minSize * minSize;
mFixedBorderX = FIXED_BORDER * ((m_border <= 1.0) ? m_border : 1.0);
mShapeBorder = SHAPE_BORDER * ((m_border <= 1.0) ? 1.0 : m_border);
m_cfdg->hasParameter(CFG::BorderFixed, mFixedBorderX, this);
m_cfdg->hasParameter(CFG::BorderDynamic, mShapeBorder, this);
if (2 * static_cast<int>(fabs(mFixedBorderX)) >= min(m_width, m_height))
mFixedBorderX = 0.0;
if (mShapeBorder <= 0.0)
mShapeBorder = 1.0;
if (m_cfdg->hasParameter(CFG::MaxNatural, mMaxNatural, this) &&
(mMaxNatural < 1.0 || (mMaxNatural - 1.0) == mMaxNatural))
{
const ASTexpression* max = m_cfdg->hasParameter(CFG::MaxNatural);
throw CfdgError(max->where, (mMaxNatural < 1.0) ?
"CF::MaxNatural must be >= 1" :
"CF::MaxNatural must be < 9007199254740992");
}
mCurrentPath.reset(new AST::ASTcompiledPath());
m_cfdg->getSymmetry(mSymmetryOps, this);
m_cfdg->setBackgroundColor(this);
}
void
RendererImpl::initBounds()
{
init();
double tile_x, tile_y;
m_tiled = m_cfdg->isTiled(nullptr, &tile_x, &tile_y);
m_frieze = m_cfdg->isFrieze(nullptr, &tile_x, &tile_y);
m_sized = m_cfdg->isSized(&tile_x, &tile_y);
m_timed = m_cfdg->isTimed(&mTimeBounds);
if (m_tiled || m_sized) {
mFixedBorderX = mShapeBorder = 0.0;
mBounds.mMin_X = -(mBounds.mMax_X = tile_x / 2.0);
mBounds.mMin_Y = -(mBounds.mMax_Y = tile_y / 2.0);
rescaleOutput(m_width, m_height, true);
mScaleArea = m_currArea;
}
if (m_frieze == CFDG::frieze_x)
m_frieze_size = tile_x / 2.0;
if (m_frieze == CFDG::frieze_y)
m_frieze_size = tile_y / 2.0;
if (m_frieze != CFDG::frieze_y)
mFixedBorderY = mFixedBorderX;
if (m_frieze == CFDG::frieze_x)
mFixedBorderX = 0.0;
}
void
RendererImpl::resetSize(int x, int y)
{
m_width = x;
m_height = y;
if (m_tiled || m_sized) {
m_currScale = m_currArea = 0.0;
rescaleOutput(m_width, m_height, true);
mScaleArea = m_currArea;
}
}
RendererImpl::~RendererImpl()
{
cleanup();
if (AbortEverything)
return;
#ifdef EXTREME_PARAM_DEBUG
AbstractSystem* sys = system();
for (auto &p: StackRule::ParamMap) {
if (p.second > 0)
sys->message("Parameter at %p is still alive, it is param number %d\n", p.first, p.second);
}
#endif
}
class Stopped { };
void
RendererImpl::cleanup()
{
// delete temp files before checking for abort
m_finishedFiles.clear();
m_unfinishedFiles.clear();
try {
std::function <void (const Shape& s)> releaseParam([](const Shape& s) {
if (Renderer::AbortEverything)
throw Stopped();
s.releaseParams();
});
for_each(mUnfinishedShapes.begin(), mUnfinishedShapes.end(), releaseParam);
for_each(mFinishedShapes.begin(), mFinishedShapes.end(), releaseParam);
} catch (Stopped&) {
return;
} catch (exception& e) {
system()->catastrophicError(e.what());
return;
}
mUnfinishedShapes.clear();
mFinishedShapes.clear();
unwindStack(0, m_cfdg->mCFDGcontents.mParameters);
mCurrentPath.reset();
m_cfdg->resetCachedPaths();
}
void
RendererImpl::setMaxShapes(int n)
{
m_maxShapes = n ? n : 400000000;
}
void
RendererImpl::resetBounds()
{
mBounds = Bounds();
}
void
RendererImpl::outputPrep(Canvas* canvas)
{
m_canvas = canvas;
if (canvas) {
m_width = canvas->mWidth;
m_height = canvas->mHeight;
if (m_tiled || m_frieze) {
agg::trans_affine tr;
m_cfdg->isTiled(&tr);
m_cfdg->isFrieze(&tr);
m_tiledCanvas.reset(new tiledCanvas(canvas, tr, m_frieze));
m_tiledCanvas->scale(m_currScale);
m_canvas = m_tiledCanvas.get();
}
mFrameTimeBounds.load_from(1.0, -Renderer::Infinity, Renderer::Infinity);
}
requestStop = false;
requestFinishUp = false;
requestUpdate = false;
m_stats.inOutput = false;
m_stats.animating = false;
m_stats.finalOutput = false;
}
double
RendererImpl::run(Canvas * canvas, bool partialDraw)
{
if (!m_stats.animating)
outputPrep(canvas);
int reportAt = 250;
Shape initShape = m_cfdg->getInitialShape(this);
initShape.mWorldState.mRand64Seed = mCurrentSeed;
if (!m_timed)
mTimeBounds = initShape.mWorldState.m_time;
try {
processShape(initShape);
} catch (CfdgError& e) {
requestStop = true;
system()->syntaxError(e);
} catch (exception& e) {
requestStop = true;
system()->catastrophicError(e.what());
}
for (;;) {
fileIfNecessary();
if (requestStop) break;
if (requestFinishUp) break;
if (mUnfinishedShapes.empty()) break;
if ((m_stats.shapeCount + m_stats.toDoCount) > m_maxShapes)
break;
// Get the largest unfinished shape
Shape s = mUnfinishedShapes.front();
pop_heap(mUnfinishedShapes.begin(), mUnfinishedShapes.end());
mUnfinishedShapes.pop_back();
m_stats.toDoCount--;
try {
const ASTrule* rule = m_cfdg->findRule(s.mShapeType, s.mWorldState.mRand64Seed.getDouble());
m_drawingMode = false; // shouldn't matter
rule->traverse(s, false, this);
} catch (CfdgError& e) {
requestStop = true;
system()->syntaxError(e);
break;
} catch (exception& e) {
requestStop = true;
system()->catastrophicError(e.what());
break;
}
if (requestUpdate || (m_stats.shapeCount > reportAt)) {
if (partialDraw)
outputPartial();
outputStats();
reportAt = 2 * m_stats.shapeCount;
}
}
if (!m_cfdg->usesTime && !m_timed)
mTimeBounds.load_from(1.0, 0.0, mTotalArea);
if (!requestStop) {
outputFinal();
}
if (!requestStop) {
outputStats();
if (m_canvas)
system()->message("Done.");
}
if (!m_canvas && m_frieze)
rescaleOutput(m_width, m_height, true);
return m_currScale;
}
void
RendererImpl::draw(Canvas* canvas)
{
mFrameTimeBounds.load_from(1.0, -Renderer::Infinity, Renderer::Infinity);
outputPrep(canvas);
outputFinal();
outputStats();
}
class OutputBounds
{
public:
OutputBounds(int frames, const agg::trans_affine_time& timeBounds,
int width, int height, RendererImpl& renderer);
void apply(const FinishedShape&);
const Bounds& frameBounds(int frame) { return mFrameBounds[frame]; }
int frameCount(int frame) { return mFrameCounts[frame]; }
void finalAccumulate();
// call after all the frames to compute the bounds at each frame
void backwardFilter(double framesToHalf);
void smooth(int window);
private:
agg::trans_affine_time mTimeBounds;
double mFrameScale;
vector<Bounds> mFrameBounds;
vector<int> mFrameCounts;
double mScale;
int mWidth;
int mHeight;
int mFrames;
RendererImpl& mRenderer;
OutputBounds& operator=(const OutputBounds&); // not defined
};
OutputBounds::OutputBounds(int frames, const agg::trans_affine_time& timeBounds,
int width, int height, RendererImpl& renderer)
: mTimeBounds(timeBounds), mScale(0.0),
mWidth(width), mHeight(height), mFrames(frames), mRenderer(renderer)
{
mFrameScale = static_cast<double>(frames) / (timeBounds.tend - timeBounds.tbegin);
mFrameBounds.resize(frames);
mFrameCounts.resize(frames, 0);
}
void
OutputBounds::apply(const FinishedShape& s)
{
if (mRenderer.requestStop || mRenderer.requestFinishUp) throw Stopped();
if (mScale == 0.0) {
// If we don't know the approximate scale yet then just
// make an educated guess.
mScale = (mWidth + mHeight) / sqrt(fabs(s.mWorldState.m_transform.determinant()));
}
agg::trans_affine_time frameTime(s.mWorldState.m_time);
frameTime.translate(-mTimeBounds.tbegin);
frameTime.scale(mFrameScale);
int begin = (frameTime.tbegin < mFrames) ? static_cast<int>(floor(frameTime.tbegin)) : (mFrames - 1);
int end = (frameTime.tend < mFrames) ? static_cast<int>(floor(frameTime.tend)) : (mFrames - 1);
if (begin < 0) begin = 0;
if (end < 0) end = 0;
for (int frame = begin; frame <= end; ++frame) {
mFrameBounds[frame] += s.mBounds;
}
mFrameCounts[begin] += 1;
}
void
OutputBounds::finalAccumulate()
{
return;
// Accumulation is done in the apply method
#if 0
vector<Bounds>::iterator prev, curr, end;
prev = mFrameBounds.begin();
end = mFrameBounds.end();
if (prev == end) return;
for (curr = prev + 1; curr != end; prev = curr, ++curr) {
*curr += *prev;
}
#endif
}
void
OutputBounds::backwardFilter(double framesToHalf)
{
double alpha = pow(0.5, 1.0 / framesToHalf);
vector<Bounds>::reverse_iterator prev, curr, end;
prev = mFrameBounds.rbegin();
end = mFrameBounds.rend();
if (prev == end) return;
for (curr = prev + 1; curr != end; prev = curr, ++curr) {
*curr = curr->interpolate(*prev, alpha);
}
}
void
OutputBounds::smooth(int window)
{
size_t frames = mFrameBounds.size();
if (frames == 0) return;
mFrameBounds.resize(frames + window - 1, mFrameBounds.back());
vector<Bounds>::iterator write, read, end;
read = mFrameBounds.begin();
double factor = 1.0 / window;
Bounds accum;
for (int i = 0; i < window; ++i)
accum.gather(*read++, factor);
write = mFrameBounds.begin();
end = mFrameBounds.end();
for (;;) {
Bounds old = *write;
*write++ = accum;
accum.gather(old, -factor);
if (read == end) break;
accum.gather(*read++, factor);
}
mFrameBounds.resize(frames);
}
void
RendererImpl::animate(Canvas* canvas, int frames, bool zoom)
{
outputPrep(canvas);
const bool ftime = m_cfdg->usesFrameTime;
zoom = zoom && !ftime;
if (ftime)
cleanup();
// start with a blank frame
int curr_width = m_width;
int curr_height = m_height;
rescaleOutput(curr_width, curr_height, true);
m_canvas->start(true, m_cfdg->getBackgroundColor(),
curr_width, curr_height);
m_canvas->end();
double frameInc = (mTimeBounds.tend - mTimeBounds.tbegin) / frames;
OutputBounds outputBounds(frames, mTimeBounds, curr_width, curr_height, *this);
if (zoom) {
system()->message("Computing zoom");
try {
forEachShape(true, [&](const FinishedShape& s) {
outputBounds.apply(s);
});
//outputBounds.finalAccumulate();
outputBounds.backwardFilter(10.0);
//outputBounds.smooth(3);
} catch (Stopped&) {
m_stats.animating = false;
return;
} catch (exception& e) {
system()->catastrophicError(e.what());
return;
}
}
m_stats.shapeCount = 0;
m_stats.animating = true;
mFrameTimeBounds.tend = mTimeBounds.tbegin;
Bounds saveBounds = mBounds;
for (int frameCount = 1; frameCount <= frames; ++frameCount)
{
system()->message("Generating frame %d of %d", frameCount, frames);
if (zoom) mBounds = outputBounds.frameBounds(frameCount - 1);
m_stats.shapeCount += outputBounds.frameCount(frameCount - 1);
mFrameTimeBounds.tbegin = mFrameTimeBounds.tend;
mFrameTimeBounds.tend = mTimeBounds.tbegin + frameInc * frameCount;
if (ftime) {
mCurrentTime = (mFrameTimeBounds.tbegin + mFrameTimeBounds.tend) * 0.5;
mCurrentFrame = (frameCount - 1.0)/(frames - 1.0);
try {
init();
} catch (CfdgError& err) {
system()->syntaxError(err);
cleanup();
mBounds = saveBounds;
m_stats.animating = false;
outputStats();
return;
}
run(canvas, false);
m_canvas = canvas;
} else {
outputFinal();
outputStats();
}
if (ftime)
cleanup();
if (requestStop || requestFinishUp) break;
}
mBounds = saveBounds;
m_stats.animating = false;
outputStats();
system()->message("Animation of %d frames complete", frames);
}
void
RendererImpl::processShape(const Shape& s)
{
double area = s.area();
if (!isfinite(area)) {
requestStop = true;
system()->error();
system()->message("A shape got too big.");
s.releaseParams();
return;
}
if (s.mWorldState.m_time.tbegin > s.mWorldState.m_time.tend) {
s.releaseParams();
return;
}
if (m_cfdg->getShapeType(s.mShapeType) == CFDGImpl::ruleType &&
m_cfdg->shapeHasRules(s.mShapeType))
{
// only add it if it's big enough (or if there are no finished shapes yet)
if (!mBounds.valid() || (area * mScaleArea >= m_minArea)) {
m_stats.toDoCount++;
mUnfinishedShapes.push_back(s);
push_heap(mUnfinishedShapes.begin(), mUnfinishedShapes.end());
} else {
s.releaseParams();
}
} else if (m_cfdg->getShapeType(s.mShapeType) == CFDGImpl::pathType) {
const ASTrule* rule = m_cfdg->findRule(s.mShapeType, 0.0);
processPrimShape(s, rule);
} else if (primShape::isPrimShape(s.mShapeType)) {
processPrimShape(s);
} else {
requestStop = true;
s.releaseParams();
system()->error();
system()->message("Shape with no rules encountered: %s.",
m_cfdg->decodeShapeName(s.mShapeType).c_str());
}
}
void
RendererImpl::processPrimShape(const Shape& s, const ASTrule* path)
{
size_t num = mSymmetryOps.size();
if (num == 0 || s.mShapeType == primShape::fillType) {
processPrimShapeSiblings(s, path);
} else {
for (size_t i = 0; i < num; ++i) {
Shape sym(s);
sym.mWorldState.m_transform.multiply(mSymmetryOps[i]);
processPrimShapeSiblings(sym, path);
}
}
s.releaseParams();
}
void
RendererImpl::processPrimShapeSiblings(const Shape& s, const ASTrule* path)
{
m_stats.shapeCount++;
if (mScale == 0.0) {
// If we don't know the approximate scale yet then just
// make an educated guess.
mScale = (m_width + m_height) / sqrt(fabs(s.mWorldState.m_transform.determinant()));
}
if (path || s.mShapeType != primShape::fillType) {
mCurrentCentroid.x = mCurrentCentroid.y = mCurrentArea = 0.0;
mPathBounds.invalidate();
m_drawingMode = false;
if (path) {
mOpsOnly = false;
path->traversePath(s, this);
} else {
CommandInfo* attr = nullptr;
if (s.mShapeType < 3) attr = &(shapeMap[s.mShapeType]);
processPathCommand(s, attr);
}
mTotalArea += mCurrentArea;
if (!m_tiled && !m_sized) {
mBounds.merge(mPathBounds.dilate(mShapeBorder));
if (m_frieze == CFDG::frieze_x)
mBounds.mMin_X = -(mBounds.mMax_X = m_frieze_size);
if (m_frieze == CFDG::frieze_y)
mBounds.mMin_Y = -(mBounds.mMax_Y = m_frieze_size);
mScale = mBounds.computeScale(m_width, m_height,
mFixedBorderX, mFixedBorderY, false);
mScaleArea = mScale * mScale;
}
} else {
mCurrentArea = 1.0;
}
FinishedShape fs(s, m_stats.shapeCount, mPathBounds);
fs.mWorldState.m_Z.sz = mCurrentArea;
if (!m_cfdg->usesTime) {
fs.mWorldState.m_time.tbegin = mTotalArea;
fs.mWorldState.m_time.tend = Renderer::Infinity;
}
if (fs.mWorldState.m_time.tbegin < mTimeBounds.tbegin &&
isfinite(fs.mWorldState.m_time.tbegin) && !m_timed)
{
mTimeBounds.tbegin = fs.mWorldState.m_time.tbegin;
}
if (fs.mWorldState.m_time.tbegin > mTimeBounds.tend &&
isfinite(fs.mWorldState.m_time.tbegin) && !m_timed)
{
mTimeBounds.tend = fs.mWorldState.m_time.tbegin;
}
if (fs.mWorldState.m_time.tend > mTimeBounds.tend &&
isfinite(fs.mWorldState.m_time.tend) && !m_timed)
{
mTimeBounds.tend = fs.mWorldState.m_time.tend;
}
if (fs.mWorldState.m_time.tend < mTimeBounds.tbegin &&
isfinite(fs.mWorldState.m_time.tend) && !m_timed)
{
mTimeBounds.tbegin = fs.mWorldState.m_time.tend;
}
if (!fs.mWorldState.isFinite()) {
requestStop = true;
system()->error();
system()->message("A shape got too big.");
return;
}
mFinishedShapes.push_back(fs);
if (fs.mParameters)
fs.mParameters->retain(this);
}
void
RendererImpl::processSubpath(const Shape& s, bool tr, int expectedType)
{
const ASTrule* rule = nullptr;
if (m_cfdg->getShapeType(s.mShapeType) != CFDGImpl::pathType &&
primShape::isPrimShape(s.mShapeType) && expectedType == ASTreplacement::op)
{
static const ASTrule PrimitivePaths[primShape::numTypes] = { { 0 }, { 1 }, { 2 }, { 3 } };
rule = &PrimitivePaths[s.mShapeType];
} else {
rule = m_cfdg->findRule(s.mShapeType, 0.0);
}
if (static_cast<int>(rule->mRuleBody.mRepType) != expectedType)
throw CfdgError(rule->mLocation, "Subpath is not of the expected type (path ops/commands)");
bool saveOpsOnly = mOpsOnly;
mOpsOnly = mOpsOnly || (expectedType == ASTreplacement::op);
rule->mRuleBody.traverse(s, tr, this, true);
mOpsOnly = saveOpsOnly;
}
//-------------------------------------------------------------------------////
void
RendererImpl::fileIfNecessary()
{
if (mFinishedShapes.size() > MoveFinishedAt)
moveFinishedToFile();
if (mUnfinishedShapes.size() > MoveUnfinishedAt)
moveUnfinishedToTwoFiles();
else if (mUnfinishedShapes.empty())
getUnfinishedFromFile();
}
void
RendererImpl::moveUnfinishedToTwoFiles()
{
m_unfinishedFiles.emplace_back(system(), AbstractSystem::ExpensionTemp,
"expansion", ++mUnfinishedFileCount);
unique_ptr<ostream> f1(m_unfinishedFiles.back().forWrite());
int num1 = m_unfinishedFiles.back().number();
m_unfinishedFiles.emplace_back(system(), AbstractSystem::ExpensionTemp,
"expansion", ++mUnfinishedFileCount);
unique_ptr<ostream> f2(m_unfinishedFiles.back().forWrite());
int num2 = m_unfinishedFiles.back().number();
system()->message("Writing %s temp files %d & %d",
m_unfinishedFiles.back().type().c_str(), num1, num2);
size_t count = mUnfinishedShapes.size() / 3;
UnfinishedContainer::iterator usi = mUnfinishedShapes.begin(),
use = mUnfinishedShapes.end();
usi += count;
if (f1->good() && f2->good()) {
AbstractSystem::Stats outStats = m_stats;
outStats.outputCount = static_cast<int>(count);
outStats.outputDone = 0;
*f1 << outStats.outputCount;
*f2 << outStats.outputCount;
outStats.outputCount = static_cast<int>(count * 2);
outStats.showProgress = true;
// Split the bottom 2/3 of the heap between the two files
while (usi != use) {
usi->write(*((m_unfinishedInFilesCount & 1) ? f1 : f2));
++usi;
++m_unfinishedInFilesCount;
++outStats.outputDone;
if (requestUpdate) {
system()->stats(outStats);
requestUpdate = false;
}
if (requestStop || requestFinishUp)
return;
}
} else {
system()->message("Cannot open temporary file for expansions");
requestStop = true;
return;
}
// Remove the written shapes, heap property remains intact
static const Shape neverActuallyUsed;
mUnfinishedShapes.resize(count, neverActuallyUsed);
assert(is_heap(mUnfinishedShapes.begin(), mUnfinishedShapes.end()));
}
void
RendererImpl::getUnfinishedFromFile()
{
if (m_unfinishedFiles.empty()) return;
TempFile t(std::move(m_unfinishedFiles.front()));
m_unfinishedFiles.pop_front();
unique_ptr<istream> f(t.forRead());
if (f->good()) {
AbstractSystem::Stats outStats = m_stats;
*f >> outStats.outputCount;
outStats.outputDone = 0;
outStats.showProgress = true;
istream_iterator<Shape> it(*f);
istream_iterator<Shape> eit;
back_insert_iterator< UnfinishedContainer > sendto(mUnfinishedShapes);
while (it != eit) {
*sendto = *it;
++it;
++outStats.outputDone;
if (requestUpdate) {
system()->stats(outStats);
requestUpdate = false;
}
if (requestStop || requestFinishUp)
return;
}
} else {
system()->message("Cannot open temporary file for expansions");
requestStop = true;
return;
}
system()->message("Resorting expansions");
fixupHeap();
}
void
RendererImpl::fixupHeap()
{
// Restore heap property to mUnfinishedShapes
auto first = mUnfinishedShapes.begin();
auto last = mUnfinishedShapes.end();
typedef UnfinishedContainer::iterator::difference_type difference_type;
difference_type n = last - first;
if (n < 2)
return;
AbstractSystem::Stats outStats = m_stats;
outStats.outputCount = static_cast<int>(n);
outStats.outputDone = 0;
outStats.showProgress = true;
last = first;
++last;
for (difference_type i = 1; i < n; ++i) {
push_heap(first, ++last);
++outStats.outputDone;
if (requestUpdate) {
system()->stats(outStats);
requestUpdate = false;
}
if (requestStop || requestFinishUp)
return;
}
assert(is_heap(mUnfinishedShapes.begin(), mUnfinishedShapes.end()));
}
//-------------------------------------------------------------------------////
void
RendererImpl::moveFinishedToFile()
{
m_finishedFiles.emplace_back(system(), AbstractSystem::ShapeTemp, "shapes", ++mFinishedFileCount);
unique_ptr<ostream> f(m_finishedFiles.back().forWrite());
if (f->good()) {
if (mFinishedShapes.size() > 10000)
system()->message("Sorting shapes...");
std::sort(mFinishedShapes.begin(), mFinishedShapes.end());
AbstractSystem::Stats outStats = m_stats;
outStats.outputCount = static_cast<int>(mFinishedShapes.size());
outStats.outputDone = 0;
outStats.showProgress = true;
for (const FinishedShape& fs: mFinishedShapes) {
*f << fs;
++outStats.outputDone;
if (requestUpdate) {
system()->stats(outStats);
requestUpdate = false;
}
if (requestStop)
return;
}
} else {
system()->message("Cannot open temporary file for shapes");
requestStop = true;
return;
}
mFinishedShapes.clear();
}
//-------------------------------------------------------------------------////
void RendererImpl::rescaleOutput(int& curr_width, int& curr_height, bool final)
{
agg::trans_affine trans;
double scale;
if (!mBounds.valid()) return;
scale = mBounds.computeScale(curr_width, curr_height,
mFixedBorderX, mFixedBorderY, true,
&trans, m_tiled || m_sized || m_frieze);
if (final // if final output
|| m_currScale == 0.0 // if first time, use this scale
|| (m_currScale * 0.90) > scale)// if grew by more than 10%
{
m_currScale = scale;
m_currArea = scale * scale;
if (m_tiledCanvas)
m_tiledCanvas->scale(scale);
m_currTrans = trans;
m_outputSoFar = 0;
m_stats.fullOutput = true;
}
}
void
RendererImpl::forEachShape(bool final, ShapeFunction op)
{
if (!final || m_finishedFiles.empty()) {
FinishedContainer::iterator start = mFinishedShapes.begin();
FinishedContainer::iterator last = mFinishedShapes.end();
if (!final)
start += m_outputSoFar;
for_each(start, last, op);
m_outputSoFar = static_cast<int>(mFinishedShapes.size());
} else {
deque<TempFile>::iterator begin, last, end;
while (m_finishedFiles.size() > MaxMergeFiles) {
TempFile t(system(), AbstractSystem::MergeTemp, "merge", ++mFinishedFileCount);
{
OutputMerge merger;
begin = m_finishedFiles.begin();
last = begin + (MaxMergeFiles - 1);
end = last + 1;
for (auto it = begin; it != end; ++it)
merger.addTempFile(*it);
std::unique_ptr<ostream> f(t.forWrite());
system()->message("Merging temp files %d through %d",
begin->number(), last->number());
merger.merge([&](const FinishedShape& s) {
*f << s;
});
} // end scope for merger and f
for (unsigned i = 0; i < MaxMergeFiles; ++i)
m_finishedFiles.pop_front();
m_finishedFiles.push_back(std::move(t));
}
OutputMerge merger;
begin = m_finishedFiles.begin();
end = m_finishedFiles.end();
for (auto it = begin; it != end; ++it)
merger.addTempFile(*it);
merger.addShapes(mFinishedShapes.begin(), mFinishedShapes.end());
merger.merge(op);
}
}
void
RendererImpl::drawShape(const FinishedShape& s)
{
if (requestStop) throw Stopped();
if (!mFinal && requestFinishUp) throw Stopped();
if (requestUpdate)
outputStats();
if (!s.mWorldState.m_time.overlaps(mFrameTimeBounds))
return;
m_stats.outputDone += 1;
agg::trans_affine tr = s.mWorldState.m_transform;
tr *= m_currTrans;
double a = s.mWorldState.m_Z.sz * m_currArea; //fabs(tr.determinant());
if ((!isfinite(a) && s.mShapeType != primShape::fillType) ||
a < m_minArea) return;
if (m_tiledCanvas && s.mShapeType != primShape::fillType) {
Bounds b = s.mBounds;
m_currTrans.transform(&b.mMin_X, &b.mMin_Y);
m_currTrans.transform(&b.mMax_X, &b.mMax_Y);
m_tiledCanvas->tileTransform(b);
}
if (m_cfdg->getShapeType(s.mShapeType) == CFDGImpl::pathType) {
//mRenderer.m_canvas->path(s.mColor, tr, *s.mAttributes);
const ASTrule* rule = m_cfdg->findRule(s.mShapeType, 0.0);
rule->traversePath(s, this);
} else {
RGBA8 color = m_cfdg->getColor(s.mWorldState.m_Color);
switch(s.mShapeType) {
case primShape::circleType:
m_canvas->circle(color, tr);
break;
case primShape::squareType:
m_canvas->square(color, tr);
break;
case primShape::triangleType:
m_canvas->triangle(color, tr);
break;
case primShape::fillType:
m_canvas->fill(color);
break;
default:
system()->error();
system()->message("Non drawable shape with no rules: %s",
m_cfdg->decodeShapeName(s.mShapeType).c_str());
requestStop = true;
throw Stopped();
}
}
}
void RendererImpl::output(bool final)
{
if (!m_canvas)
return;
if (!final && !m_finishedFiles.empty())
return; // don't do updates once we have temp files
m_stats.inOutput = true;
m_stats.fullOutput = final;
m_stats.finalOutput = final;
m_stats.outputCount = m_stats.shapeCount;
mFinal = final;
int curr_width = m_width;
int curr_height = m_height;
rescaleOutput(curr_width, curr_height, final);
m_stats.outputDone = m_outputSoFar;
if (final) {
if (mFinishedShapes.size() > 10000)
system()->message("Sorting shapes...");
std::sort(mFinishedShapes.begin(), mFinishedShapes.end());
}
m_canvas->start(m_outputSoFar == 0, m_cfdg->getBackgroundColor(),
curr_width, curr_height);
m_drawingMode = true;
//OutputDraw draw(*this, final);
try {
forEachShape(final, [=](const FinishedShape& s) {
this->drawShape(s);
});
}
catch (Stopped&) { }
catch (exception& e) {
system()->catastrophicError(e.what());
}
m_canvas->end();
m_stats.inOutput = false;
m_stats.outputTime = m_canvas->mTime;
}
void
RendererImpl::outputStats()
{
system()->stats(m_stats);
requestUpdate = false;
}
void
RendererImpl::processPathCommand(const Shape& s, const AST::CommandInfo* attr)
{
if (m_drawingMode) {
if (m_canvas && attr) {
RGBA8 color = m_cfdg->getColor(s.mWorldState.m_Color);
agg::trans_affine tr = s.mWorldState.m_transform;
tr *= m_currTrans;
m_canvas->path(color, tr, *attr);
}
} else {
if (attr) {
double area = 0.0;
agg::point_d cent(0.0, 0.0);
mPathBounds.update(s.mWorldState.m_transform, m_pathIter, mScale, *attr,
¢, &area);
mCurrentCentroid.x = (mCurrentCentroid.x * mCurrentArea + cent.x * area) /
(mCurrentArea + area);
mCurrentCentroid.y = (mCurrentCentroid.x * mCurrentArea + cent.y * area) /
(mCurrentArea + area);
mCurrentArea = mCurrentArea + area;
}
}
}
void
RendererImpl::storeParams(const StackRule* p)
{
p->mRefCount = StackRule::MaxRefCount;
m_cfdg->mLongLivedParams.push_back(p);
}
| burstas/context-free | src-common/renderimpl.cpp | C++ | gpl-2.0 | 35,325 |
<?php
namespace Syw\Front\ApiBundle\Tests\Controller;
use Syw\Front\MainBundle\Tests\BaseTestCase;
/**
* Class BaseControllerTest
*
* @author Christin Löhner <alex.loehner@linux.com>
*/
abstract class BaseControllerTest extends BaseTestCase
{
/**
* @var EntityManager
*/
public $_em;
protected $client = null;
public function setUp()
{
$kernel = static::createKernel();
$kernel->boot();
$this->_em = $kernel->getContainer()->get('doctrine.orm.entity_manager');
$this->_em->beginTransaction();
$this->client = static::createClient();
}
/**
* Rollback changes.
*/
public function tearDown()
{
$this->_em->rollback();
parent::tearDown();
$this->_em->close();
}
}
| christinloehner/linuxcounter.new | src/Syw/Front/ApiBundle/Tests/Controller/BaseControllerTest.php | PHP | gpl-3.0 | 795 |
/* Copyright (C) 2003-2015 LiveCode Ltd.
This file is part of LiveCode.
LiveCode is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License v3 as published by the Free
Software Foundation.
LiveCode 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 LiveCode. If not see <http://www.gnu.org/licenses/>. */
#include "prefix.h"
#include "globdefs.h"
#include "filedefs.h"
#include "objdefs.h"
#include "parsedef.h"
#include "mcio.h"
#include "util.h"
#include "font.h"
#include "sellst.h"
#include "stack.h"
#include "card.h"
#include "field.h"
#include "scrolbar.h"
#include "mcerror.h"
#include "param.h"
#include "globals.h"
#include "dispatch.h"
#include "mctheme.h"
#include "exec.h"
#include "stackfileformat.h"
real8 MCScrollbar::markpos;
uint2 MCScrollbar::mode = SM_CLEARED;
////////////////////////////////////////////////////////////////////////////////
MCPropertyInfo MCScrollbar::kProperties[] =
{
DEFINE_RW_OBJ_ENUM_PROPERTY(P_STYLE, InterfaceScrollbarStyle, MCScrollbar, Style)
DEFINE_RW_OBJ_PROPERTY(P_THUMB_SIZE, Double, MCScrollbar, ThumbSize)
DEFINE_RW_OBJ_PROPERTY(P_THUMB_POS, Double, MCScrollbar, ThumbPos)
DEFINE_RW_OBJ_PROPERTY(P_LINE_INC, Double, MCScrollbar, LineInc)
DEFINE_RW_OBJ_PROPERTY(P_PAGE_INC, Double, MCScrollbar, PageInc)
DEFINE_RO_OBJ_ENUM_PROPERTY(P_ORIENTATION, InterfaceScrollbarOrientation, MCScrollbar, Orientation)
DEFINE_RW_OBJ_PROPERTY(P_NUMBER_FORMAT, String, MCScrollbar, NumberFormat)
DEFINE_RW_OBJ_PROPERTY(P_START_VALUE, String, MCScrollbar, StartValue)
DEFINE_RW_OBJ_PROPERTY(P_END_VALUE, String, MCScrollbar, EndValue)
DEFINE_RW_OBJ_PROPERTY(P_SHOW_VALUE, Bool, MCScrollbar, ShowValue)
};
MCObjectPropertyTable MCScrollbar::kPropertyTable =
{
&MCControl::kPropertyTable,
sizeof(kProperties) / sizeof(kProperties[0]),
&kProperties[0],
};
////////////////////////////////////////////////////////////////////////////////
MCScrollbar::MCScrollbar()
{
flags |= F_HORIZONTAL | F_TRAVERSAL_ON;
rect.width = rect.height = DEFAULT_SB_WIDTH;
thumbpos = 0.0;
thumbsize = 8192.0;
pageinc = thumbsize;
lineinc = 512.0;
// MW-2013-08-27: [[ UnicodifyScrollbar ]] Initialize the members to kMCEmptyString.
startstring = MCValueRetain(kMCEmptyString);
endstring = MCValueRetain(kMCEmptyString);
startvalue = 0.0;
endvalue = 65535.0;
nffw = 0;
nftrailing = 0;
nfforce = 0;
hover_part = WTHEME_PART_UNDEFINED;
linked_control = NULL;
m_embedded = false;
// MM-2014-07-31: [[ ThreadedRendering ]] Used to ensure the progress bar animate message is only posted from a single thread.
m_animate_posted = false;
}
MCScrollbar::MCScrollbar(const MCScrollbar &sref) : MCControl(sref)
{
thumbpos = sref.thumbpos;
thumbsize = sref.thumbsize;
pageinc = sref.pageinc;
lineinc = sref.lineinc;
// MW-2013-08-27: [[ UnicodifyScrollbar ]] Initialize the members to the other scrollbars values
startstring = MCValueRetain(sref . startstring);
endstring = MCValueRetain(sref . endstring);
startvalue = sref.startvalue;
endvalue = sref.endvalue;
nffw = sref.nffw;
nftrailing = sref.nftrailing;
nfforce = sref.nfforce;
hover_part = WTHEME_PART_UNDEFINED;
linked_control = NULL;
m_embedded = false;
// MM-2014-07-31: [[ ThreadedRendering ]] Used to ensure the progress bar animate message is only posted from a single thread.
m_animate_posted = false;
}
MCScrollbar::~MCScrollbar()
{
if (linked_control != NULL)
linked_control -> unlink(this);
// MW-2013-08-27: [[ UnicodifyScrollbar ]] Release the string members.
MCValueRelease(startstring);
MCValueRelease(endstring);
}
Chunk_term MCScrollbar::gettype() const
{
return CT_SCROLLBAR;
}
const char *MCScrollbar::gettypestring()
{
return MCscrollbarstring;
}
void MCScrollbar::open()
{
MCControl::open();
// MW-2011-02-03: [[ Bug 7861 ]] Should make working with large Mac progress bars better.
if (opened == 1 && !getflag(F_SB_STYLE))
{
uint2 oldwidth = MAC_SB_WIDTH;
uint2 newwidth = DEFAULT_SB_WIDTH;
if (IsMacLFAM())
{
oldwidth = DEFAULT_SB_WIDTH;
newwidth = MAC_SB_WIDTH;
}
borderwidth = DEFAULT_BORDER;
if (rect.height == oldwidth)
rect.height = newwidth;
if (rect.width == oldwidth)
rect.width = newwidth;
}
compute_barsize();
}
Boolean MCScrollbar::kdown(MCStringRef p_string, KeySym key)
{
if (!(state & CS_NO_MESSAGES))
if (MCObject::kdown(p_string, key))
return True;
Boolean done = False;
switch (key)
{
case XK_Home:
update(0.0, MCM_scrollbar_line_inc);
done = True;
break;
case XK_End:
update(endvalue, MCM_scrollbar_end);
done = True;
break;
case XK_Right:
case XK_Down:
update(thumbpos + lineinc, MCM_scrollbar_line_inc);
done = True;
break;
case XK_Left:
case XK_Up:
update(thumbpos - lineinc, MCM_scrollbar_line_dec);
done = True;
break;
case XK_Prior:
update(thumbpos - pageinc, MCM_scrollbar_page_dec);
done = True;
break;
case XK_Next:
update(thumbpos + pageinc, MCM_scrollbar_page_inc);
done = True;
break;
default:
break;
}
if (done)
message_with_valueref_args(MCM_mouse_up, MCSTR("1"));
return done;
}
Boolean MCScrollbar::mfocus(int2 x, int2 y)
{
// MW-2007-09-18: [[ Bug 1650 ]] Disabled state linked to thumb size
if (!(flags & F_VISIBLE || showinvisible())
|| (issbdisabled() && getstack()->gettool(this) == T_BROWSE))
return False;
if (state & CS_SCROLL)
{
// I.M. [[bz 9559]] disable scrolling where start value & end value are the same
if (startvalue == endvalue)
return True;
real8 newpos;
double t_thumbsize = thumbsize;
if (t_thumbsize > fabs(endvalue - startvalue))
t_thumbsize = fabs(endvalue - startvalue);
if (flags & F_SCALE)
t_thumbsize = 0;
bool t_forward;
t_forward = (endvalue > startvalue);
MCRectangle t_bar_rect, t_thumb_rect, t_thumb_start_rect, t_thumb_end_rect;
t_bar_rect = compute_bar();
t_thumb_rect = compute_thumb(markpos);
t_thumb_start_rect = compute_thumb(startvalue);
if (t_forward)
t_thumb_end_rect = compute_thumb(endvalue - t_thumbsize);
else
t_thumb_end_rect = compute_thumb(endvalue + t_thumbsize);
int32_t t_bar_start, t_bar_length, t_thumb_start, t_thumb_length;
int32_t t_movement;
if (getstyleint(flags) == F_VERTICAL)
{
t_bar_start = t_thumb_start_rect.y;
t_bar_length = t_thumb_end_rect.y + t_thumb_end_rect.height - t_bar_start;
t_thumb_start = t_thumb_rect.y;
t_thumb_length = t_thumb_rect.height;
t_movement = y - my;
}
else
{
t_bar_start = t_thumb_start_rect.x;
t_bar_length = t_thumb_end_rect.x + t_thumb_end_rect.width - t_bar_start;
t_thumb_start = t_thumb_rect.x;
t_thumb_length = t_thumb_rect.width;
t_movement = x - mx;
}
t_bar_start += t_thumb_length / 2;
t_bar_length -= t_thumb_length;
// AL-2013-07-26: [[ Bug 11044 ]] Prevent divide by zero when computing scrollbar thumbposition
if (t_bar_length == 0)
t_bar_length = 1;
int32_t t_new_position;
t_new_position = t_thumb_start + t_thumb_length / 2 + t_movement;
t_new_position = MCU_min(t_bar_start + t_bar_length, MCU_max(t_bar_start, t_new_position));
if (t_forward)
newpos = startvalue + ((t_new_position - t_bar_start) / (double)t_bar_length) * (fabs(endvalue - startvalue) - t_thumbsize);
else
newpos = startvalue - ((t_new_position - t_bar_start) / (double)t_bar_length) * (fabs(endvalue - startvalue) - t_thumbsize);
update(newpos, MCM_scrollbar_drag);
return True;
}
else if (!MCdispatcher -> isdragtarget() && MCcurtheme && MCcurtheme->getthemepropbool(WTHEME_PROP_SUPPORTHOVERING)
&& MCU_point_in_rect(rect, x, y) )
{
if (!(state & CS_MFOCUSED) && !getstate(CS_SELECTED))
{
MCWidgetInfo winfo;
winfo.type = (Widget_Type)getwidgetthemetype();
if (MCcurtheme->iswidgetsupported(winfo.type))
{
getwidgetthemeinfo(winfo);
Widget_Part wpart = MCcurtheme->hittest(winfo,mx,my,rect);
if (wpart != hover_part)
{
hover_part = wpart;
// MW-2011-08-18: [[ Layers ]] Invalidate the whole object.
redrawall();
}
}
}
}
return MCControl::mfocus(x, y);
}
void MCScrollbar::munfocus()
{
if (MCcurtheme && hover_part != WTHEME_PART_UNDEFINED && MCcurtheme->getthemepropbool(WTHEME_PROP_SUPPORTHOVERING))
{
hover_part = WTHEME_PART_UNDEFINED;
// MW-2011-08-18: [[ Layers ]] Invalidate the whole object.
redrawall();
}
MCControl::munfocus();
}
Boolean MCScrollbar::mdown(uint2 which)
{
if (state & CS_MFOCUSED)
return False;
if (state & CS_MENU_ATTACHED)
return MCObject::mdown(which);
state |= CS_MFOCUSED;
if (!IsMacEmulatedLF() && flags & F_TRAVERSAL_ON && !(state & CS_KFOCUSED))
getstack()->kfocusset(this);
uint2 margin;
MCRectangle brect = compute_bar();
if (flags & F_SCALE)
margin = 0;
else
if (getstyleint(flags) == F_VERTICAL)
margin = brect.width - 1;
else
margin = brect.height - 1;
Tool tool = state & CS_NO_MESSAGES ? T_BROWSE : getstack()->gettool(this);
MCWidgetInfo winfo;
winfo.type = (Widget_Type)getwidgetthemetype();
switch (which)
{
case Button1:
switch (tool)
{
case T_BROWSE:
message_with_valueref_args(MCM_mouse_down, MCSTR("1"));
if (flags & F_PROGRESS) //progress bar does not respond to mouse down event
return False;
if (MCcurtheme && MCcurtheme->iswidgetsupported(winfo.type))
{
getwidgetthemeinfo(winfo);
Widget_Part wpart = MCcurtheme->hittest(winfo,mx,my,rect);
// scrollbar needs to check first if mouse-down occured in arrows
switch (wpart)
{
case WTHEME_PART_ARROW_DEC:
if (MCmodifierstate & MS_SHIFT)
mode = SM_BEGINNING;
else
mode = SM_LINEDEC;
break;
case WTHEME_PART_ARROW_INC:
if (MCmodifierstate & MS_SHIFT)
mode = SM_END;
else
mode = SM_LINEINC;
break;
case WTHEME_PART_TRACK_DEC:
mode = SM_PAGEDEC;
break;
case WTHEME_PART_TRACK_INC:
mode = SM_PAGEINC;
break;
}
}
else
{ //Non-theme appearence stuff: for vertical scrollbar or scale
if (getstyleint(flags) == F_VERTICAL)
{
uint2 height;
if (brect.height <= margin << 1)
height = 1;
else
height = brect.height - (margin << 1);
markpos = (my - (brect.y + margin))
* fabs(endvalue - startvalue) / height;
if (my < brect.y + margin)
if (MCmodifierstate & MS_SHIFT)
mode = SM_BEGINNING;
else
mode = SM_LINEDEC;
else
if (my > brect.y + brect.height - margin)
if (MCmodifierstate & MS_SHIFT)
mode = SM_END;
else
mode = SM_LINEINC;
else
{
MCRectangle thumb = compute_thumb(thumbpos);
if (my < thumb.y)
mode = SM_PAGEDEC;
else
if (my > thumb.y + thumb.height)
mode = SM_PAGEINC;
}
}
else
{ //for Horizontal scrollbar or scale
uint2 width;
if (brect.width <= (margin << 1))
width = 1;
else
width = brect.width - (margin << 1);
markpos = (mx - (brect.x + margin))
* fabs(endvalue - startvalue) / width;
if (mx < brect.x + margin)
if (MCmodifierstate & MS_SHIFT)
mode = SM_BEGINNING;
else
mode = SM_LINEDEC;
else
if (mx > brect.x + brect.width - margin)
if (MCmodifierstate & MS_SHIFT)
mode = SM_END;
else
mode = SM_LINEINC;
else
{
MCRectangle thumb = compute_thumb(thumbpos);
if (mx < thumb.x)
mode = SM_PAGEDEC;
else
if (mx > thumb.x + thumb.width)
mode = SM_PAGEINC;
}
}
} //end of Non-MAC-Appearance Manager stuff
switch (mode)
{
case SM_BEGINNING:
update(0, MCM_scrollbar_beginning);
break;
case SM_END:
update(endvalue, MCM_scrollbar_end);
break;
case SM_LINEDEC:
case SM_LINEINC:
timer(MCM_internal, NULL);
redrawarrow(mode);
break;
case SM_PAGEDEC:
case SM_PAGEINC:
timer(MCM_internal, NULL);
break;
default:
state |= CS_SCROLL;
markpos = thumbpos;
if (IsMacEmulatedLF())
movethumb(thumbpos--);
else if (MCcurtheme)
{
// MW-2011-08-18: [[ Layers ]] Invalidate the whole object.
redrawall();
}
}
break;
case T_POINTER:
case T_SCROLLBAR:
start(True);
break;
case T_HELP:
break;
default:
return False;
}
break;
case Button2:
if (message_with_valueref_args(MCM_mouse_down, MCSTR("2")) == ES_NORMAL)
return True;
state |= CS_SCROLL;
{
real8 newpos;
real8 range = endvalue - startvalue;
real8 offset = startvalue;
if (flags & F_SCALE)
margin = MOTIF_SCALE_THUMB_SIZE >> 1;
else
if (MCproportionalthumbs)
if (startvalue > endvalue)
offset += thumbsize / 2.0;
else
offset -= thumbsize / 2.0;
else
margin = FIXED_THUMB_SIZE >> 1;
if (getstyleint(flags) == F_VERTICAL)
newpos = (my - brect.y - margin) * range
/ (brect.height - (margin << 1)) + offset;
else
newpos = (mx - brect.x - margin) * range
/ (brect.width - (margin << 1)) + offset;
update(newpos, MCM_scrollbar_drag);
markpos = thumbpos;
}
break;
case Button3:
message_with_valueref_args(MCM_mouse_down, MCSTR("3"));
break;
}
return True;
}
Boolean MCScrollbar::mup(uint2 which, bool p_release)
{
if (!(state & CS_MFOCUSED))
return False;
if (state & CS_MENU_ATTACHED)
return MCObject::mup(which, p_release);
state &= ~CS_MFOCUSED;
if (state & CS_GRAB)
{
ungrab(which);
return True;
}
Tool tool = state & CS_NO_MESSAGES ? T_BROWSE : getstack()->gettool(this);
switch (which)
{
case Button1:
switch (tool)
{
case T_BROWSE:
if (state & CS_SCROLL)
{
state &= ~CS_SCROLL;
if (IsMacEmulatedLF())
movethumb(thumbpos--);
else if (MCcurtheme)
{
// MW-2011-08-18: [[ Layers ]] Invalidate the whole object.
redrawall();
}
}
else
{
uint2 oldmode = mode;
mode = SM_CLEARED;
if (MCcurtheme)
{
// MW-2011-08-18: [[ Layers ]] Invalidate the whole object.
redrawall();
}
else if (oldmode == SM_LINEDEC || oldmode == SM_LINEINC)
redrawarrow(oldmode);
}
if (!p_release && MCU_point_in_rect(rect, mx, my))
message_with_valueref_args(MCM_mouse_up, MCSTR("1"));
else
message_with_valueref_args(MCM_mouse_release, MCSTR("1"));
break;
case T_SCROLLBAR:
case T_POINTER:
end(true, p_release);
break;
case T_HELP:
help();
break;
default:
return False;
}
break;
case Button2:
if (state & CS_SCROLL)
{
state &= ~CS_SCROLL;
// MW-2011-08-18: [[ Layers ]] Invalidate the whole object.
redrawall();
}
case Button3:
if (!p_release && MCU_point_in_rect(rect, mx, my))
message_with_args(MCM_mouse_up, which);
else
message_with_args(MCM_mouse_release, which);
break;
}
return True;
}
Boolean MCScrollbar::doubledown(uint2 which)
{
if (which == Button1 && getstack()->gettool(this) == T_BROWSE)
return mdown(which);
return MCControl::doubledown(which);
}
Boolean MCScrollbar::doubleup(uint2 which)
{
if (which == Button1 && getstack()->gettool(this) == T_BROWSE)
return mup(which, false);
return MCControl::doubleup(which);
}
void MCScrollbar::applyrect(const MCRectangle &nrect)
{
rect = nrect;
compute_barsize();
}
void MCScrollbar::timer(MCNameRef mptr, MCParameter *params)
{
if (MCNameIsEqualTo(mptr, MCM_internal, kMCCompareCaseless) ||
MCNameIsEqualTo(mptr, MCM_internal2, kMCCompareCaseless))
{
// MW-2009-06-16: [[ Bug ]] Previously this was only waiting for one
// one event (anyevent == True) this meant that it was possible for
// the critical 'mouseUp' event to be missed and an effectively
// infinite timer loop to be entered if the amount of processing
// inbetween timer invocations was too high. So, instead, we process
// all events at this point to ensure the mouseUp is handled.
// (In the future we should flush mouseUp events to the dispatch queue)
// MW-2014-04-16: [[ Bug 12183 ]] This wait does not seem to make much
// sense. It seems to be so that a mouseUp in a short space of time
// stops the scrollbar from moving. This isn't how things should be I
// don't think - so commenting it out for now.
// MCscreen->wait(MCsyncrate / 1000.0, True, False); // dispatch mup
if (state & CS_MFOCUSED && !MCbuttonstate)
{
mup(Button1, false);
return;
}
if (mode != SM_CLEARED)
{
uint2 delay = MCNameIsEqualTo(mptr, MCM_internal, kMCCompareCaseless) ? MCrepeatdelay : MCrepeatrate;
MCscreen->addtimer(this, MCM_internal2, delay);
MCRectangle thumb;
switch (mode)
{
case SM_LINEDEC:
update(thumbpos - lineinc, MCM_scrollbar_line_dec);
break;
case SM_LINEINC:
update(thumbpos + lineinc, MCM_scrollbar_line_inc);
break;
case SM_PAGEDEC:
if ( flags & F_SCALE )
update(thumbpos - pageinc, MCM_scrollbar_page_dec);
else
{
// TH-2008-01-23. Previously was pageinc - lineinc which appeared to be wrong
update(thumbpos - (pageinc - lineinc), MCM_scrollbar_page_dec);
}
thumb = compute_thumb(thumbpos);
if (getstyleint(flags) == F_VERTICAL)
{
if (thumb.y + thumb.height < my)
mode = SM_CLEARED;
}
else
if (thumb.x + thumb.height < mx)
mode = SM_CLEARED;
break;
case SM_PAGEINC:
if (flags & F_SCALE)
update(thumbpos + pageinc, MCM_scrollbar_page_inc);
else
{
// TH-2008-01-23. Previously was pageinc + lineinc which appeared to be wrong.
update(thumbpos + (pageinc - lineinc), MCM_scrollbar_page_inc);
}
thumb = compute_thumb(thumbpos);
if (getstyleint(flags) == F_VERTICAL)
{
if (thumb.y > my)
mode = SM_CLEARED;
}
else
if (thumb.x > mx)
mode = SM_CLEARED;
break;
}
if (parent->gettype() != CT_CARD)
{
MCControl *cptr = (MCControl *)parent;
cptr->readscrollbars();
}
}
}
else if (MCNameIsEqualTo(mptr, MCM_internal3, kMCCompareCaseless))
{
#ifdef _MAC_DESKTOP
// MW-2012-09-17: [[ Bug 9212 ]] Mac progress bars do not animate.
if (getflag(F_PROGRESS))
{
// MM-2014-07-31: [[ ThreadedRendering ]] Flag that there is no longer a progress bar animation message pending.
m_animate_posted = false;
redrawall();
}
#endif
}
else
MCControl::timer(mptr, params);
}
MCControl *MCScrollbar::clone(Boolean attach, Object_pos p, bool invisible)
{
MCScrollbar *newscrollbar = new MCScrollbar(*this);
if (attach)
newscrollbar->attach(p, invisible);
return newscrollbar;
}
void MCScrollbar::compute_barsize()
{
if (flags & F_SHOW_VALUE && (MClook == LF_MOTIF
|| getstyleint(flags) == F_VERTICAL))
{
if (getstyleint(flags) == F_VERTICAL)
{
uint2 twidth = rect.width != 0 ? rect.width : 1;
barsize = MCU_max(nffw, 1);
// MW-2013-08-27: [[ UnicodifyScrollbar ]] Use MCString primitives.
if (MCStringGetLength(startstring) > barsize)
barsize = MCStringGetLength(startstring);
if (MCStringIsEmpty(endstring))
barsize = MCU_max(barsize, 5);
else
barsize = MCU_max((uindex_t)barsize, MCStringGetLength(endstring));
// MM-2014-04-16: [[ Bug 11964 ]] Pass through the transform of the stack to make sure the measurment is correct for scaled text.
barsize *= MCFontMeasureText(m_font, MCSTR("0"), getstack() -> getdevicetransform());
barsize = twidth - (barsize + barsize * (twidth - barsize) / twidth);
}
else
{
uint2 theight = rect.height;
barsize = theight - gettextheight();
}
}
else
if (getstyleint(flags) == F_VERTICAL)
barsize = rect.width;
else
barsize = rect.height;
}
MCRectangle MCScrollbar::compute_bar()
{
MCRectangle brect = rect;
if (flags & F_SHOW_VALUE && (MClook == LF_MOTIF
|| getstyleint(flags) == F_VERTICAL))
{
if (getstyleint(flags) == F_VERTICAL)
brect.width = barsize;
else
{
brect.y += brect.height - barsize;
brect.height = barsize;
}
}
return brect;
}
MCRectangle MCScrollbar::compute_thumb(real8 pos)
{
MCRectangle thumb;
MCWidgetInfo winfo;
winfo.type = (Widget_Type)getwidgetthemetype();
thumb . width = thumb . height = thumb . x = thumb . y = 0 ; // Initialize the values.
if (MCcurtheme && MCcurtheme->iswidgetsupported(winfo.type))
{
getwidgetthemeinfo(winfo);
winfo.part = WTHEME_PART_THUMB;
((MCWidgetScrollBarInfo*)(winfo.data))->thumbpos = pos;
MCcurtheme->getwidgetrect(winfo,WTHEME_METRIC_PARTSIZE,rect,thumb);
}
else
{
MCRectangle trect = compute_bar();
real8 range = endvalue - startvalue;
if (flags & F_SHOW_BORDER && (MClook == LF_MOTIF || !(flags & F_SCALE)
|| getstyleint(flags) == F_VERTICAL))
{
if (IsMacEmulatedLF())
trect = MCU_reduce_rect(trect, 1);
else
trect = MCU_reduce_rect(trect, borderwidth);
}
if (getstyleint(flags) == F_VERTICAL)
{
if (flags & F_SCALE || (thumbsize != 0 && rect.height > rect.width * 3))
{
thumb.x = trect.x;
thumb.width = trect.width;
if (flags & F_SCALE)
{
real8 height = trect.height - MOTIF_SCALE_THUMB_SIZE;
real8 offset = height * (pos - startvalue);
thumb.y = trect.y;
if (range != 0.0)
thumb.y += (int2)(offset / range);
thumb.height = MOTIF_SCALE_THUMB_SIZE;
}
else
if (MCproportionalthumbs)
{
thumb.y = trect.y + trect.width;
real8 height = trect.height - (trect.width << 1) + 1;
if (range != 0.0 && fabs(endvalue - startvalue) != thumbsize)
{
int2 miny = thumb.y;
real8 offset = height * (pos - startvalue);
thumb.y += (int2)(offset / range);
range = fabs(range);
thumb.height = (uint2)(thumbsize * height / range);
uint2 minsize = IsMacEmulatedLF() ? trect.width : MIN_THUMB_SIZE;
if (thumb.height < minsize)
{
uint2 diff = minsize - thumb.height;
thumb.height = minsize;
thumb.y -= (int2)(diff * (pos + thumbsize - startvalue) / range);
if (thumb.y < miny)
thumb.y = miny;
}
}
else
thumb.height = (int2)height - 1;
}
else
{
real8 height = trect.height - (trect.width << 1) - FIXED_THUMB_SIZE;
real8 offset = height * (pos - startvalue);
if (range < 0)
range += thumbsize;
else
range -= thumbsize;
thumb.y = trect.y + trect.width;
if (range != 0.0)
thumb.y += (int2)(offset / range);
thumb.height = FIXED_THUMB_SIZE;
}
}
else
thumb.height = 0;
}
else
{ // horizontal
if (flags & F_SCALE || (thumbsize != 0 && rect.width > rect.height * 3))
{
thumb.y = trect.y;
thumb.height = trect.height;
if (flags & F_SCALE)
{
switch (MClook)
{
case LF_MOTIF:
thumb.width = MOTIF_SCALE_THUMB_SIZE;
break;
case LF_MAC:
thumb.width = MAC_SCALE_THUMB_SIZE;
thumb.height = 16;
trect.x += 7;
trect.width -= 11;
break;
default:
// Win95's thumb width is computed, varied depends on the height of the rect
// if rect.height < 21, scale down the width by a scale factor
// WIN_SCALE_THUMB_HEIGHT + space + 4(tic mark)
if (trect.height < WIN_SCALE_HEIGHT)
thumb.width = trect.height
* WIN_SCALE_THUMB_WIDTH / WIN_SCALE_HEIGHT;
else
thumb.width = WIN_SCALE_THUMB_WIDTH;
thumb.height = MCU_min(WIN_SCALE_HEIGHT, trect.height) - 6;
}
real8 width = trect.width - thumb.width;
real8 offset = width * (pos - startvalue);
thumb.x = trect.x;
if (range != 0.0)
thumb.x += (int2)(offset / range);
}
else
if (MCproportionalthumbs)
{
thumb.x = trect.x + trect.height;
real8 width = trect.width - (trect.height << 1) + 1;
if (range != 0.0 && fabs(endvalue - startvalue) != thumbsize)
{
int2 minx = thumb.x;
real8 offset = width * (pos - startvalue);
thumb.x += (int2)(offset / range);
range = fabs(range);
thumb.width = (uint2)(thumbsize * width / range);
uint2 minsize = IsMacEmulatedLF() ? trect.height : MIN_THUMB_SIZE;
if (thumb.width < minsize)
{
uint2 diff = minsize - thumb.width;
thumb.width = minsize;
thumb.x -= (int2)(diff * (pos + thumbsize - startvalue) / range);
if (thumb.x < minx)
thumb.x = minx;
}
}
else
thumb.width = (int2)width - 1;
}
else
{
real8 width = trect.width - (trect.height << 1) - FIXED_THUMB_SIZE;
real8 offset = width * (pos - startvalue);
thumb.x = trect.x + trect.height;
if (range < 0)
range += thumbsize;
else
range -= thumbsize;
if (range != 0.0)
thumb.x += (int2)(offset / range);
thumb.width = FIXED_THUMB_SIZE;
}
}
else
thumb.width = 0;
}
}
return thumb;
}
void MCScrollbar::update(real8 newpos, MCNameRef mess)
{
real8 oldpos = thumbpos;
real8 ts = thumbsize;
if (thumbsize > fabs(endvalue - startvalue))
ts = thumbsize = fabs(endvalue - startvalue);
if (flags & F_SB_STYLE)
ts = 0;
if (startvalue < endvalue)
if (newpos < startvalue)
thumbpos = startvalue;
else
if (newpos + ts > endvalue)
thumbpos = endvalue - ts;
else
thumbpos = newpos;
else
if (newpos > startvalue)
thumbpos = startvalue;
else
if (newpos - ts < endvalue)
thumbpos = endvalue + ts;
else
thumbpos = newpos;
if (thumbpos != oldpos)
signallisteners(P_THUMB_POS);
if ((thumbpos != oldpos || mode == SM_LINEDEC || mode == SM_LINEINC)
&& opened && (flags & F_VISIBLE || showinvisible()))
{
if (thumbpos != oldpos)
{
// MW-2011-08-18: [[ Layers ]] Invalidate the whole object.
redrawall();
}
MCAutoStringRef t_data;
MCU_r8tos(thumbpos, nffw, nftrailing, nfforce, &t_data);
switch (message_with_valueref_args(mess, *t_data))
{
case ES_NOT_HANDLED:
case ES_PASS:
if (!MCNameIsEqualTo(mess, MCM_scrollbar_drag, kMCCompareCaseless))
message_with_valueref_args(MCM_scrollbar_drag, *t_data);
default:
break;
}
if (linked_control != NULL)
linked_control -> readscrollbars();
}
}
void MCScrollbar::getthumb(real8 &pos)
{
pos = thumbpos;
}
void MCScrollbar::setthumb(real8 pos, real8 size, real8 linc, real8 ev)
{
thumbpos = pos;
thumbsize = size;
pageinc = size;
lineinc = linc;
endvalue = ev;
// MW-2008-11-02: [[ Bug ]] This method is only used by scrollbars directly
// attached to controls. In this case, they are created from the templateScrollbar
// and this means 'startValue' could be anything - however we need it to be zero
// if we want to avoid strangeness.
startvalue = 0.0;
}
void MCScrollbar::movethumb(real8 pos)
{
if (thumbpos != pos)
{
thumbpos = pos;
// MW-2011-08-18: [[ Layers ]] Invalidate the whole object.
redrawall();
}
}
void MCScrollbar::setborderwidth(uint1 nw)
{
int2 d = nw - borderwidth;
if (rect.width <= rect.height)
{
rect.width += d << 1;
rect.x -= d;
}
else
{
rect.height += d << 1;
rect.y -= d;
}
borderwidth = nw;
}
void MCScrollbar::reset()
{
flags &= ~F_HAS_VALUES;
startvalue = 0.0;
endvalue = 65535.0;
// MW-2013-08-27: [[ UnicodifyScrollbar ]] Reset the string values to the empty string.
MCValueAssign(startstring, kMCEmptyString);
MCValueAssign(endstring, kMCEmptyString);
}
void MCScrollbar::redrawarrow(uint2 oldmode)
{
// MW-2011-08-18: [[ Layers ]] Invalidate the whole object.
redrawall();
}
bool MCScrollbar::issbdisabled(void) const
{
bool ret;
ret = getflag(F_DISABLED) || (MClook != LF_MOTIF && !(flags & F_SB_STYLE) && fabs(endvalue - startvalue) == thumbsize);
return ret;
}
void MCScrollbar::link(MCControl *p_control)
{
linked_control = p_control;
}
// MW-2012-09-20: [[ Bug 10395 ]] This method is invoked rather than layer_redrawall()
// to ensure that in the embedded case, the parent's layer is updated.
void MCScrollbar::redrawall(void)
{
if (!m_embedded)
{
layer_redrawall();
return;
}
((MCControl *)parent) -> layer_redrawrect(getrect());
}
// MW-2012-09-20: [[ Bug 10395 ]] This method marks the control as embedded
// thus causing it to redraw through its parent.
void MCScrollbar::setembedded(void)
{
m_embedded = true;
}
///////////////////////////////////////////////////////////////////////////////
//
// SAVING AND LOADING
//
IO_stat MCScrollbar::extendedsave(MCObjectOutputStream& p_stream, uint4 p_part, uint32_t p_version)
{
return defaultextendedsave(p_stream, p_part, p_version);
}
IO_stat MCScrollbar::extendedload(MCObjectInputStream& p_stream, uint32_t p_version, uint4 p_length)
{
return defaultextendedload(p_stream, p_version, p_length);
}
IO_stat MCScrollbar::save(IO_handle stream, uint4 p_part, bool p_force_ext, uint32_t p_version)
{
IO_stat stat;
if ((stat = IO_write_uint1(OT_SCROLLBAR, stream)) != IO_NORMAL)
return stat;
if ((stat = MCControl::save(stream, p_part, p_force_ext, p_version)) != IO_NORMAL)
return stat;
if (flags & F_SAVE_ATTS)
{
real8 range = endvalue - startvalue;
if (range != 0.0)
range = 65535.0 / range;
uint2 i2 = (uint2)((thumbpos - startvalue) * range);
if ((stat = IO_write_uint2(i2, stream)) != IO_NORMAL)
return stat;
i2 = (uint2)(thumbsize * range);
if ((stat = IO_write_uint2(i2, stream)) != IO_NORMAL)
return stat;
i2 = (uint2)(lineinc * range);
if ((stat = IO_write_uint2(i2, stream)) != IO_NORMAL)
return stat;
i2 = (uint2)(pageinc * range);
if ((stat = IO_write_uint2(i2, stream)) != IO_NORMAL)
return stat;
if (flags & F_HAS_VALUES)
{
// MW-2013-08-27: [[ UnicodifyScrollbar ]] Update to use stringref primitives.
// MW-2013-11-20: [[ UnicodeFileFormat ]] If sfv >= 7000, use unicode.
if ((stat = IO_write_stringref_new(startstring, stream, p_version >= kMCStackFileFormatVersion_7_0)) != IO_NORMAL)
return stat;
// MW-2013-11-20: [[ UnicodeFileFormat ]] If sfv >= 7000, use unicode.
if ((stat = IO_write_stringref_new(endstring, stream, p_version >= kMCStackFileFormatVersion_7_0)) != IO_NORMAL)
return stat;
if ((stat = IO_write_uint2(nffw, stream)) != IO_NORMAL)
return stat;
if ((stat = IO_write_uint2(nftrailing, stream)) != IO_NORMAL)
return stat;
if ((stat = IO_write_uint2(nfforce, stream)) != IO_NORMAL)
return stat;
}
}
return savepropsets(stream, p_version);
}
IO_stat MCScrollbar::load(IO_handle stream, uint32_t version)
{
IO_stat stat;
if ((stat = MCObject::load(stream, version)) != IO_NORMAL)
return checkloadstat(stat);
if (flags & F_SAVE_ATTS)
{
uint2 i2;
if ((stat = IO_read_uint2(&i2, stream)) != IO_NORMAL)
return checkloadstat(stat);
thumbpos = (real8)i2;
if ((stat = IO_read_uint2(&i2, stream)) != IO_NORMAL)
return checkloadstat(stat);
thumbsize = (real8)i2;
if ((stat = IO_read_uint2(&i2, stream)) != IO_NORMAL)
return checkloadstat(stat);
lineinc = (real8)i2;
if ((stat = IO_read_uint2(&i2, stream)) != IO_NORMAL)
return checkloadstat(stat);
pageinc = (real8)i2;
if (flags & F_HAS_VALUES)
{
// MW-2013-08-27: [[ UnicodifyScrollbar ]] Update to use stringref primitives.
// MW-2013-11-20: [[ UnicodeFileFormat ]] If sfv >= 7000, use unicode.
if ((stat = IO_read_stringref_new(startstring, stream, version >= kMCStackFileFormatVersion_7_0)) != IO_NORMAL)
return checkloadstat(stat);
if (!MCStringToDouble(startstring, startvalue))
startvalue = 0.0;
// MW-2013-08-27: [[ UnicodifyScrollbar ]] Update to use stringref primitives.
// MW-2013-11-20: [[ UnicodeFileFormat ]] If sfv >= 7000, use unicode.
if ((stat = IO_read_stringref_new(endstring, stream, version >= kMCStackFileFormatVersion_7_0)) != IO_NORMAL)
return checkloadstat(stat);
if (!MCStringToDouble(endstring, endvalue))
endvalue = 0.0;
real8 range = (endvalue - startvalue) / 65535.0;
thumbpos = thumbpos * range + startvalue;
thumbsize *= range;
lineinc *= range;
pageinc *= range;
if ((stat = IO_read_uint2(&nffw, stream)) != IO_NORMAL)
return checkloadstat(stat);
if ((stat = IO_read_uint2(&nftrailing, stream)) != IO_NORMAL)
return checkloadstat(stat);
if ((stat = IO_read_uint2(&nfforce, stream)) != IO_NORMAL)
return checkloadstat(stat);
}
}
if (version <= kMCStackFileFormatVersion_2_0)
{
if (flags & F_TRAVERSAL_ON)
rect = MCU_reduce_rect(rect, MCfocuswidth);
if (flags & F_SHOW_VALUE && getstyleint(flags) == F_HORIZONTAL)
rect = MCU_reduce_rect(rect, 4);
}
return loadpropsets(stream, version);
}
| PaulMcClernan/livecode | engine/src/scrolbar.cpp | C++ | gpl-3.0 | 33,008 |
using FluentValidation;
using NzbDrone.Core.Annotations;
using NzbDrone.Core.ThingiProvider;
using NzbDrone.Core.Validation;
namespace NzbDrone.Core.ImportLists.StevenLu
{
public class StevenLuSettingsValidator : AbstractValidator<StevenLuSettings>
{
public StevenLuSettingsValidator()
{
RuleFor(c => c.Link).ValidRootUrl();
}
}
public class StevenLuSettings : IProviderConfig
{
private static readonly StevenLuSettingsValidator Validator = new StevenLuSettingsValidator();
public StevenLuSettings()
{
Link = "https://s3.amazonaws.com/popular-movies/movies.json";
}
[FieldDefinition(0, Label = "URL", HelpText = "Don't change this unless you know what you are doing.")]
public string Link { get; set; }
public NzbDroneValidationResult Validate()
{
return new NzbDroneValidationResult(Validator.Validate(this));
}
}
}
| Radarr/Radarr | src/NzbDrone.Core/ImportLists/StevenLu/StevenLuSettings.cs | C# | gpl-3.0 | 981 |
static void Button_tick(Button *self) {
if(self->onTick) self->onTick();
}
void Button::create(Window &parent, unsigned x, unsigned y, unsigned width, unsigned height, const string &text) {
object->widget = gtk_button_new_with_label(text);
widget->parent = &parent;
gtk_widget_set_size_request(object->widget, width, height);
g_signal_connect_swapped(G_OBJECT(object->widget), "clicked", G_CALLBACK(Button_tick), (gpointer)this);
if(parent.window->defaultFont) setFont(*parent.window->defaultFont);
gtk_fixed_put(GTK_FIXED(parent.object->formContainer), object->widget, x, y);
gtk_widget_show(object->widget);
}
| grim210/defimulator | snespurify/phoenix/gtk/button.cpp | C++ | gpl-3.0 | 629 |
<?php
/* Copyright (C) 2001-2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2004-2016 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2005-2009 Regis Houssin <regis.houssin@capnetworks.com>
* Copyright (C) 2013 Antoine Iauch <aiauch@gpcsolutions.fr>
*
* 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/>.
*/
/**
* \file htdocs/compta/stats/cabyuser.php
* \brief Page reporting Salesover by user
*/
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
$socid = GETPOST('socid','int');
// Security check
if ($user->societe_id > 0) $socid = $user->societe_id;
if (! empty($conf->comptabilite->enabled)) $result=restrictedArea($user,'compta','','','resultat');
if (! empty($conf->accounting->enabled)) $result=restrictedArea($user,'accounting','','','comptarapport');
// Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES')
$modecompta = $conf->global->ACCOUNTING_MODE;
if (GETPOST("modecompta")) $modecompta=GETPOST("modecompta");
$sortorder=isset($_GET["sortorder"])?$_GET["sortorder"]:$_POST["sortorder"];
$sortfield=isset($_GET["sortfield"])?$_GET["sortfield"]:$_POST["sortfield"];
if (! $sortorder) $sortorder="asc";
if (! $sortfield) $sortfield="name";
// Date range
$year=GETPOST("year");
$month=GETPOST("month");
$date_startyear = GETPOST("date_startyear");
$date_startmonth = GETPOST("date_startmonth");
$date_startday = GETPOST("date_startday");
$date_endyear = GETPOST("date_endyear");
$date_endmonth = GETPOST("date_endmonth");
$date_endday = GETPOST("date_endday");
if (empty($year))
{
$year_current = strftime("%Y",dol_now());
$month_current = strftime("%m",dol_now());
$year_start = $year_current;
} else {
$year_current = $year;
$month_current = strftime("%m",dol_now());
$year_start = $year;
}
$date_start=dol_mktime(0,0,0,$_REQUEST["date_startmonth"],$_REQUEST["date_startday"],$_REQUEST["date_startyear"]);
$date_end=dol_mktime(23,59,59,$_REQUEST["date_endmonth"],$_REQUEST["date_endday"],$_REQUEST["date_endyear"]);
// Quarter
if (empty($date_start) || empty($date_end)) // We define date_start and date_end
{
$q=GETPOST("q")?GETPOST("q"):0;
if ($q==0)
{
// We define date_start and date_end
$month_start=GETPOST("month")?GETPOST("month"):($conf->global->SOCIETE_FISCAL_MONTH_START?($conf->global->SOCIETE_FISCAL_MONTH_START):1);
$year_end=$year_start;
$month_end=$month_start;
if (! GETPOST("month")) // If month not forced
{
if (! GETPOST('year') && $month_start > $month_current)
{
$year_start--;
$year_end--;
}
$month_end=$month_start-1;
if ($month_end < 1) $month_end=12;
else $year_end++;
}
$date_start=dol_get_first_day($year_start,$month_start,false); $date_end=dol_get_last_day($year_end,$month_end,false);
}
if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); }
if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); }
if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); }
if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); }
}
else
{
// TODO We define q
}
$commonparams=array();
$commonparams['modecompta']=$modecompta;
$commonparams['sortorder'] = $sortorder;
$commonparams['sortfield'] = $sortfield;
$headerparams = array();
$headerparams['date_startyear'] = $date_startyear;
$headerparams['date_startmonth'] = $date_startmonth;
$headerparams['date_startday'] = $date_startday;
$headerparams['date_endyear'] = $date_endyear;
$headerparams['date_endmonth'] = $date_endmonth;
$headerparams['date_endday'] = $date_endday;
$headerparams['q'] = $q;
$tableparams = array();
$tableparams['search_categ'] = $selected_cat;
$tableparams['subcat'] = ($subcat === true)?'yes':'';
// Adding common parameters
$allparams = array_merge($commonparams, $headerparams, $tableparams);
$headerparams = array_merge($commonparams, $headerparams);
$tableparams = array_merge($commonparams, $tableparams);
foreach($allparams as $key => $value) {
$paramslink .= '&' . $key . '=' . $value;
}
/*
* View
*/
llxHeader();
$form=new Form($db);
// Show report header
if ($modecompta=="CREANCES-DETTES") {
$nom=$langs->trans("SalesTurnover").', '.$langs->trans("ByUserAuthorOfInvoice");
$calcmode=$langs->trans("CalcModeDebt");
$calcmode.='<br>('.$langs->trans("SeeReportInInputOutputMode",'<a href="'.$_SERVER["PHP_SELF"].'?year='.$year.'&modecompta=RECETTES-DEPENSES">','</a>').')';
$period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1);
//$periodlink="<a href='".$_SERVER["PHP_SELF"]."?year=".($year-1)."&modecompta=".$modecompta."'>".img_previous()."</a> <a href='".$_SERVER["PHP_SELF"]."?year=".($year+1)."&modecompta=".$modecompta."'>".img_next()."</a>";
$description=$langs->trans("RulesCADue");
if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.= $langs->trans("DepositsAreNotIncluded");
else $description.= $langs->trans("DepositsAreIncluded");
$builddate=time();
//$exportlink=$langs->trans("NotYetAvailable");
} else {
$nom=$langs->trans("SalesTurnover").', '.$langs->trans("ByUserAuthorOfInvoice");
$calcmode=$langs->trans("CalcModeEngagement");
$calcmode.='<br>('.$langs->trans("SeeReportInDueDebtMode",'<a href="'.$_SERVER["PHP_SELF"].'?year='.$year.'&modecompta=CREANCES-DETTES">','</a>').')';
$period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1);
//$periodlink="<a href='".$_SERVER["PHP_SELF"]."?year=".($year-1)."&modecompta=".$modecompta."'>".img_previous()."</a> <a href='".$_SERVER["PHP_SELF"]."?year=".($year+1)."&modecompta=".$modecompta."'>".img_next()."</a>";
$description=$langs->trans("RulesCAIn");
$description.= $langs->trans("DepositsAreIncluded");
$builddate=time();
//$exportlink=$langs->trans("NotYetAvailable");
}
$moreparam=array();
if (! empty($modecompta)) $moreparam['modecompta']=$modecompta;
report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,$moreparam,$calcmode);
if (! empty($conf->accounting->enabled))
{
print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1);
}
// Show array
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
// Extra parameters management
foreach($headerparams as $key => $value)
{
print '<input type="hidden" name="'.$key.'" value="'.$value.'">';
}
$catotal=0;
if ($modecompta == 'CREANCES-DETTES') {
$sql = "SELECT u.rowid as rowid, u.lastname as name, u.firstname as firstname, sum(f.total) as amount, sum(f.total_ttc) as amount_ttc";
$sql.= " FROM ".MAIN_DB_PREFIX."user as u";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.fk_user_author = u.rowid";
$sql.= " WHERE f.fk_statut in (1,2)";
if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
$sql.= " AND f.type IN (0,1,2,5)";
} else {
$sql.= " AND f.type IN (0,1,2,3,5)";
}
if ($date_start && $date_end) {
$sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
}
} else {
/*
* Liste des paiements (les anciens paiements ne sont pas vus par cette requete car, sur les
* vieilles versions, ils n'etaient pas lies via paiement_facture. On les ajoute plus loin)
*/
$sql = "SELECT u.rowid as rowid, u.lastname as name, u.firstname as firstname, sum(pf.amount) as amount_ttc";
$sql.= " FROM ".MAIN_DB_PREFIX."user as u" ;
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.fk_user_author = u.rowid ";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON pf.fk_facture = f.rowid";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement as p ON p.rowid = pf.fk_paiement";
$sql.= " WHERE 1=1";
if ($date_start && $date_end) {
$sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'";
}
}
$sql.= " AND f.entity = ".$conf->entity;
if ($socid) $sql.= " AND f.fk_soc = ".$socid;
$sql .= " GROUP BY u.rowid, u.lastname, u.firstname";
$sql .= " ORDER BY u.rowid";
$result = $db->query($sql);
if ($result) {
$num = $db->num_rows($result);
$i=0;
while ($i < $num) {
$obj = $db->fetch_object($result);
$amount_ht[$obj->rowid] = $obj->amount;
$amount[$obj->rowid] = $obj->amount_ttc;
$name[$obj->rowid] = $obj->name.' '.$obj->firstname;
$catotal_ht+=$obj->amount;
$catotal+=$obj->amount_ttc;
$i++;
}
} else {
dol_print_error($db);
}
// Adding old-version payments, non-bound by "paiement_facture" then without User
if ($modecompta != 'CREANCES-DETTES') {
$sql = "SELECT -1 as rowidx, '' as name, '' as firstname, sum(DISTINCT p.amount) as amount_ttc";
$sql.= " FROM ".MAIN_DB_PREFIX."bank as b";
$sql.= ", ".MAIN_DB_PREFIX."bank_account as ba";
$sql.= ", ".MAIN_DB_PREFIX."paiement as p";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON p.rowid = pf.fk_paiement";
$sql.= " WHERE pf.rowid IS NULL";
$sql.= " AND p.fk_bank = b.rowid";
$sql.= " AND b.fk_account = ba.rowid";
$sql.= " AND ba.entity IN (".getEntity('bank_account').")";
if ($date_start && $date_end) {
$sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'";
}
$sql.= " GROUP BY rowidx, name, firstname";
$sql.= " ORDER BY rowidx";
$result = $db->query($sql);
if ($result) {
$num = $db->num_rows($result);
$i=0;
while ($i < $num) {
$obj = $db->fetch_object($result);
$amount[$obj->rowidx] = $obj->amount_ttc;
$name[$obj->rowidx] = $obj->name.' '.$obj->firstname;
$catotal+=$obj->amount_ttc;
$i++;
}
} else {
dol_print_error($db);
}
}
$morefilter='';
print '<div class="div-table-responsive">';
print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
print "<tr class=\"liste_titre\">";
print_liste_field_titre(
$langs->trans("User"),
$_SERVER["PHP_SELF"],
"name",
"",
$paramslink,
"",
$sortfield,
$sortorder
);
if ($modecompta == 'CREANCES-DETTES') {
print_liste_field_titre(
$langs->trans('AmountHT'),
$_SERVER["PHP_SELF"],
"amount_ht",
"",
$paramslink,
'align="right"',
$sortfield,
$sortorder
);
} else {
print_liste_field_titre('');
}
print_liste_field_titre(
$langs->trans("AmountTTC"),
$_SERVER["PHP_SELF"],
"amount_ttc",
"",
$paramslink,
'align="right"',
$sortfield,
$sortorder
);
print_liste_field_titre(
$langs->trans("Percentage"),
$_SERVER["PHP_SELF"],"amount_ttc",
"",
$paramslink,
'align="right"',
$sortfield,
$sortorder
);
print_liste_field_titre(
$langs->trans("OtherStatistics"),
$_SERVER["PHP_SELF"],
"",
"",
"",
'align="center" width="20%"'
);
print "</tr>\n";
$var=true;
if (count($amount)) {
$arrayforsort=$name;
// We define arrayforsort
if ($sortfield == 'name' && $sortorder == 'asc') {
asort($name);
$arrayforsort=$name;
}
if ($sortfield == 'name' && $sortorder == 'desc') {
arsort($name);
$arrayforsort=$name;
}
if ($sortfield == 'amount_ht' && $sortorder == 'asc') {
asort($amount_ht);
$arrayforsort=$amount_ht;
}
if ($sortfield == 'amount_ht' && $sortorder == 'desc') {
arsort($amount_ht);
$arrayforsort=$amount_ht;
}
if ($sortfield == 'amount_ttc' && $sortorder == 'asc') {
asort($amount);
$arrayforsort=$amount;
}
if ($sortfield == 'amount_ttc' && $sortorder == 'desc') {
arsort($amount);
$arrayforsort=$amount;
}
$i = 0;
foreach($arrayforsort as $key => $value) {
print '<tr class="oddeven">';
// Third party
$fullname=$name[$key];
if ($key >= 0) {
$linkname='<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$key.'">'.img_object($langs->trans("ShowUser"),'user').' '.$fullname.'</a>';
} else {
$linkname=$langs->trans("PaymentsNotLinkedToUser");
}
print "<td>".$linkname."</td>\n";
// Amount w/o VAT
print '<td align="right">';
if ($modecompta != 'CREANCES-DETTES')
{
if ($key > 0) {
print '<a href="'.DOL_URL_ROOT.'/compta/paiement/list.php?userid='.$key.'">';
} else {
print '<a href="'.DOL_URL_ROOT.'/compta/paiement/list.php?userid=-1">';
}
} else {
if ($key > 0) {
print '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?userid='.$key.'">';
} else {
print '<a href="#">';
}
print price($amount_ht[$key]);
}
print '</td>';
// Amount with VAT
print '<td align="right">';
if ($modecompta != 'CREANCES-DETTES') {
if ($key > 0) {
print '<a href="'.DOL_URL_ROOT.'/compta/paiement/list.php?userid='.$key.'">';
} else {
print '<a href="'.DOL_URL_ROOT.'/compta/paiement/list.php?userid=-1">';
}
} else {
if ($key > 0) {
print '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?userid='.$key.'">';
} else {
print '<a href="#">';
}
}
print price($amount[$key]);
print '</td>';
// Percent
print '<td align="right">'.($catotal > 0 ? round(100 * $amount[$key] / $catotal,2).'%' : ' ').'</td>';
// Other stats
print '<td align="center">';
if (! empty($conf->propal->enabled) && $key>0) {
print ' <a href="'.DOL_URL_ROOT.'/comm/propal/stats/index.php?userid='.$key.'">'.img_picto($langs->trans("ProposalStats"),"stats").'</a> ';
}
if (! empty($conf->commande->enabled) && $key>0) {
print ' <a href="'.DOL_URL_ROOT.'/commande/stats/index.php?userid='.$key.'">'.img_picto($langs->trans("OrderStats"),"stats").'</a> ';
}
if (! empty($conf->facture->enabled) && $key>0) {
print ' <a href="'.DOL_URL_ROOT.'/compta/facture/stats/index.php?userid='.$key.'">'.img_picto($langs->trans("InvoiceStats"),"stats").'</a> ';
}
print '</td>';
print "</tr>\n";
$i++;
}
// Total
print '<tr class="liste_total">';
print '<td>'.$langs->trans("Total").'</td>';
if ($modecompta != 'CREANCES-DETTES') {
print '<td colspan="1"></td>';
} else {
print '<td align="right">'.price($catotal_ht).'</td>';
}
print '<td align="right">'.price($catotal).'</td>';
print '<td> </td>';
print '<td> </td>';
print '</tr>';
$db->free($result);
}
print "</table>";
print '</div>';
print '</form>';
llxFooter();
$db->close();
| apachler/dolibarr | htdocs/compta/stats/cabyuser.php | PHP | gpl-3.0 | 15,636 |
package utils
import (
"os"
"path/filepath"
"github.com/securityfirst/tent/component"
)
func WriteCmp(base string, c component.Component) error {
path := filepath.Join(base, c.Path())
if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil {
return err
}
f, err := os.Create(path)
if err != nil {
return err
}
if _, err := f.WriteString(c.Contents()); err != nil {
return err
}
return nil
}
| securityfirst/tent | utils/persistence.go | GO | gpl-3.0 | 416 |
System.register(['angular2/core'], function(exports_1) {
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1;
var MyComponent;
return {
setters:[
function (core_1_1) {
core_1 = core_1_1;
}],
execute: function() {
MyComponent = (function () {
function MyComponent() {
}
MyComponent = __decorate([
core_1.Component({ selector: 'my-component', template: '<h1>My Component</h1>' }),
__metadata('design:paramtypes', [])
], MyComponent);
return MyComponent;
})();
exports_1("MyComponent", MyComponent);
}
}
});
//# sourceMappingURL=my_component.js.map | burner/AngularVibed | Examples2/Example05/node_modules/angular2/ts/examples/core/ts/prod_mode/my_component.js | JavaScript | gpl-3.0 | 1,526 |
<?php
// This is a SPIP language file -- Ceci est un fichier langue de SPIP
// extrait automatiquement de http://trad.spip.net/tradlang_module/forum?lang_cible=id
// ** ne pas modifier le fichier **
if (!defined('_ECRIRE_INC_VERSION')) {
return;
}
$GLOBALS[$GLOBALS['idx_lang']] = array(
// B
'bouton_radio_articles_futurs' => 'untuk artikel yang akan dipublikasikan di masa depan saja (tidak ada aksi di database).',
'bouton_radio_articles_tous' => 'untuk semua artikel tanpa pengecualian.',
'bouton_radio_articles_tous_sauf_forum_desactive' => 'untuk semua artikel, terkecuali artikel yang forumnya dinonaktifkan.',
'bouton_radio_enregistrement_obligatoire' => 'Registrasi diperlukan (pengguna harus mendaftarkan diri dengan memberikan alamat e-mailnya sebelum dapat berkontribusi).',
'bouton_radio_moderation_priori' => 'Moderasi awal (
kontribusi hanya akan ditampilkan setelah validasi
oleh administrator).', # MODIF
'bouton_radio_modere_abonnement' => 'registrasi diperlukan',
'bouton_radio_modere_posteriori' => 'moderasi akhir', # MODIF
'bouton_radio_modere_priori' => 'moderasi awal', # MODIF
'bouton_radio_publication_immediate' => 'Publikasi pesan segera
(kontribusi akan ditampilkan sesegera mungkin setelah dikirimkan, kemudian
administrator dapat menghapusnya).',
// F
'form_pet_message_commentaire' => 'Ada pesan atau komentar?',
'forum' => 'Forum',
'forum_acces_refuse' => 'Anda tidak memiliki akses ke forum ini lagi.',
'forum_attention_dix_caracteres' => '<b>Peringatan!</b> Pesan anda hendaknya terdiri dari sepuluh karakter atau lebih.',
'forum_attention_trois_caracteres' => '<b>Peringatan!</b> Judul anda hendaknya terdiri dari tiga karakter atau lebih.',
'forum_attention_trop_caracteres' => '<b>Peringatan !</b> pesan anda terlalu panjang (@compte@ karakter) : untuk dapat menyimpannya, pesan tidak boleh lebih dari @max@ karakter.', # MODIF
'forum_avez_selectionne' => 'Anda telah memilih:',
'forum_cliquer_retour' => 'Klik <a href=\'@retour_forum@\'>di sini</a> untuk lanjut.',
'forum_forum' => 'forum',
'forum_info_modere' => 'Forum ini telah dimoderasi: kontribusi anda hanya akan muncul setelah divalidasi oleh administrator situs.', # MODIF
'forum_lien_hyper' => '<b>Tautan web</b> (opsional)', # MODIF
'forum_message_definitif' => 'Pesan akhir: kirim ke situs',
'forum_message_trop_long' => 'Pesan anda terlalu panjang. Panjang maksimum adalah 20000 karakter.', # MODIF
'forum_ne_repondez_pas' => 'Jangan balas ke e-mail ini tapi ke forum yang terdapat di alamat berikut:', # MODIF
'forum_page_url' => '(Jika pesan anda merujuk pada sebuah artikel yang dipublikasi di web atau halaman yang memberikan informasi lebih lanjut, silakan masukkan judul halaman dan URL-nya di bawah).',
'forum_poste_par' => 'Pesan dikirim@parauteur@ mengikuti artikel anda.', # MODIF
'forum_qui_etes_vous' => '<b>Siapa anda?</b> (opsional)', # MODIF
'forum_texte' => 'Teks pesan anda:', # MODIF
'forum_titre' => 'Subyek:', # MODIF
'forum_url' => 'URL:', # MODIF
'forum_valider' => 'Validasi pilihan ini',
'forum_voir_avant' => 'Lihat pesan sebelum dikirim', # MODIF
'forum_votre_email' => 'Alamat e-mail anda:', # MODIF
'forum_votre_nom' => 'Nama anda (atau alias):', # MODIF
'forum_vous_enregistrer' => 'Sebelum berpartisipasi di
forum ini, anda harus mendaftarkan diri. Terima kasih
telah memasukkan pengidentifikasi pribadi yang
diberikan pada anda. Jika anda belum terdaftar, anda harus',
'forum_vous_inscrire' => 'mendaftarkan diri.',
// I
'icone_poster_message' => 'Kirim sebuah pesan',
'icone_suivi_forum' => 'Tindak lanjut dari forum umum: @nb_forums@ kontribusi',
'icone_suivi_forums' => 'Kelola forum',
'icone_supprimer_message' => 'Hapus pesan ini',
'icone_valider_message' => 'Validasi pesan ini',
'info_activer_forum_public' => '<i>Untuk mengaktifkan forum-forum umum, silakan pilih mode moderasi standar forum-forum tersebut:</I>', # MODIF
'info_appliquer_choix_moderation' => 'Terapkan pilihan moderasi ini:',
'info_desactiver_forum_public' => 'Non aktifkan penggunaan forum
umum. Forum umum dapat digunakan berdasarkan kasus per kasus untuk
artikel-artikel; dan penggunannya dilarang untuk bagian, berita, dll.',
'info_envoi_forum' => 'Kirim forum ke penulis artikel',
'info_fonctionnement_forum' => 'Operasi forum:',
'info_gauche_suivi_forum_2' => 'Halaman <i>tindak lanjut forum</i> adalah alat bantu pengelola situs anda (bukan area diskusi atau pengeditan). Halaman ini menampilkan semua kontribusi forum umum artikel ini dan mengizinkan anda untuk mengelola kontribusi-kontribusi ini.', # MODIF
'info_liens_syndiques_3' => 'forum',
'info_liens_syndiques_4' => 'adalah',
'info_liens_syndiques_5' => 'forum',
'info_liens_syndiques_6' => 'adalah',
'info_liens_syndiques_7' => 'validasi tertunda.',
'info_mode_fonctionnement_defaut_forum_public' => 'Mode operasi standar forum-forum umum',
'info_option_email' => 'Ketika seorang pengunjung situs mengirimkan sebuah pesan ke forum
yang terasosiasi dengan sebuah artikel, penulis artikel akan diinformasikan
melalui e-mail. Anda ingin menggunakan opsi ini?', # MODIF
'info_pas_de_forum' => 'tidak ada forum',
'item_activer_forum_administrateur' => 'Aktifkan forum administrator',
'item_desactiver_forum_administrateur' => 'Non aktifkan forum administrator',
// L
'lien_reponse_article' => 'Balasan pada artikel',
'lien_reponse_breve_2' => 'Balasan pada artikel berita',
'lien_reponse_rubrique' => 'Balasan pada bagian',
'lien_reponse_site_reference' => 'Balasan pada situs-situs referensi:', # MODIF
// O
'onglet_messages_internes' => 'Pesan internal',
'onglet_messages_publics' => 'Pesan umum',
'onglet_messages_vide' => 'Pesan tanpa teks',
// R
'repondre_message' => 'Balasan pada pesan ini',
// S
'statut_original' => 'asli',
// T
'titre_cadre_forum_administrateur' => 'Forum pribadi para administrator',
'titre_cadre_forum_interne' => 'Forum intern',
'titre_forum' => 'Forum',
'titre_forum_suivi' => 'Tindak lanjut forum',
'titre_page_forum_suivi' => 'Tindak lanjut forum'
);
?>
| ernestovi/ups | spip/plugins-dist/forum/lang/forum_id.php | PHP | gpl-3.0 | 6,067 |
<?php
class Dashboard extends Controller
{
// Protected or private properties
protected $_template;
// Constructor
public function __construct()
{
parent::Controller();
// Check if the logged user is an administrator
$this->access_library->check_access();
// Load needed models, libraries, helpers and language files
$this->load->module_model('admin', 'information_model', 'information');
$this->load->module_language('admin', 'dashboard');
}
// Public methods
public function index()
{
$this->config->load('open_blog');
$data['website_url'] = $this->config->item('website_url');
$data['new_version'] = $this->information->check_for_upgrade();
$this->_template['page'] = 'dashboard';
$this->system_library->load($this->_template['page'], $data, TRUE);
}
}
/* End of file dashboard.php */
/* Location: ./application/modules/admin/controllers/dashboard.php */ | JasonBaier/Open-Blog | application/modules/admin/controllers/dashboard.php | PHP | gpl-3.0 | 952 |
# This file is part of BuhIRC.
#
# BuhIRC 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.
#
# BuhIRC 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 BuhIRC. If not, see <http://www.gnu.org/licenses/>.
import re
import random
from modules import Module
class VoreModule(Module):
name = "Vore"
description = "#vore-specific commands and chat responses."
# These regexes are borrowed from GyroTech's code
self_regex = "(?i)(((it|him|her|their|them)sel(f|ves))|Burpy\s?Hooves)"
all_regex = "(?i)every\s?(body|one|pony|pone|poni)"
def module_init(self, bot):
if "vore" not in bot.config:
return "Vore section in config is required."
self.config = bot.config["vore"]
self.reacts = self.config["react_messages"]
self.cmd_replies = self.config["command_replies"]
self.hook_command("eat", self.on_command_eat)
self.hook_command("cockvore", self.on_command_cockvore)
self.hook_command("inflate", self.on_command_inflate)
def do_command_reply(self, bot, target, replies):
# Replies is a 3-tuple of lists that looks like: (replies for target=me, replies for target=all, replies for target=user)
reply = None
if re.match(self.self_regex, target, re.IGNORECASE): # !eat BuhIRC
reply = random.choice(replies[0])
elif re.match(self.all_regex, target, re.IGNORECASE): # !eat everypony
reply = random.choice(replies[1])
else:
reply = random.choice(replies[2]) # !eat AppleDash (Or any other user.)
try:
bot.reply_act(reply % target)
except TypeError: # Format string wasn't filled. (No %s)
bot.reply_act(reply)
def on_command_eat(self, bot, ln, args):
eaten = ln.hostmask.nick
if len(args) > 0:
eaten = " ".join(args)
eaten = eaten.strip()
self.do_command_reply(bot, eaten, (self.cmd_replies["eat_self"], self.cmd_replies["eat_all"], self.cmd_replies["eat_user"]))
def on_command_cockvore(self, bot, ln, args):
cockvored = ln.hostmask.nick
if len(args) > 0:
cockvored = " ".join(args)
cockvored = cockvored.strip()
self.do_command_reply(bot, cockvored, (self.cmd_replies["cockvore_self"], self.cmd_replies["cockvore_all"], self.cmd_replies["cockvore_user"]))
def on_command_inflate(self, bot, ln, args):
inflated = ln.hostmask.nick
if len(args) > 0:
inflated = " ".join(args)
inflated = inflated.strip()
if re.match(self.all_regex, inflated, re.IGNORECASE): # Not implemented
return
self.do_command_reply(bot, inflated, (self.cmd_replies["inflate_self"], [], self.cmd_replies["inflate_user"]))
| AppleDash/burpyhooves | modules/vore.py | Python | gpl-3.0 | 3,226 |
"""
WSGI config for group_warning project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "group_warning.settings")
application = get_wsgi_application()
| fazlerabby7/group_warning | group_warning/wsgi.py | Python | gpl-3.0 | 404 |
/****************************************
* This file is part of UNIX Guide for the Perplexed project.
* Copyright (C) 2014 by Assaf Gordon <assafgordon@gmail.com>
* Released under GPLv3 or later.
****************************************/
/* Each test in 'tests' array has the following elements:
* 1. short name for the test (must be unique).
* 2. input string for the parser
* 3. should-be-accepted: true/false.
* if TRUE, the syntax is expected to be
* accepted by the parser, using the specific rule in item 4,
* *AND ALL SUBSEQUENT* rules. See "rules" variable for the list and order
* of rules.
* if FALSE, the syntax must not be accepted by the parser, using the
* specific rule in item 4.
* 4. parser rule to check.
* The rule name must match the names in 'posix_shell.pegjs' .
* See 'rules' variable for list of valid starting rules.
*/
"use strict";
/* List of rules, must be the same as the rules
* listed in "posix_shell.pegjs".
* For each rule (the key), the subsequent rules to be also tested are listed.
* The hierarchial order must match 'posix_shell.pegjs'.
*/
var rules = {
'Non_Operator_UnquotedCharacters' : 'Tokens_Command',
'SingleQuotedString' : 'Tokens_Command',
'DoubleQuotedString' : 'Tokens_Command',
'SubshellExpandable' : 'Tokens_Command',
'BacktickExpandable' : 'Tokens_Command',
'ParameterExpandable' : 'Tokens_Command',
'ParameterOperationExpandable' : 'Tokens_Command',
'ArithmeticExpandable' : 'Tokens_Command',
'Expandable' : '',
'Tokens_Command' : 'SimpleCommand',
'Redirection' : 'Redirections',
'Assignment' : 'Assignments_Or_Redirections',
'Assignments_Or_Redirections' : 'SimpleCommand',
'Redirections' : 'SimpleCommand',
'SimpleCommand' : 'Command',
'Command' : 'Pipeline',
'Pipeline' : 'AndOrList',
'AndOrList' : 'List',
'List' : undefined, /* last rule in hierarchy */
/* Special rules, which should not automatically lead to subsequent rules */
'Token_NoDelimiter' : undefined,
'TerminatedList' : undefined,
/* NOTE: these rules must be used directly, no other rule points to them */
'Compound_Command_Subshell' : 'Command',
'Compound_Command_Currentshell' : 'Command',
'For_clause' : 'Command'
};
var tests = [
/* test-name, test-input, should-be-accepted, start-rule */
/* Single words, without any quoted characters, accpted in the context of a command. */
["nqc1", "hello", true, "Non_Operator_UnquotedCharacters"],
["nqc2", "he%llo", true, "Non_Operator_UnquotedCharacters"],
["nqc3", "9hello", true, "Non_Operator_UnquotedCharacters"],
["nqc4", "h_", true, "Non_Operator_UnquotedCharacters"],
["nqc5", "==ds@_", true, "Non_Operator_UnquotedCharacters"],
["nqc6", "foo bar", true, "Non_Operator_UnquotedCharacters"],
["nqc7", "foo\"bar", false, "Non_Operator_UnquotedCharacters"],
["nqc8", "foo\$bar", false, "Non_Operator_UnquotedCharacters"],
["nqc9", "|foobar", false, "Non_Operator_UnquotedCharacters"],
["nqc10", "foobar>", false, "Non_Operator_UnquotedCharacters"],
["nqc11", "foobar&", false, "Non_Operator_UnquotedCharacters"],
["nqc12", "foobar;", false, "Non_Operator_UnquotedCharacters"],
["nqc13", ";foobar", false, "Non_Operator_UnquotedCharacters"],
/* Single and Double Quoted strings (must be properly quoted) */
["dquote1", '"hello"', true, "DoubleQuotedString"],
["dquote2", 'hello', false, "DoubleQuotedString"],
["dquote3", 'h"ello', false, "DoubleQuotedString"],
["dquote4", '"hello', false, "DoubleQuotedString"],
["dquote5", 'hello"', false, "DoubleQuotedString"],
["dquote6", '"he$llo"', true, "DoubleQuotedString"],
["dquote7", '"he>llo"', true, "DoubleQuotedString"],
["dquote8", '"he llo"', true, "DoubleQuotedString"],
["dquote9", '"he\\llo"', true, "DoubleQuotedString"],
["dquote10", '"he|llo"', true, "DoubleQuotedString"],
["dquote11", '""', true, "DoubleQuotedString"],
["dquote12", '"hell\'lo"', true, "DoubleQuotedString"],
["dquote13", '"hello world"',true, "DoubleQuotedString"],
["dquote14", '"foo\tbar"', true, "DoubleQuotedString"],
["dquote15", '"hello("', true, "DoubleQuotedString"],
["dquote16", '"he)llo"', true, "DoubleQuotedString"],
["dquote17", '"he{llo"', true, "DoubleQuotedString"],
["dquote18", '"he}llo"', true, "DoubleQuotedString"],
["dquote19", '"${FOO}world"',true, "DoubleQuotedString"],
/* Double-Quotes with parameter expansion */
["dquote30", '"hello$(uname)world"', true, "DoubleQuotedString"],
["dquote31", '"hello$(uname -s)world"',true, "DoubleQuotedString"],
["dquote32", '"hello${uname}world"', true, "DoubleQuotedString"],
["dquote33", '"hello$(echo "world")"',true, "DoubleQuotedString"],
["dquote34", '"hello$(echo \'world\')"',true, "DoubleQuotedString"],
["dquote37", '"hello$FOO"', true, "DoubleQuotedString"],
["dquote38", '"hello$((1+4))"',true, "DoubleQuotedString"],
["dquote39", '"hello$(echo"',false, "DoubleQuotedString"],
["dquote40", '"hello${echo"',false, "DoubleQuotedString"],
["dquote41", '"hello$((1+4)"',false, "DoubleQuotedString"],
["squote1", "'hello'", true, "SingleQuotedString"],
["squote2", "he'llo", false, "SingleQuotedString"],
["squote3", "'hello", false, "SingleQuotedString"],
["squote4", "hello'", false, "SingleQuotedString"],
["squote5", "'he$llo'", true, "SingleQuotedString"],
["squote6", "'he\"llo'", true, "SingleQuotedString"],
["squote7", "'he llo'", true, "SingleQuotedString"],
["squote8", "''", true, "SingleQuotedString"],
["squote9", "'\"'", true, "SingleQuotedString"],
/* Test single tokens - any combination fo quoted and unquoted strings,
that logically become one token/word.
Special characters must be properly quoted. */
["word1", 'he"llo"', true, "Token_NoDelimiter"],
["word2", 'he"ll\'o"', true, "Token_NoDelimiter"],
["word3", 'he"ll""o"', true, "Token_NoDelimiter"],
["word4", 'hell\\"o', true, "Token_NoDelimiter"],
["word5", 'he"\'ll"o', true, "Token_NoDelimiter"],
["word6", 'he\\|llo', true, "Token_NoDelimiter"],
["word7", 'he"\\|"llo', true, "Token_NoDelimiter"],
["word8", 'he"\\\\"llo', true, "Token_NoDelimiter"],
["word9", 'he\\\\llo', true, "Token_NoDelimiter"],
["word10", '"he|llo"', true, "Token_NoDelimiter"],
["word11", '"he l lo"', true, "Token_NoDelimiter"],
["word12", '"he&llo"', true, "Token_NoDelimiter"],
["word13", '"he;llo"', true, "Token_NoDelimiter"],
["word14", '"he>llo"', true, "Token_NoDelimiter"],
["word15", '"he>llo"world',true, "Token_NoDelimiter"],
["word16", 'foo>bar', false, "Token_NoDelimiter"],
["word17", 'foo|bar', false, "Token_NoDelimiter"],
["word18", 'foo bar', false, "Token_NoDelimiter"],
["word19", 'foo\\|bar', true, "Token_NoDelimiter"],
["word20", 'foo\\>bar', true, "Token_NoDelimiter"],
["word21", 'foo\\ bar', true, "Token_NoDelimiter"],
["word22", '"foo|bar"', true, "Token_NoDelimiter"],
["word23", '"foo>bar"', true, "Token_NoDelimiter"],
["word24", '"foo bar"', true, "Token_NoDelimiter"],
["word25", '"foo "bar', true, "Token_NoDelimiter"],
["word26", "'foo 'bar", true, "Token_NoDelimiter"],
["word27", "'foo '\"bar\"",true, "Token_NoDelimiter"],
/* TODO: these are accepted, but at the moment - do not actually
perform sub-shell and parameter expansion */
/* Test 'tokens' rule - whitespace separates tokens,
only non-operator tokens should be accepted
(operator characters can be accepted if they're quoted - thus
losing their special meaning) */
["token1", "hello world", true, "Tokens_Command"],
["token2", "hello world", true, "Tokens_Command"],
["token4", "'hello world' foo bar", true, "Tokens_Command"],
["token5", "'hello world' \"foo bar\"", true, "Tokens_Command"],
/* single-quote not terminated */
["token6", "hello world' \"foo bar\"", false, "Tokens_Command"],
["token7", "hello \t \t world", true, "Tokens_Command"],
["token8", "hello '' world", true, "Tokens_Command"],
["token9", 'cut -f1 -d""', true, "Tokens_Command"],
["token10", 'foo bar|', false, "Tokens_Command"],
["token11", 'foo|bar', false, "Tokens_Command"],
["token12", 'foo>bar', false, "Tokens_Command"],
["token13", 'foo ">bar"', true, "Tokens_Command"],
["token14", 'foo && bar', false, "Tokens_Command"],
["token15", 'foo ; bar', false, "Tokens_Command"],
["token16", 'foo > bar', false, "Tokens_Command"],
["token17", 'foo ">" bar', true, "Tokens_Command"],
/* Token commands must not accept reserved words as first words
of the command, but accept if non-first */
["token18", 'echo if', true, "Tokens_Command"],
["token19", 'if echo', false, "Tokens_Command"],
["token20", 'echo {', true, "Tokens_Command"],
["token21", '{ echo', false, "Tokens_Command"],
["token22", 'echo }', true, "Tokens_Command"],
["token23", '} echo', false, "Tokens_Command"],
["token24", 'echo else', true, "Tokens_Command"],
["token25", 'else echo', false, "Tokens_Command"],
["token26", 'echo elif', true, "Tokens_Command"],
["token27", 'elif echo', false, "Tokens_Command"],
["token28", 'echo then', true, "Tokens_Command"],
["token29", 'then echo', false, "Tokens_Command"],
["token30", 'echo fi', true, "Tokens_Command"],
["token31", 'fi echo', false, "Tokens_Command"],
["token32", 'echo while', true, "Tokens_Command"],
["token33", 'while echo', false, "Tokens_Command"],
["token34", 'echo until', true, "Tokens_Command"],
["token35", 'until echo', false, "Tokens_Command"],
["token36", 'echo do', true, "Tokens_Command"],
["token37", 'do echo', false, "Tokens_Command"],
["token38", 'echo done', true, "Tokens_Command"],
["token39", 'done echo', false, "Tokens_Command"],
["token40", 'echo case', true, "Tokens_Command"],
["token41", 'case echo', false, "Tokens_Command"],
["token42", 'echo esac', true, "Tokens_Command"],
["token43", 'esac echo', false, "Tokens_Command"],
["token44", 'echo in', true, "Tokens_Command"],
["token45", 'in echo', false, "Tokens_Command"],
["token46", 'echo !', true, "Tokens_Command"],
["token47", '! echo', false, "Tokens_Command"],
/* Test single redirection */
["redir1", ">foo.txt", true, "Redirection"],
["redir2", "2>foo.txt", true, "Redirection"],
["redir3", "<foo.txt", true, "Redirection"],
["redir4", "2>&1", true, "Redirection"],
["redir5", ">&1", true, "Redirection"],
["redir6", "<>foo.txt", true, "Redirection"],
["redir7", ">>foo.txt", true, "Redirection"],
["redir8", ">'f o o.txt'", true, "Redirection"],
["redir9", ">f o o.txt", false, "Redirection"],
["redir10", ">", false, "Redirection"],
["redir11", "<", false, "Redirection"],
/* The redirection rule accepts just one redirection.
multiple redirections are tested below. */
["redir12", ">foo.txt 2>&1", false, "Redirection"],
["redir13", "<bar.txt >foo.txt", false, "Redirection"],
//allow whitespace before the filename
["redir14", "> foo.txt", true, "Redirection"],
["redir15", "< foo.txt", true, "Redirection"],
["redir16", ">> foo.txt", true, "Redirection"],
["redir17", "<> foo.txt", true, "Redirection"],
/* Test Multiple Redirections */
["mredir1", ">foo.txt 2>&1", true, "Redirections"],
["mredir2", "<bar.txt >foo.txt", true, "Redirections"],
["mredir3", "<bar.txt>foo.txt", true, "Redirections"],
["mredir4", "2>&1<foo.txt", true, "Redirections"],
/* Test Single Assignment */
["asgn1", "FOO=BAR", true, "Assignment"],
["asgn2", "FOO='fo fo > BAR'", true, "Assignment"],
["asgn3", "FOO=HELLO\"WOR LD\"", true, "Assignment"],
["asgn4", "FOO=", true, "Assignment"],
["asgn5", "F\"OO\"=BAR", false, "Assignment"],
["asgn6", "=BAR", false, "Assignment"],
/* Test multiple assignments and redirections.
though not very common, both assignments AND redirections can appear
before the actual command to execute, eg.:
FOO=BAR <input.txt >counts.txt wc -l
Additionally, shell commands with only assignments and redirections
(and no command to execute) are perfectly valid.
*/
["asgnrdr1", "FOO=BAR >hello.txt", true, "Assignments_Or_Redirections"],
["asgnrdr2", "FOO=BAR HELLO=WORLD", true, "Assignments_Or_Redirections"],
["asgnrdr3", "2>&1 FOO=BAR BAZ=BOM", true, "Assignments_Or_Redirections"],
["asgnrdr4", "FOO=BAR>out.txt", true, "Assignments_Or_Redirections"],
["asgnrdr5", "FOO=\">foo.txt\">out.txt", true, "Assignments_Or_Redirections"],
/* this test includes a command 'seq', and should not be accepted by this rule.
it should be accepted by later rules. */
["asgnrdr6", "FOO=BAR seq 10", false, "Assignments_Or_Redirections"],
["asgnrdr7", "FOO=BAR >out.txt seq 10", false, "Assignments_Or_Redirections"],
/* Test Simple Commands, with assignment and redirections */
["smpl1", "FOO=BAR cut -f1", true, "SimpleCommand" ],
["smpl2", "FOO=BAR HELLO=WORLD cut -f1", true, "SimpleCommand" ],
/* NOTE: the last BAZ=BOO is NOT a variable assignment. it should be parsed
* as a normal parameter to 'cut' - but it is still a valid command syntax. */
["smpl3", "FOO=BAR HELLO=WORLD cut -f1 BAZ=BOO", true, "SimpleCommand" ],
["smpl4", "FOO=BAR <foo.txt cut -f1", true, "SimpleCommand" ],
["smpl5", "<foo.txt cut -f1", true, "SimpleCommand" ],
["smpl6", "7<foo.txt cut -f1", true, "SimpleCommand" ],
["smpl7", "7<foo.txt FOO=BAR ZOOM=ZOOM >text.txt cut -f1", true, "SimpleCommand" ],
["smpl8", "2>&1 FOO=BAR ZOOM=ZOOM cut -f1", true, "SimpleCommand" ],
["smpl9", "7<&1 FOO=BAR ZOOM=ZOOM cut -f1", true, "SimpleCommand" ],
["smpl10", "<>yes.txt FOO=BAR ZOOM=ZOOM cut -f1", true, "SimpleCommand" ],
["smpl11", "FFO=BAR>yes.txt cut -f1", true, "SimpleCommand" ],
["smpl12", ">yes.txt cut -f1 <foo.txt", true, "SimpleCommand" ],
/* test 'redirection_word_hack' rule */
["smpl13", "cut -f1 >foo.txt 2>&1", true, "SimpleCommand" ],
["smpl14", "cut -f1 2>&1", true, "SimpleCommand" ],
["smpl15", "cut -f1 1>foo.txt 2>&1", true, "SimpleCommand" ],
["smpl16", "HELLO=FOO 1>foo.txt 2>&1" , true, "SimpleCommand" ],
/* Simple commands must not accept pipes, ands, ors and
other special operators, unless quoted. */
["smpl17", "seq 10 | wc -l", false, "SimpleCommand" ],
["smpl18", "seq 10 '|' wc -l", true, "SimpleCommand" ],
["smpl19", "seq 10 && echo ok", false, "SimpleCommand" ],
["smpl20", "seq 10 \"&&\" echo ok", true, "SimpleCommand" ],
["smpl21", "seq 10 || echo ok", false, "SimpleCommand" ],
["smpl22", "seq 10 \"||\" echo ok", true, "SimpleCommand" ],
["smpl23", "seq 10 \\|\\| echo ok" , true, "SimpleCommand" ],
["smpl25", "seq 10 ; echo ok", false, "SimpleCommand" ],
["smpl26", "seq 10 & echo ok", false, "SimpleCommand" ],
/* Few more cases */
["smpl27", "true>foo.txt", true, "SimpleCommand" ],
["smpl28", "true>foo.txt<foo.txt", true, "SimpleCommand" ],
/* Simple Command rule must not accept compound commands */
["smpl40", "( true | false )", false, "SimpleCommand" ],
["smpl41", "{ true ; false ; }", false, "SimpleCommand" ],
/* Test Compound-Command-SubShell rule */
["cmpss1", "( uname )", true, "Compound_Command_Subshell"],
["cmpss2", "(uname)", true, "Compound_Command_Subshell"],
["cmpss3", "( uname | true | false)", true, "Compound_Command_Subshell"],
["cmpss4", "( uname | true & false)", true, "Compound_Command_Subshell"],
["cmpss5", "( uname ; true ; false)", true, "Compound_Command_Subshell"],
["cmpss6", "( uname && true || false)", true, "Compound_Command_Subshell"],
["cmpss7", "()", false, "Compound_Command_Subshell"],
/* Test Compound-Command-CurrentShell rule */
["cmpcs1", "{ uname ; }", true, "Compound_Command_Currentshell"],
["cmpcs2", "{ uname & }", true, "Compound_Command_Currentshell"],
["cmpcs3", "{ uname }", false, "Compound_Command_Currentshell"],
["cmpcs4", "{ uname;}", true, "Compound_Command_Currentshell"],
["cmpcs5", "{ uname&}", true, "Compound_Command_Currentshell"],
["cmpcs6", "{ uname; }", true, "Compound_Command_Currentshell"],
["cmpcs7", "{ uname& }", true, "Compound_Command_Currentshell"],
["cmpcs9", "{ uname | true | false ; }", true, "Compound_Command_Currentshell"],
["cmpcs10", "{ uname | true & false ; }", true, "Compound_Command_Currentshell"],
["cmpcs11", "{ uname ; true ; false ; }", true, "Compound_Command_Currentshell"],
["cmpcs12", "{ uname && true || false & }", true, "Compound_Command_Currentshell"],
["cmpcs13", "{}", false, "Compound_Command_Currentshell"],
/* Test For clause */
["for1", "for a in a b c d ; do true ; done", true, "For_clause"],
/* missing 'in' */
["for2", "for a a b c d ; do true ; done", false, "For_clause"],
/* missing semi-colon before do */
["for3", "for a in a b c d do true ; done", false, "For_clause"],
/* missing 'do' */
["for4", "for a in a b c d ; true ; done", false, "For_clause"],
/* missing semi-colon before done */
["for5", "for a in a b c d ; do true done", false, "For_clause"],
/* missing command between do and done */
["for6", "for a in a b c d ; do ; done", false, "For_clause"],
/* non-simple values in word-list */
["for7", "for a in $(ls); do echo a=$a ; done", true, "For_clause"],
/* Test Pipeline rule */
["pipe1", "seq 1 2 10 | wc -l", true, "Pipeline"],
["pipe2", "seq 1 2 10 2>foo.txt | wc -l 2>>foo2.txt ", true, "Pipeline"],
["pipe3", "FOO=BAR seq 1 2 10 2>foo.txt | wc -l 2>>foo2.txt ", true, "Pipeline"],
["pipe4", "FOO=BAR seq 1 2 10 2>foo.txt | FOO=BAR Pc -l 2>>foo2.txt ", true, "Pipeline"],
["pipe5", "FOO=BAR seq 1 2 10 2>foo.txt | <input.txt wc -l 2>>foo2.txt ", true, "Pipeline"],
["pipe6", "FOO=BAR seq 1 2 10 2>foo.txt | FOO=BAR <input.txt wc -l 2>>foo2.txt ", true, "Pipeline"],
["pipe7", "cut -f1 <genes.txt|sort -k1V,1 -k2nr,2 ", true, "Pipeline"],
["pipe8", "cut -f1 <genes.txt | sort -k1V,1 -k2nr,2 | uniq -c >text.txt", true, "Pipeline"],
/* Pipeline'd commands must not accept ands, ors and
other special operators, unless quoted. */
["pipe9", "cut -f1 | seq 10 && echo ok ", false, "Pipeline"],
["pipe10", "cut -f1 | seq 10 & echo ok ", false, "Pipeline"],
["pipe11", "cut -f1 | seq 10 ; echo ok ", false, "Pipeline"],
["pipe12", "true && cut -f1 | seq 10", false, "Pipeline"],
["pipe13", "cut -f1 |", false, "Pipeline"],
["pipe14", "|cut -f1 |", false, "Pipeline"],
["pipe15", "|cut -f1", false, "Pipeline"],
/* Pipelines with compound commands */
["pipe30", "seq 10 | ( sed -u 1q ; sort -nr)", true, "Pipeline"],
["pipe31", "( cat hello ; tac world ) | wc -l", true, "Pipeline"],
["pipe32", "seq 10 | { sed -u 1q ; sort -nr ; }", true, "Pipeline"],
["pipe33", "{ cat hello ; tac world ; } | wc -l", true, "Pipeline"],
/* Test AndOrList rule */
["andor1", "true && false || seq 1", true, "AndOrList" ],
["andor2", "true && false | wc", true, "AndOrList" ],
["andor3", "true && false | wc || seq 1", true, "AndOrList" ],
["andor4", "true && false && false && echo ok || echo fail",true, "AndOrList" ],
["andor5", "true && false ; wc", false, "AndOrList" ],
["andor6", "true && false & wc", false, "AndOrList" ],
["andor7", "true &&", false, "AndOrList" ],
["andor8", "true ||", false, "AndOrList" ],
["andor9", " && true", false, "AndOrList" ],
["andor10", " || true", false, "AndOrList" ],
["andor11", "&& true", false, "AndOrList" ],
["andor12", "|| true", false, "AndOrList" ],
["andor13", "true && && true", false, "AndOrList" ],
["andor14", "false && || true", false, "AndOrList" ],
/* AndOrLists with compound commands */
["andor30", "true && ( sed -u 1q ; sort -nr)", true, "AndOrList"],
["andor31", "( cat hello ; tac world ) || wc -l", true, "AndOrList"],
["andor32", "seq 10 && { sed -u 1q ; sort -nr ; }", true, "AndOrList"],
["andor33", "{ cat hello ; tac world ; } && wc -l", true, "AndOrList"],
/* Test List rule */
["list1", "true ;", true, "List" ],
["list2", "true &", true, "List" ],
["list3", "true ; false", true, "List" ],
["list4", "true ; false ;", true, "List" ],
["list5", "true & false ;", true, "List" ],
["list6", "true & false &", true, "List" ],
["list7", "true && false &", true, "List" ],
["list8", ";", false, "List" ],
["list9", "&", false, "List" ],
/* Test TerminatedList Rule - a special rule for commands inside "{}" which requires
that each command be terminated (unlike "List" rule,
in which the last command is optionally terminated */
["tlist1", "true ;", true, "TerminatedList"],
["tlist2", "true &", true, "TerminatedList"],
["tlist3", "true ; false ;", true, "TerminatedList"],
["tlist4", "true ; false &", true, "TerminatedList"],
["tlist5", "true", false, "TerminatedList"],
["tlist6", "true", false, "TerminatedList"],
["tlist7", "true ; false", false, "TerminatedList"],
["tlist8", "true ; false", false, "TerminatedList"],
/* Test Sub-Shell Parameter Expansion */
["subshell1", "$()", true, "SubshellExpandable"],
["subshell2", "$())", false, "SubshellExpandable"],
["subshell3", "$(ls)", true, "SubshellExpandable"],
["subshell4", "$(echo $(uname -s))", true, "SubshellExpandable"],
["subshell5", "$(()", false, "SubshellExpandable"],
["subshell6", "$(echo \\()", true, "SubshellExpandable"],
["subshell7", "$(echo \\))", true, "SubshellExpandable"],
["subshell8", "$(echo \\$)", true, "SubshellExpandable"],
["subshell9", "$(echo $($()$()$($($()))uname -s))", true, "SubshellExpandable"],
["subshell10", "$(echo ${USER})", true, "SubshellExpandable"],
["subshell11", "$(echo `uname -s`)", true, "SubshellExpandable"],
["subshell12", "aaa$()", false, "SubshellExpandable"],
["subshell13", "$(echo hi)" , true, "SubshellExpandable"],
["subshell14", "$( )", true, "SubshellExpandable"],
["subshell15", "$( \t \t )", true, "SubshellExpandable"],
["subshell16", "$(FOO=BAR)", true, "SubshellExpandable"],
["subshell17", "$(true|false)", true, "SubshellExpandable"],
["subshell18", "$(true;false)", true, "SubshellExpandable"],
["subshell19", "$(true;false;)", true, "SubshellExpandable"],
["subshell20", "$(foo 2>1.txt | wc-l)", true, "SubshellExpandable"],
/* Test Backtick Subshell parameter expansion */
/*TODO: add more backtick tests */
["backtick1", "`ls`", true, "BacktickExpandable"],
["backtick2", "`ls", false, "BacktickExpandable"],
["backtick3", "ls`", false, "BacktickExpandable"],
["backtick4", "ls``", false, "BacktickExpandable"],
/* TODO: Test 5 should not fail. what's the diff between this and subshell13? */
/*["backtick5", "`echo hi`", true, "BacktickExpandable"],*/
/* Test Parameter Expansion (without operations) */
["ParamExp1", "${FOO}", true, "ParameterExpandable"],
["ParamExp2", "$FOO", true, "ParameterExpandable"],
["ParamExp3", "${FOO", false, "ParameterExpandable"],
["ParamExp4", "$FOO}", false, "ParameterExpandable"],
["ParamExp5", "$F.OO", false, "ParameterExpandable"],
["ParamExp6", "$FOO=", false, "ParameterExpandable"],
["ParamExp7", "$FO${O}", false, "ParameterExpandable"],
["ParamExp8", "${FOO=BAR}", false, "ParameterExpandable"],
/* Special parameters */
["ParamExp9", "$!", true, "ParameterExpandable"],
["ParamExp10", "$$", true, "ParameterExpandable"],
["ParamExp11", "$-", true, "ParameterExpandable"],
["ParamExp12", "$?", true, "ParameterExpandable"],
["ParamExp13", "$@", true, "ParameterExpandable"],
["ParamExp14", "${!}", true, "ParameterExpandable"],
["ParamExp15", "${$}", true, "ParameterExpandable"],
["ParamExp16", "${-}", true, "ParameterExpandable"],
["ParamExp17", "${?}", true, "ParameterExpandable"],
["ParamExp18", "${@}", true, "ParameterExpandable"],
/* Test Parameter Expansion with operations */
["ParmOpExp1", "${FOO=BAR}", true, "ParameterOperationExpandable"],
["ParmOpExp2", "${FOO:-BAR}", true, "ParameterOperationExpandable"],
["ParmOpExp3", "${FOO-BAR}", true, "ParameterOperationExpandable"],
["ParmOpExp4", "${FOO:=BAR}", true, "ParameterOperationExpandable"],
["ParmOpExp5", "${FOO=BAR}", true, "ParameterOperationExpandable"],
["ParmOpExp6", "${FOO:?BAR}", true, "ParameterOperationExpandable"],
["ParmOpExp7", "${FOO?BAR}", true, "ParameterOperationExpandable"],
["ParmOpExp8", "${FOO:+BAR}", true, "ParameterOperationExpandable"],
["ParmOpExp9", "${FOO+BAR}", true, "ParameterOperationExpandable"],
["ParmOpExp10", "${FOO%BAR}", true, "ParameterOperationExpandable"],
["ParmOpExp12", "${FOO%%BAR}", true, "ParameterOperationExpandable"],
["ParmOpExp13", "${FOO#BAR}", true, "ParameterOperationExpandable"],
["ParmOpExp14", "${FOO##BAR}", true, "ParameterOperationExpandable"],
["ParmOpExp15", "${FOO=}", true, "ParameterOperationExpandable"],
["ParmOpExp16", "${FOO=(}", true, "ParameterOperationExpandable"],
/* Go Recursive */
["ParmOpExp17", "${FOO=${BAR}}", true, "ParameterOperationExpandable"],
["ParmOpExp18", "${FOO=BAR${BAR}}", true, "ParameterOperationExpandable"],
["ParmOpExp19", "${FOO=${BAR-BAZ}}", true, "ParameterOperationExpandable"],
["ParmOpExp20", "${FOO=$(uname -s)BAZ}", true, "ParameterOperationExpandable"],
["ParmOpExp21", "${FOO=$BAR}", true, "ParameterOperationExpandable"],
/* Test bad syntax */
["ParmOpExp22", "${FOO", false, "ParameterOperationExpandable"],
["ParmOpExp23", "${FOO=", false, "ParameterOperationExpandable"],
["ParmOpExp24", "$FOO=BAR", false, "ParameterOperationExpandable"],
["ParmOpExp25", "$FOO=BAR}", false, "ParameterOperationExpandable"],
["ParmOpExp26", "$FOO}", false, "ParameterOperationExpandable"],
["ParmOpExp28", "${FOO=HELLO\"WORLD}", false, "ParameterOperationExpandable"],
["ParmOpExp29", "${FOO=HELLO\'WORLD}", false, "ParameterOperationExpandable"],
["ParmOpExp30", "${FOO=HEL${LOWORLD}", false, "ParameterOperationExpandable"],
["ParmOpExp31", "${#FOO}", true, "ParameterOperationExpandable"],
/* Test Arithmatic Expansion */
/* TODO: as more arithmetic operations are added, add appropriate tests */
["arthm1", "$(())", true, "ArithmeticExpandable"],
["arthm2", "$(( ))", true, "ArithmeticExpandable"],
["arthm3", "$((1))", true, "ArithmeticExpandable"],
["arthm4", "$(( 3 ))", true, "ArithmeticExpandable"],
["arthm5", "$((A))", true, "ArithmeticExpandable"],
["arthm6", "$(($A))", true, "ArithmeticExpandable"],
["arthm7", "$((1+2+3))", true, "ArithmeticExpandable"],
["arthm8", "$((1+2*3))", true, "ArithmeticExpandable"],
["arthm9", "$((A*3))", true, "ArithmeticExpandable"],
["arthm10", "$((1+FOO*3))", true, "ArithmeticExpandable"],
["arthm11", "$(((1+FOO)*3))", true, "ArithmeticExpandable"],
// Zero
["arthm12", "$((0))", true, "ArithmeticExpandable"],
// Octal
["arthm13", "$((033))", true, "ArithmeticExpandable"],
// Hex
["arthm14", "$((0x33))", true, "ArithmeticExpandable"],
/* Go Recursive */
["arthm20", "$(( $(nproc)+1 ))", true, "ArithmeticExpandable"],
["arthm21", "$(( ${PID}*1 ))", true, "ArithmeticExpandable"],
["arthm22", "$(( $((42))*9 ))", true, "ArithmeticExpandable"],
/* Test bad syntax */
["arthm30", "$(( 3+4 )", false, "ArithmeticExpandable"],
/* Test possible combinations of parameter expansions - single token*/
["expan1", "una$(echo me)", true, "Token_NoDelimiter"],
["expan2", "una${A}", true, "Token_NoDelimiter"],
["expan3", "una$A", true, "Token_NoDelimiter"],
["expan4", "una${FOO-me}", true, "Token_NoDelimiter"],
["expan5", "hel'lo'${USER}$(echo wo)`uptime`", true, "Token_NoDelimiter"],
["expan6", "${A}$(ls)$B$C${D}-foo", true, "Token_NoDelimiter"],
/* TODO: test expansion with assignment, redirection */
];
module.exports = {
"tests" : tests,
"parser_rules": rules
};
| agordon/agnostic | src/tests/shell_syntax_tests.js | JavaScript | gpl-3.0 | 27,765 |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.sql.view;
public interface EditPanelListener {
public void cancelled();
public void modified();
public void deleted();
public void inserted(int id);
}
| eric-lemesre/OpenConcerto | OpenConcerto/src/org/openconcerto/sql/view/EditPanelListener.java | Java | gpl-3.0 | 830 |
@extends('hideyo_backend::_layouts.default')
@section('main')
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
@include('hideyo_backend::_partials.news-tabs', array('newsEdit' => true))
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<ol class="breadcrumb">
<li><a href="/"><i class="entypo-folder"></i>Dashboard</a></li>
<li><a href="{!! URL::route('hideyo.news.index') !!}">News</a></li>
<li><a href="{!! URL::route('hideyo.news.edit', $news->id) !!}">edit</a></li>
<li><a href="{!! URL::route('hideyo.news.edit', $news->id) !!}">{!! $news->title !!}</a></li>
</ol>
<h2>News <small>edit</small></h2>
<hr/>
{!! Notification::showAll() !!}
{!! Form::model($news, array('method' => 'put', 'route' => array('hideyo.news.update', $news->id), 'files' => true, 'class' => 'form-horizontal form-groups-bordered validate')) !!}
<input type="hidden" name="_token" value="{!! Session::token() !!}">
<div class="form-group">
{!! Form::label('news_group_id', 'Group', array('class' => 'col-sm-3 control-label')) !!}
<div class="col-sm-5">
{!! Form::select('news_group_id', [null => '--select--'] + $groups, null, array('class' => 'form-control')) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('title', 'Title', array('class' => 'col-sm-3 control-label')) !!}
<div class="col-sm-5">
{!! Form::text('title', null, array('class' => 'form-control', 'data-validate' => 'required', 'data-message-required' => 'This is custom message for required field.')) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('short_description', 'Short description', array('class' => 'col-sm-3 control-label')) !!}
<div class="col-sm-5">
{!! Form::text('short_description', null, array('class' => 'form-control', 'data-validate' => 'required', 'data-message-required' => 'This is custom message for required field.')) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('news', 'Content', array('class' => 'col-sm-3 control-label')) !!}
<div class="col-sm-9">
{!! Form::textarea('content', null, array('class' => 'form-control ckeditor', 'data-validate' => 'required', 'data-message-required' => 'This is custom message for required field.')) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('published_at', 'Published at', array('class' => 'col-sm-3 control-label')) !!}
<div class="col-sm-5">
{!! Form::text('published_at', null, array('class' => 'datepicker form-control', 'data-sign' => '€')) !!}
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-5">
{!! Form::submit('Save', array('class' => 'btn btn-default')) !!}
<a href="{!! URL::route('hideyo.news.index') !!}" class="btn btn-large">Cancel</a>
</div>
</div>
</div>
</div>
@stop
| kkorte/backend | src/resources/views/news/edit.blade.php | PHP | gpl-3.0 | 3,427 |
package org.sigmah.offline.js;
/*
* #%L
* Sigmah
* %%
* Copyright (C) 2010 - 2016 URD
* %%
* 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/gpl-3.0.html>.
* #L%
*/
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import java.util.HashMap;
import java.util.Map;
import org.sigmah.offline.fileapi.Int8Array;
import org.sigmah.shared.dto.value.FileVersionDTO;
import org.sigmah.shared.file.TransfertType;
/**
* File upload progression.
*
* @author Raphaël Calabro (rcalabro@ideia.fr)
*/
public final class TransfertJS extends JavaScriptObject {
public static TransfertJS createTransfertJS(FileVersionDTO fileVersionDTO, TransfertType type) {
final TransfertJS transfertJS = Values.createJavaScriptObject(TransfertJS.class);
transfertJS.setFileVersion(FileVersionJS.toJavaScript(fileVersionDTO));
transfertJS.setData(Values.createTypedJavaScriptArray(Int8Array.class));
transfertJS.setProgress(0);
transfertJS.setType(type);
return transfertJS;
}
protected TransfertJS() {
}
public native int getId() /*-{
return this.id;
}-*/;
public native void setId(int id) /*-{
this.id = id;
}-*/;
public TransfertType getType() {
return Values.getEnum(this, "type", TransfertType.class);
}
public void setType(TransfertType type) {
Values.setEnum(this, "type", type);
}
public native FileVersionJS getFileVersion() /*-{
return this.fileVersion;
}-*/;
public native void setFileVersion(FileVersionJS fileVersion) /*-{
this.fileVersion = fileVersion;
}-*/;
public native JsArray<Int8Array> getData() /*-{
return this.data;
}-*/;
public native void setData(JsArray<Int8Array> data) /*-{
this.data = data;
}-*/;
public native void setData(Int8Array data) /*-{
this.data = [data];
}-*/;
public native int getProgress() /*-{
return this.progress;
}-*/;
public native void setProgress(int progress) /*-{
this.progress = progress;
}-*/;
public native JsMap<String, String> getProperties() /*-{
return this.properties;
}-*/;
public native void setProperties(JsMap<String, String> properties) /*-{
this.properties = properties;
}-*/;
public Map<String, String> getPropertyMap() {
if(getProperties() != null) {
return new HashMap<String, String>(new AutoBoxingJsMap<String, String>(getProperties(), AutoBoxingJsMap.STRING_BOXER));
}
return null;
}
public void setProperties(Map<String, String> map) {
if(map != null) {
final JsMap<String, String> jsMap = JsMap.createMap();
jsMap.putAll(map);
setProperties(jsMap);
}
}
}
| Raphcal/sigmah | src/main/java/org/sigmah/offline/js/TransfertJS.java | Java | gpl-3.0 | 3,177 |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.clearcanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project 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.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
#if UNIT_TESTS
#pragma warning disable 1591,0419,1574,1587
using System;
using System.Collections.Generic;
using System.Drawing;
using ClearCanvas.Dicom;
using ClearCanvas.ImageViewer.StudyManagement;
using NUnit.Framework;
namespace ClearCanvas.ImageViewer.PresentationStates.Dicom.Tests
{
[TestFixture]
public class OverlayPlanePresentationTests
{
private static GeneratedOverlayTestImages _testImages;
[TestFixtureSetUp]
public void Init()
{
_testImages = new GeneratedOverlayTestImages();
}
[Test]
public void TestSanity()
{
// make sure that the functions that supporting testing here can actually tell when something is wrong
var file = _testImages.ImageDataOverlay;
using (var images = CreateImages(file))
{
AssertFrameIdentity(1, 1, images[0], "assertion 1 yielded false negative");
try
{
AssertFrameIdentity(0, 1, images[0], "2");
Assert.Fail("assertion 2 yielded false positive");
}
catch (Exception)
{
// expected
}
try
{
AssertFrameIdentity(1, 5, images[0], "3");
Assert.Fail("assertion 3 yielded false positive");
}
catch (Exception)
{
// expected
}
try
{
AssertFrameIdentity(1, null, images[0], "4");
Assert.Fail("assertion 4 yielded false positive");
}
catch (Exception)
{
// expected
}
}
}
[Test]
public void TestMultiframeImageEmbeddedOverlay()
{
var file = _testImages.MultiframeImageEmbeddedOverlay;
using (var images = CreateImages(file))
{
Assert.AreEqual(17, images.Count, "should be exactly 17 frames in this instance");
// these frames should be exactly 1-to-1
for (int n = 0; n < 17; n++)
AssertFrameIdentity(n + 1, n + 1, images[n], "multiframe image with embedded overlay image #{0}", n + 1);
}
}
[Test]
public void TestMultiframeImageDataOverlay()
{
var file = _testImages.MultiframeImageDataOverlay;
using (var images = CreateImages(file))
{
Assert.AreEqual(17, images.Count, "should be exactly 17 frames in this instance");
// these frames should be exactly 1-to-1
for (int n = 0; n < 17; n++)
AssertFrameIdentity(n + 1, n + 1, images[n], "multiframe image with data overlay image #{0}", n + 1);
}
}
[Test]
public void TestMultiframeImageDataOverlayDifferentSize()
{
var file = _testImages.MultiframeImageDataOverlayDifferentSize;
using (var images = CreateImages(file))
{
Assert.AreEqual(17, images.Count, "should be exactly 17 frames in this instance");
// these frames should be exactly 1-to-1
for (int n = 0; n < 17; n++)
AssertFrameIdentity(n + 1, n + 1, images[n], "multiframe image with different size data overlay image #{0}", n + 1);
}
}
[Test]
public void TestMultiframeImageDataOverlayNotMultiframe()
{
var file = _testImages.MultiframeImageDataOverlayNotMultiframe;
using (var images = CreateImages(file))
{
Assert.AreEqual(17, images.Count, "should be exactly 17 frames in this instance");
// these frames should all have overlay #1
for (int n = 0; n < 17; n++)
AssertFrameIdentity(n + 1, 1, images[n], "multiframe image with non-multiframe data overlay image #{0}", n + 1);
}
}
[Test]
public void TestMultiframeImageDataOverlayLowSubrangeImplicitOrigin()
{
var file = _testImages.MultiframeImageDataOverlayLowSubrangeImplicitOrigin;
using (var images = CreateImages(file))
{
Assert.AreEqual(17, images.Count, "should be exactly 17 frames in this instance");
// these frames should all have 1-to-1 overlays
for (int n = 0; n < 7; n++)
AssertFrameIdentity(n + 1, n + 1, images[n], "multiframe image with data overlays on subrange 1-7 (encoded as implicit origin) image #{0}", n + 1);
// these frames should not have overlays
for (int n = 7; n < 17; n++)
AssertFrameIdentity(n + 1, null, images[n], "multiframe image with data overlays on subrange 1-7 (encoded as implicit origin) image #{0}", n + 1);
}
}
[Test]
public void TestMultiframeImageDataOverlayLowSubrange()
{
var file = _testImages.MultiframeImageDataOverlayLowSubrange;
using (var images = CreateImages(file))
{
Assert.AreEqual(17, images.Count, "should be exactly 17 frames in this instance");
// these frames should all have 1-to-1 overlays
for (int n = 0; n < 7; n++)
AssertFrameIdentity(n + 1, n + 1, images[n], "multiframe image with data overlays on subrange 1-7 image #{0}", n + 1);
// these frames should not have overlays
for (int n = 7; n < 17; n++)
AssertFrameIdentity(n + 1, null, images[n], "multiframe image with data overlays on subrange 1-7 image #{0}", n + 1);
}
}
[Test]
public void TestMultiframeImageDataOverlayMidSubrange()
{
var file = _testImages.MultiframeImageDataOverlayMidSubrange;
using (var images = CreateImages(file))
{
Assert.AreEqual(17, images.Count, "should be exactly 17 frames in this instance");
// these frames should all have 1-to-1 overlays
for (int n = 5; n < 12; n++)
AssertFrameIdentity(n + 1, n + 1 - 5, images[n], "multiframe image with data overlays on subrange 6-12 image #{0}", n + 1);
// these frames should not have overlays
for (int n = 12; n < 17; n++)
AssertFrameIdentity(n + 1, null, images[n], "multiframe image with data overlays on subrange 6-12 image #{0}", n + 1);
// these frames should not have overlays
for (int n = 0; n < 5; n++)
AssertFrameIdentity(n + 1, null, images[n], "multiframe image with data overlays on subrange 6-12 image #{0}", n + 1);
}
}
[Test]
public void TestMultiframeImageDataOverlayHighSubrange()
{
var file = _testImages.MultiframeImageDataOverlayHighSubrange;
using (var images = CreateImages(file))
{
Assert.AreEqual(17, images.Count, "should be exactly 17 frames in this instance");
// these frames should all have 1-to-1 overlays
for (int n = 10; n < 17; n++)
AssertFrameIdentity(n + 1, n + 1 - 10, images[n], "multiframe image with data overlays on subrange 11-17 image #{0}", n + 1);
// these frames should not have overlays
for (int n = 0; n < 10; n++)
AssertFrameIdentity(n + 1, null, images[n], "multiframe image with data overlays on subrange 11-17 image #{0}", n + 1);
}
}
[Test]
public void TestImageEmbeddedOverlay()
{
var file = _testImages.ImageEmbeddedOverlay;
using (var images = CreateImages(file))
{
Assert.AreEqual(1, images.Count, "should be exactly 1 frames in this instance");
// that frames should be exactly 1-to-1
AssertFrameIdentity(1, 1, images[0], "image with embedded overlay image #{0}", 1);
}
}
[Test]
public void TestImageDataOverlay()
{
var file = _testImages.ImageDataOverlay;
using (var images = CreateImages(file))
{
Assert.AreEqual(1, images.Count, "should be exactly 1 frames in this instance");
// that frames should be exactly 1-to-1
AssertFrameIdentity(1, 1, images[0], "image with data overlay image #{0}", 1);
}
}
[Test]
public void TestImageDataOverlayDifferentSize()
{
var file = _testImages.ImageDataOverlayDifferentSize;
using (var images = CreateImages(file))
{
Assert.AreEqual(1, images.Count, "should be exactly 1 frames in this instance");
// that frames should be exactly 1-to-1
AssertFrameIdentity(1, 1, images[0], "image with different size data overlay image #{0}", 1);
}
}
[Test]
public void TestImageDataOverlayMultiframe()
{
var file = _testImages.ImageDataOverlayMultiframe;
using (var images = CreateImages(file))
{
Assert.AreEqual(1, images.Count, "should be exactly 1 frames in this instance");
// that frames should not have an overlay displayed
AssertFrameIdentity(1, null, images[0], "image with multiframe data overlay image #{0}", 1);
}
// should check that there is an error displayed
}
[Test]
public void TestImageEmbeddedOverlay8Bit()
{
var file = _testImages.ImageEmbeddedOverlay8Bit;
using (var images = CreateImages(file))
{
Assert.AreEqual(1, images.Count, "should be exactly 1 frames in this instance");
// that frames should be exactly 1-to-1
AssertFrameIdentity(1, 1, images[0], "image with embedded overlay image #{0}", 1);
}
}
[Test]
public void TestImageDataOverlayOWAttribute()
{
var file = _testImages.ImageDataOverlayOWAttribute;
using (var images = CreateImages(file))
{
Assert.AreEqual(1, images.Count, "should be exactly 1 frames in this instance");
// that frames should be exactly 1-to-1
AssertFrameIdentity(1, 1, images[0], "image with data overlay image #{0}", 1);
}
}
[Test]
public void TestMultiframeImageEmbeddedOverlay8Bit()
{
var file = _testImages.MultiframeImageEmbeddedOverlay8Bit;
using (var images = CreateImages(file))
{
Assert.AreEqual(17, images.Count, "should be exactly 17 frames in this instance");
// these frames should be exactly 1-to-1
for (int n = 0; n < 17; n++)
AssertFrameIdentity(n + 1, n + 1, images[n], "multiframe image with embedded overlay image #{0}", n + 1);
}
}
[Test]
public void TestMultiframeImageDataOverlayOWAttribute()
{
var file = _testImages.MultiframeImageDataOverlayOWAttribute;
using (var images = CreateImages(file))
{
Assert.AreEqual(17, images.Count, "should be exactly 17 frames in this instance");
// these frames should be exactly 1-to-1
for (int n = 0; n < 17; n++)
AssertFrameIdentity(n + 1, n + 1, images[n], "multiframe image with data overlay image #{0}", n + 1);
}
}
private static void AssertFrameIdentity(int expectedImageFrameNumber, int? expectedOverlayFrameNumber, IPresentationImage image, string message, params object[] args)
{
int actualImageFrameNumber;
int? actualOverlayFrameNumber;
IdentifyPresentationImageFrames(image, out actualImageFrameNumber, out actualOverlayFrameNumber);
Assert.AreEqual(expectedImageFrameNumber, actualImageFrameNumber, message + " (IMAGE frame number)", args);
Assert.AreEqual(expectedOverlayFrameNumber, actualOverlayFrameNumber, message + " (OVERLAY frame number)", args);
}
private static void IdentifyPresentationImageFrames(IPresentationImage image, out int imageFrameNumber, out int? overlayFrameNumber)
{
var overlayColor = Color.Red;
var imageColor = Color.White;
// force the overlays to show in our chosen colour
PresentationState.DicomDefault.Deserialize(image);
var dps = DicomGraphicsPlane.GetDicomGraphicsPlane((IDicomPresentationImage) image, true);
foreach (var overlay in dps.ImageOverlays)
overlay.Color = overlayColor;
var sopProvider = (IImageSopProvider) image;
using (var dump = image.DrawToBitmap(sopProvider.Frame.Columns, sopProvider.Frame.Rows))
{
// identify the frame number encoded in the image
imageFrameNumber = 0;
imageFrameNumber += AreEqual(Sample(dump, 95, 205, 8, 8), imageColor) ? 0x10 : 0;
imageFrameNumber += AreEqual(Sample(dump, 113, 205, 8, 8), imageColor) ? 0x08 : 0;
imageFrameNumber += AreEqual(Sample(dump, 130, 205, 8, 8), imageColor) ? 0x04 : 0;
imageFrameNumber += AreEqual(Sample(dump, 148, 205, 8, 8), imageColor) ? 0x02 : 0;
imageFrameNumber += AreEqual(Sample(dump, 166, 205, 8, 8), imageColor) ? 0x01 : 0;
// check if overlay positioning blocks are in the right place
if (!AreEqual(Sample(dump, 187, 73, 8, 8), overlayColor) || !AreEqual(Sample(dump, 74, 182, 8, 8), overlayColor))
{
overlayFrameNumber = null;
return;
}
// identify the frame number encoded in the overlay
overlayFrameNumber = 0;
overlayFrameNumber += AreEqual(Sample(dump, 95, 182, 8, 8), overlayColor) ? 0x10 : 0;
overlayFrameNumber += AreEqual(Sample(dump, 113, 182, 8, 8), overlayColor) ? 0x08 : 0;
overlayFrameNumber += AreEqual(Sample(dump, 130, 182, 8, 8), overlayColor) ? 0x04 : 0;
overlayFrameNumber += AreEqual(Sample(dump, 148, 182, 8, 8), overlayColor) ? 0x02 : 0;
overlayFrameNumber += AreEqual(Sample(dump, 166, 182, 8, 8), overlayColor) ? 0x01 : 0;
}
}
private static DisposableList<IPresentationImage> CreateImages(DicomFile dicomFile)
{
using (var dataSource = new LocalSopDataSource(dicomFile))
{
using (var sop = new ImageSop(dataSource))
{
return new DisposableList<IPresentationImage>(PresentationImageFactory.Create(sop));
}
}
}
private class DisposableList<T> : List<T>, IDisposable
where T : IDisposable
{
public DisposableList(IEnumerable<T> collection)
: base(collection) {}
public void Dispose()
{
foreach (var item in this)
item.Dispose();
}
}
private static bool AreEqual(Color a, Color b)
{
var c = Color.FromArgb(Math.Abs(a.R - b.R), Math.Abs(a.G - b.G), Math.Abs(a.B - b.B));
return c.GetBrightness() < 0.01f;
}
private static Color Sample(Bitmap image, int x, int y, int width, int height)
{
float count = width*height;
float r = 0;
float g = 0;
float b = 0;
for (int dx = -width/2; dx < width/2; dx++)
{
for (int dy = -height/2; dy < height/2; dy++)
{
var c = image.GetPixel(dx + x, dy + y);
r += c.R/count;
g += c.G/count;
b += c.B/count;
}
}
return Color.FromArgb((int) r, (int) g, (int) b);
}
}
}
#endif | chinapacs/ImageViewer | ImageViewer/PresentationStates/Dicom/Tests/OverlayPlanePresentationTests.cs | C# | gpl-3.0 | 14,746 |
#!/usr/bin/python3
from ansible.module_utils.arvados_common import process
def main():
additional_argument_spec={
"uuid": dict(required=True, type="str"),
"owner_uuid": dict(required=True, type="str"),
"name": dict(required=True, type="str"),
}
filter_property = "uuid"
filter_value_module_parameter = "uuid"
module_parameter_to_resource_parameter_map = {
"owner_uuid": "owner_uuid",
"name": "name",
}
process("repositories", additional_argument_spec, filter_property, filter_value_module_parameter,
module_parameter_to_resource_parameter_map)
if __name__ == "__main__":
main()
| wtsi-hgi/hgi-ansible | ansible/library/arvados_repository.py | Python | gpl-3.0 | 670 |
/*
* This file is part of Flying PhotoBooth.
*
* Flying PhotoBooth 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.
*
* Flying PhotoBooth 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 Flying PhotoBooth. If not, see <http://www.gnu.org/licenses/>.
*/
package com.groundupworks.partyphotobooth.setup.fragments;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Spinner;
import com.groundupworks.partyphotobooth.R;
import com.groundupworks.partyphotobooth.helpers.PreferencesHelper;
import com.groundupworks.partyphotobooth.helpers.PreferencesHelper.PhotoBoothMode;
import com.groundupworks.partyphotobooth.helpers.PreferencesHelper.PhotoBoothTheme;
import com.groundupworks.partyphotobooth.helpers.PreferencesHelper.PhotoStripTemplate;
import com.groundupworks.partyphotobooth.setup.model.PhotoBoothModeAdapter;
import com.groundupworks.partyphotobooth.setup.model.PhotoBoothThemeAdapter;
import com.groundupworks.partyphotobooth.setup.model.PhotoStripTemplateAdapter;
import java.lang.ref.WeakReference;
/**
* Ui for setting up the photo booth.
*
* @author Benedict Lau
*/
public class PhotoBoothSetupFragment extends Fragment {
/**
* Callbacks for this fragment.
*/
private WeakReference<PhotoBoothSetupFragment.ICallbacks> mCallbacks = null;
/**
* A {@link PreferencesHelper} instance.
*/
private PreferencesHelper mPreferencesHelper = new PreferencesHelper();
//
// Views.
//
private Spinner mMode;
private Spinner mTheme;
private Spinner mTemplate;
private Button mNext;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = new WeakReference<PhotoBoothSetupFragment.ICallbacks>(
(PhotoBoothSetupFragment.ICallbacks) activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/*
* Inflate views from XML.
*/
View view = inflater.inflate(R.layout.fragment_photo_booth_setup, container, false);
mMode = (Spinner) view.findViewById(R.id.setup_photo_booth_mode);
mTheme = (Spinner) view.findViewById(R.id.setup_photo_booth_theme);
mTemplate = (Spinner) view.findViewById(R.id.setup_photo_booth_template);
mNext = (Button) view.findViewById(R.id.setup_photo_booth_button_next);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Activity activity = getActivity();
final Context appContext = activity.getApplicationContext();
/*
* Configure views with saved preferences and functionalize.
*/
final PhotoBoothModeAdapter modeAdapter = new PhotoBoothModeAdapter(activity);
mMode.setAdapter(modeAdapter);
mMode.setSelection(mPreferencesHelper.getPhotoBoothMode(appContext).ordinal());
mMode.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
PhotoBoothMode selectedMode = modeAdapter.getPhotoBoothMode(position);
mPreferencesHelper.storePhotoBoothMode(appContext, selectedMode);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
});
final PhotoBoothThemeAdapter themeAdapter = new PhotoBoothThemeAdapter(activity);
mTheme.setAdapter(themeAdapter);
mTheme.setSelection(mPreferencesHelper.getPhotoBoothTheme(appContext).ordinal());
mTheme.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
PhotoBoothTheme selectedTheme = themeAdapter.getPhotoBoothTheme(position);
mPreferencesHelper.storePhotoBoothTheme(appContext, selectedTheme);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
});
final PhotoStripTemplateAdapter templateAdapter = new PhotoStripTemplateAdapter(activity);
mTemplate.setAdapter(templateAdapter);
mTemplate.setSelection(mPreferencesHelper.getPhotoStripTemplate(appContext).ordinal());
mTemplate.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
PhotoStripTemplate selectedTemplate = templateAdapter.getPhotoStripTemplate(position);
mPreferencesHelper.storePhotoStripTemplate(appContext, selectedTemplate);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
});
mNext.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Call to client.
ICallbacks callbacks = getCallbacks();
if (callbacks != null) {
callbacks.onPhotoBoothSetupCompleted();
}
}
});
}
//
// Private methods.
//
/**
* Gets the callbacks for this fragment.
*
* @return the callbacks; or null if not set.
*/
private PhotoBoothSetupFragment.ICallbacks getCallbacks() {
PhotoBoothSetupFragment.ICallbacks callbacks = null;
if (mCallbacks != null) {
callbacks = mCallbacks.get();
}
return callbacks;
}
//
// Public methods.
//
/**
* Creates a new {@link PhotoBoothSetupFragment} instance.
*
* @return the new {@link PhotoBoothSetupFragment} instance.
*/
public static PhotoBoothSetupFragment newInstance() {
return new PhotoBoothSetupFragment();
}
//
// Interfaces.
//
/**
* Callbacks for this fragment.
*/
public interface ICallbacks {
/**
* Setup of the photo booth has completed.
*/
void onPhotoBoothSetupCompleted();
}
}
| benhylau/flying-photo-booth | party-photo-booth/src/com/groundupworks/partyphotobooth/setup/fragments/PhotoBoothSetupFragment.java | Java | gpl-3.0 | 7,157 |
import React, { PropTypes } from 'react'
import classnames from 'classnames'
const SettingsPageMenuLayout = ({ children, title, className }) => (
<div
className={classnames(
'settings-page-menu-layout bg-white pt3 pr4 pl5 border-only-bottom border-gray94',
className
)}
>
<h1 className="h1 mt0 mb3">{title}</h1>
{children}
</div>
)
SettingsPageMenuLayout.propTypes = {
children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
className: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
title: PropTypes.string.isRequired
}
export default SettingsPageMenuLayout
| igr-santos/hub-client | app/components/Layout/SettingsPageMenuLayout.js | JavaScript | gpl-3.0 | 624 |
export default class FilesUploadHandler {
static isUploadEnabled( mediaType ) {
const unfilteredFilesTypes = [ 'svg', 'application/json' ];
if ( ! unfilteredFilesTypes.includes( mediaType ) ) {
return true;
}
return elementor.config.filesUpload.unfilteredFiles;
}
static setUploadTypeCaller( frame ) {
frame.uploader.uploader.param( 'uploadTypeCaller', 'elementor-wp-media-upload' );
}
static getUnfilteredFilesNotEnabledDialog( callback ) {
const onConfirm = () => {
elementorCommon.ajax.addRequest( 'enable_unfiltered_files_upload', {}, true );
elementor.config.filesUpload.unfilteredFiles = true;
callback();
};
return elementor.helpers.getSimpleDialog(
'e-enable-unfiltered-files-dialog',
__( 'Enable Unfiltered File Uploads', 'elementor' ),
__( 'Before you enable unfiltered files upload, note that this kind of files include a security risk. Elementor does run a process to remove possible malicious code, but there is still risk involved when using such files.', 'elementor' ),
__( 'Enable', 'elementor' ),
onConfirm
);
}
}
| pojome/elementor | assets/dev/js/editor/utils/files-upload-handler.js | JavaScript | gpl-3.0 | 1,087 |
'use superstrict';
try {
if ((-25 >> 3) === -4) {
'ok';
} else {
'fail';
}
} catch (e) {
}
| vacuumlabs/babel-plugin-superstrict | test/eval_tests/casting_signed_right_shift_numbers.js | JavaScript | gpl-3.0 | 106 |
# (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst.
# -*- coding: utf-8 -*-
"""Use AppConf to store sensible defaults for settings. This also documents the
settings that lizard_damage defines. Each setting name automatically has
"FLOODING_LIB_" prepended to it.
By puttng the AppConf in this module and importing the Django settings
here, it is possible to import Django's settings with `from flooding_lib.conf
import settings` and be certain that the AppConf
stuff has also been loaded."""
# Python 3 is coming
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import os
from django.conf import settings
settings # Pyflakes...
from appconf import AppConf
class MyAppConf(AppConf):
COLORMAP_DIR = os.path.join(
settings.FLOODING_SHARE, 'colormaps')
| lizardsystem/flooding | flooding_lib/conf.py | Python | gpl-3.0 | 875 |
package com.mucommander.share.impl.imgur;
import com.mucommander.commons.file.AbstractFile;
import com.mucommander.commons.file.FileFactory;
import com.mucommander.commons.file.util.FileSet;
import com.mucommander.share.impl.imgur.ImgurAPI.Callback;
import com.mucommander.text.Translator;
import com.mucommander.ui.dialog.file.ProgressDialog;
import com.mucommander.ui.main.MainFrame;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Future;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
*
* @author Mathias
*/
public class ImgurJobTest {
private ImgurAPI mockImgurAPI;
private ProgressDialog mockProgressDialog;
private MainFrame mockMainFrame;
private FileSet mockFiles;
private Future mockFuture;
private ImgurJob instance;
public ImgurJobTest() {
}
@BeforeClass
public void setUpClass() throws Exception {
//Uses localized strings
try {
Translator.init();
} catch (Exception e) {
throw new RuntimeException(e);
}
//Mock Future
mockFuture = mock(Future.class);
when(mockFuture.isDone()).thenReturn(true);
//Mock ImgurAPI
mockImgurAPI = mock(ImgurAPI.class);
when(mockImgurAPI.uploadAsync(any(File.class), any(Callback.class))).thenReturn(mockFuture);
//Mock ProgressDialog
mockProgressDialog = mock(ProgressDialog.class);
//Mock MainFrame
mockMainFrame = mock(MainFrame.class);
//Mock FileSet
mockFiles = mock(FileSet.class);
}
@BeforeMethod
public void setUpMethod() throws Exception {
instance = new ImgurJob(mockImgurAPI, mockProgressDialog, mockMainFrame, mockFiles);
}
/**
* Test of hasFolderChanged method, of class ImgurJob.
*/
@Test
public void testHasFolderChanged() {
System.out.println("hasFolderChanged");
AbstractFile folder = mock(AbstractFile.class);
boolean expResult = false;
boolean result = instance.hasFolderChanged(folder);
assertEquals(result, expResult);
}
@Test
public void successLocalFile() throws IOException {
File tmp = File.createTempFile("test", ".tmp");
tmp.deleteOnExit();
AbstractFile file = FileFactory.getFile(tmp.getAbsolutePath());
boolean result = instance.processFile(file, null);
boolean expResult = true;
assertEquals(result, expResult);
}
/**
* Test of getStatusString method, of class ImgurJob.
*/
@Test
public void testGetStatusString() {
System.out.println("getStatusString");
String status = instance.getStatusString();
assertNotNull(status);
assertTrue(!status.equals(""));
}
}
| raisercostin/mucommander | src/test/com/mucommander/share/impl/imgur/ImgurJobTest.java | Java | gpl-3.0 | 3,124 |
package edu.hucare.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.Set;
/**
* Created by Kuzon on 7/28/2016.
*/
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String email;
private String name;
private String password;
@OneToMany(mappedBy = "user")
private Set<ControlDevice> controlDevices;
@OneToMany(mappedBy = "user")
private Set<TerminalDevice> terminalDevices;
@OneToMany(mappedBy = "user")
private Set<Schedule> schedules;
public User() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@JsonIgnore
public Set<ControlDevice> getControlDevices() {
return controlDevices;
}
@JsonIgnore
public void setControlDevices(Set<ControlDevice> controlDevices) {
this.controlDevices = controlDevices;
}
@JsonIgnore
public Set<TerminalDevice> getTerminalDevices() {
return terminalDevices;
}
@JsonIgnore
public void setTerminalDevices(Set<TerminalDevice> terminalDevices) {
this.terminalDevices = terminalDevices;
}
@JsonIgnore
public Set<Schedule> getSchedules() {
return schedules;
}
@JsonIgnore
public void setSchedules(Set<Schedule> schedules) {
this.schedules = schedules;
}
}
| adalee-group/watering-system | server/schedule-service/src/main/java/edu/hucare/model/User.java | Java | gpl-3.0 | 1,897 |
/**
* Copyright 2013 hbz NRW (http://www.hbz-nrw.de/)
*
* This file is part of regal-drupal.
*
* regal-drupal 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.
*
* regal-drupal 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 regal-drupal. If not, see <http://www.gnu.org/licenses/>.
*/
(function($) {
var translations = {
}
/**
* Common behaviours
*/
Drupal.behaviors.edoweb = {
attach: function (context, settings) {
var home_href = Drupal.settings.basePath + 'resource';
if (document.location.pathname == home_href && '' != document.location.search) {
var query_params = [];
var all_params = document.location.search.substr(1).split('&');
$.each(all_params, function(i, param) {
if ('query[0][facets]' == param.substr(0, 16)) {
query_params.push(param);
}
});
if (query_params) {
sessionStorage.setItem('edoweb_search', '?' + query_params.join('&'));
}
} else if (document.location.pathname == home_href) {
sessionStorage.removeItem('edoweb_search');
}
if (search = sessionStorage.getItem('edoweb_search')) {
$('a[href="' + home_href + '"]').attr('href', home_href + search);
if ('resource' == Drupal.settings.edoweb.site_frontpage) {
$('a[href="/"]').attr('href', home_href + search);
}
}
/**
* Date parser for tablesort plugin
*/
$.tablesorter.addParser({
id: 'edowebDate',
is: function(s) {
return /^.*, /.test(s);
},
format: function(s, table, cell, cellIndex) {
return $(cell).closest('tr').attr('data-updated');
},
type: 'text'
});
/**
* Translations, these have to be defined here (i.e. in a behaviour)
* in order for Drupal.t to pick them up.
*/
translations['Add researchData'] = Drupal.t('Add researchData');
translations['Add monograph'] = Drupal.t('Add monograph');
translations['Add journal'] = Drupal.t('Add journal');
translations['Add volume'] = Drupal.t('Add volume');
translations['Add issue'] = Drupal.t('Add issue');
translations['Add article'] = Drupal.t('Add article');
translations['Add file'] = Drupal.t('Add file');
translations['Add part'] = Drupal.t('Add part');
translations['Add webpage'] = Drupal.t('Add webpage');
translations['Add version'] = Drupal.t('Add version');
}
}
/**
* Edoweb helper functions
*/
Drupal.edoweb = {
/**
* URI to CURIE
*/
compact_uri: function(uri) {
var namespaces = Drupal.settings.edoweb.namespaces;
for (prefix in namespaces) {
if (uri.indexOf(namespaces[prefix]) == 0) {
var local_part = uri.substring(namespaces[prefix].length);
return prefix + ':' + local_part;
}
}
return uri;
},
expand_curie: function(curie) {
var namespaces = Drupal.settings.edoweb.namespaces;
var curie_parts = curie.split(':');
for (prefix in namespaces) {
if (prefix == curie_parts[0]) {
return namespaces[prefix] + curie_parts[1];
}
}
},
t: function(string) {
if (string in translations) {
return translations[string];
} else {
return string;
}
},
/**
* Pending AJAX requests
*/
pending_requests: [],
/**
* Function loads a tabular view for a list of linked entities
*/
entity_table: function(field_items, operations, view_mode) {
view_mode = view_mode || 'default';
field_items.each(function() {
var container = $(this);
var curies = [];
container.find('a[data-curie]').each(function() {
curies.push(this.getAttribute('data-curie'));
});
var columns = container.find('a[data-target-bundle]')
.attr('data-target-bundle')
.split(' ')[0];
if (columns && curies.length > 0) {
container.siblings('table').remove();
var throbber = $('<div class="ajax-progress"><div class="throbber"> </div></div>')
container.before(throbber);
Drupal.edoweb.entity_list('edoweb_basic', curies, columns, view_mode).onload = function () {
if (this.status == 200) {
var result_table = $(this.responseText).find('table');
result_table.find('a[data-curie]').not('.resolved').not('.edoweb.download').each(function() {
Drupal.edoweb.entity_label($(this));
});
result_table.removeClass('sticky-enabled');
var updated_column = result_table.find('th[specifier="updated"]').index();
if (updated_column > -1) {
result_table.tablesorter({sortList: [[updated_column,1]]});
}
//TODO: check interference with tree navigation block
//Drupal.attachBehaviors(result_table);
container.find('div.field-item>a[data-curie]').each(function() {
if (! result_table.find('tr[data-curie="' + $(this).attr('data-curie') + '"]').length) {
var missing_entry = $(this).clone();
var row = $('<tr />');
result_table.find('thead').find('tr>th').each(function() {
row.append($('<td />'));
});
missing_entry.removeAttr('data-target-bundle');
row.find('td:eq(0)').append(missing_entry);
row.find('td:eq(1)').append(missing_entry.attr('data-curie'));
//FIXME: how to deal with this with configurable columns?
result_table.append(row);
}
});
container.hide();
container.after(result_table);
for (label in operations) {
operations[label](result_table);
}
Drupal.edoweb.last_modified_label(result_table);
Drupal.edoweb.hideEmptyTableColumns(result_table);
Drupal.edoweb.hideTableHeaders(result_table);
}
throbber.remove();
};
}
});
},
/**
* Function loads a tabular view for a list of linked entities
*/
entity_table_detail: function(field_items, operations, view_mode) {
view_mode = 'default';
field_items.each(function() {
var container = $(this);
var curies = [];
container.find('a[data-curie]').each(function() {
curies.push(this.getAttribute('data-curie'));
});
var columns = container.find('a[data-target-bundle]')
.attr('data-target-bundle')
.split(' ')[0];
if (columns && curies.length > 0) {
container.siblings('table').remove();
var throbber = $('<div class="ajax-progress"><div class="throbber"> </div></div>')
container.before(throbber);
Drupal.edoweb.entity_list_detail('edoweb_basic', curies, columns, view_mode).onload = function () {
if (this.status == 200) {
result_table = $(this.responseText).find('table');
result_table.find('a[data-curie]').not('.resolved').not('.edoweb.download').each(function() {
Drupal.edoweb.entity_label($(this));
});
result_table.removeClass('sticky-enabled');
var updated_column = result_table.find('th[specifier="updated"]').index();
if (updated_column > -1) {
result_table.tablesorter({sortList: [[updated_column,1]]});
}
//TODO: check interference with tree navigation block
//Drupal.attachBehaviors(result_table);
container.find('div.field-item>a[data-curie]').each(function() {
if (! result_table.find('tr[data-curie="' + $(this).attr('data-curie') + '"]').length) {
var missing_entry = $(this).clone();
var row = $('<tr />');
result_table.find('thead').find('tr>th').each(function() {
row.append($('<td />'));
});
missing_entry.removeAttr('data-target-bundle');
row.find('td:eq(0)').append(missing_entry);
row.find('td:eq(1)').append(missing_entry.attr('data-curie'));
//FIXME: how to deal with this with configurable columns?
result_table.append(row);
}
});
container.hide();
container.after(result_table);
container.after("<br/>");
for (label in operations) {
operations[label](result_table);
}
Drupal.edoweb.last_modified_label(result_table);
Drupal.edoweb.hideEmptyTableColumns(result_table);
Drupal.edoweb.hideTableHeaders(result_table);
}
throbber.remove();
};
}
});
},
/**
* Function returns an entities label.
*/
entity_label: function(element) {
var entity_type = 'edoweb_basic';
var entity_id = element.attr('data-curie');
if (cached_label = sessionStorage.getItem(entity_id)) {
element.text(cached_label);
} else {
$.get(Drupal.settings.basePath + 'edoweb_entity_label/' + entity_type + '/' + entity_id).onload = function() {
var label = this.status == 200 ? this.responseText : entity_id;
if (this.status == 200) {
sessionStorage.setItem(entity_id, label);
}
element.text(label);
element.addClass('resolved');
};
}
},
/**
* Function returns a list of entities.
*/
entity_list: function(entity_type, entity_curies, columns, view_mode) {
return $.get(Drupal.settings.basePath
+ 'edoweb_entity_list/'
+ entity_type
+ '/' + view_mode
+ '?' + $.param({'ids': entity_curies, 'columns': columns})
);
},
/**
* Function returns a list of entities.
*/
entity_list_detail: function(entity_type, entity_curies, columns, view_mode) {
return $.get(Drupal.settings.basePath
+ 'edoweb_entity_list_detail/'
+ entity_type
+ '/' + view_mode
+ '?' + $.param({'ids': entity_curies, 'columns': columns})
);
},
last_modified_label: function(container) {
$('a.edoweb.lastmodified', container).each(function() {
var link = $(this);
$.get(link.attr('href'), function(data) {
link.replaceWith($(data));
});
});
},
/**
* Hides table columns that do not contain any data
*/
hideEmptyTableColumns: function(table) {
// Hide table columns that do not contain any data
table.find('th').each(function(i) {
var remove = 0;
var tds = $(this).parents('table').find('tr td:nth-child(' + (i + 1) + ')')
tds.each(function(j) { if ($(this).text() == '') remove++; });
if (remove == (table.find('tr').length - 1)) {
$(this).hide();
tds.hide();
}
});
},
/**
* Hide the th of a table
*/
hideTableHeaders: function(table) {
if (!(table.parent().hasClass('field-name-field-edoweb-struct-child'))
&& !(table.hasClass('sticky-enabled'))
&& !(table.closest('form').length))
{
table.find('thead').hide();
}
},
blockUIMessage: {
message: '<div class="ajax-progress"><div class="throbber"> </div></div> Bitte warten...'
}
}
// AJAX navigation, if possible
if (window.history && history.pushState) {
Drupal.edoweb.navigateTo = function(href) {
var throbber = $('<div class="ajax-progress"><div class="throbber"> </div></div>');
$('#content').html(throbber);
$.ajax({
url: href,
complete: function(xmlHttp, status) {
throbber.remove();
var html = $(xmlHttp.response);
Drupal.attachBehaviors(html);
$('#content').replaceWith(html.find('#content'));
$('#breadcrumb').replaceWith(html.find('#breadcrumb'));
if ($('#messages').length) {
$('#messages').replaceWith(html.find('#messages'));
} else {
$('#header').after(html.find('#messages'));
}
document.title = html.filter('title').text();
$('.edoweb-tree li.active').removeClass('active');
$('.edoweb-tree li>a[href="' + location.pathname + '"]').closest('li').addClass('active');
}
});
};
if (!this.attached) {
history.replaceState({tree: true}, null, document.location);
window.addEventListener("popstate", function(e) {
if (e.state && e.state.tree) {
Drupal.edoweb.navigateTo(location.pathname);
if (Drupal.edoweb.refreshTree) {
Drupal.edoweb.refreshTree();
}
}
});
this.attached = true;
}
} else {
Drupal.edoweb.navigateTo = function(href) {
window.location = href;
};
}
})(jQuery);
| jschnasse/regal-drupal | edoweb/js/edoweb.js | JavaScript | gpl-3.0 | 13,745 |
/*
This file is part of Cute Chess.
Copyright (C) 2008-2018 Cute Chess authors
Cute Chess 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.
Cute Chess 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 Cute Chess. If not, see <http://www.gnu.org/licenses/>.
*/
#include "sprt.h"
#include <cmath>
#include <QtGlobal>
class BayesElo;
class SprtProbability;
class BayesElo
{
public:
BayesElo(double bayesElo, double drawElo);
BayesElo(const SprtProbability& p);
double bayesElo() const;
double drawElo() const;
double scale() const;
private:
double m_bayesElo;
double m_drawElo;
};
class SprtProbability
{
public:
SprtProbability(int wins, int losses, int draws);
SprtProbability(const BayesElo& b);
bool isValid() const;
double pWin() const;
double pLoss() const;
double pDraw() const;
private:
double m_pWin;
double m_pLoss;
double m_pDraw;
};
BayesElo::BayesElo(double bayesElo, double drawElo)
: m_bayesElo(bayesElo),
m_drawElo(drawElo)
{
}
BayesElo::BayesElo(const SprtProbability& p)
{
Q_ASSERT(p.isValid());
m_bayesElo = 200.0 * std::log10(p.pWin() / p.pLoss() *
(1.0 - p.pLoss()) / (1.0 - p.pWin()));
m_drawElo = 200.0 * std::log10((1.0 - p.pLoss()) / p.pLoss() *
(1.0 - p.pWin()) / p.pWin());
}
double BayesElo::bayesElo() const
{
return m_bayesElo;
}
double BayesElo::drawElo() const
{
return m_drawElo;
}
double BayesElo::scale() const
{
const double x = std::pow(10.0, -m_drawElo / 400.0);
return 4.0 * x / ((1.0 + x) * (1.0 + x));
}
SprtProbability::SprtProbability(int wins, int losses, int draws)
{
Q_ASSERT(wins > 0 && losses > 0 && draws > 0);
const int count = wins + losses + draws;
m_pWin = double(wins) / count;
m_pLoss = double(losses) / count;
m_pDraw = 1.0 - m_pWin - m_pLoss;
}
SprtProbability::SprtProbability(const BayesElo& b)
{
m_pWin = 1.0 / (1.0 + std::pow(10.0, (b.drawElo() - b.bayesElo()) / 400.0));
m_pLoss = 1.0 / (1.0 + std::pow(10.0, (b.drawElo() + b.bayesElo()) / 400.0));
m_pDraw = 1.0 - m_pWin - m_pLoss;
}
bool SprtProbability::isValid() const
{
return 0.0 < m_pWin && m_pWin < 1.0 &&
0.0 < m_pLoss && m_pLoss < 1.0 &&
0.0 < m_pDraw && m_pDraw < 1.0;
}
double SprtProbability::pWin() const
{
return m_pWin;
}
double SprtProbability::pLoss() const
{
return m_pLoss;
}
double SprtProbability::pDraw() const
{
return m_pDraw;
}
Sprt::Sprt()
: m_elo0(0),
m_elo1(0),
m_alpha(0),
m_beta(0),
m_wins(0),
m_losses(0),
m_draws(0)
{
}
bool Sprt::isNull() const
{
return m_elo0 == 0 && m_elo1 == 0 && m_alpha == 0 && m_beta == 0;
}
void Sprt::initialize(double elo0, double elo1,
double alpha, double beta)
{
m_elo0 = elo0;
m_elo1 = elo1;
m_alpha = alpha;
m_beta = beta;
}
Sprt::Status Sprt::status() const
{
Status status = {
Continue,
0.0,
0.0,
0.0
};
if (m_wins <= 0 || m_losses <= 0 || m_draws <= 0)
return status;
// Estimate draw_elo out of sample
const SprtProbability p(m_wins, m_losses, m_draws);
const BayesElo b(p);
// Probability laws under H0 and H1
const double s = b.scale();
const BayesElo b0(m_elo0 / s, b.drawElo());
const BayesElo b1(m_elo1 / s, b.drawElo());
const SprtProbability p0(b0), p1(b1);
// Log-Likelyhood Ratio
status.llr = m_wins * std::log(p1.pWin() / p0.pWin()) +
m_losses * std::log(p1.pLoss() / p0.pLoss()) +
m_draws * std::log(p1.pDraw() / p0.pDraw());
// Bounds based on error levels of the test
status.lBound = std::log(m_beta / (1.0 - m_alpha));
status.uBound = std::log((1.0 - m_beta) / m_alpha);
if (status.llr > status.uBound)
status.result = AcceptH1;
else if (status.llr < status.lBound)
status.result = AcceptH0;
return status;
}
void Sprt::addGameResult(GameResult result)
{
if (result == Win)
m_wins++;
else if (result == Draw)
m_draws++;
else if (result == Loss)
m_losses++;
}
| joergoster/cutechess | projects/lib/src/sprt.cpp | C++ | gpl-3.0 | 4,340 |
/*
* Copyright (c) 2018 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
mica.contact
.factory('ContactsSearchResource', ['$resource', 'ContactSerializationService',
function ($resource, ContactSerializationService) {
return $resource(contextPath + '/ws/draft/persons/_search?', {}, {
'search': {
method: 'GET',
params: {query: '@query', 'exclude': '@exclude'},
transformResponse: ContactSerializationService.deserializeList,
errorHandler: true
}
});
}])
.factory('PersonResource', ['$resource', function ($resource) {
return $resource(contextPath + '/ws/draft/person/:id', {}, {
'get': {method: 'GET', params: {id: '@id'}},
'update': {method: 'PUT', params: {id: '@id'}},
'delete': {method: 'DELETE', params: {id: '@id'}},
'create': {url: contextPath + '/ws/draft/persons', method: 'POST'},
'getStudyMemberships': {url: contextPath + '/ws/draft/persons/study/:studyId', method: 'GET', isArray: true, params: {studyId: '@studyId'}},
'getNetworkMemberships': {url: contextPath + '/ws/draft/persons/network/:networkId', method: 'GET', isArray: true, params: {networkId: '@networkId'}}
});
}])
.factory('ContactSerializationService', ['LocalizedValues',
function (LocalizedValues) {
var it = this;
this.serialize = function(person) {
if (person.institution) {
person.institution.name = LocalizedValues.objectToArray(person.institution.name);
person.institution.department = LocalizedValues.objectToArray(person.institution.department);
if (person.institution.address) {
person.institution.address.street = LocalizedValues.objectToArray(person.institution.address.street);
person.institution.address.city = LocalizedValues.objectToArray(person.institution.address.city);
if (person.institution.address.country) {
person.institution.address.country = {'iso': person.institution.address.country};
}
}
}
return person;
};
this.deserializeList = function (personsList) {
personsList = angular.fromJson(personsList);
if (personsList.persons) {
personsList.persons = personsList.persons.map(function (person) {
return it.deserialize(person);
});
}
return personsList;
};
this.deserialize = function(person) {
person = angular.copy(person);
if (person.institution) {
person.institution.name = LocalizedValues.arrayToObject(person.institution.name);
person.institution.department = LocalizedValues.arrayToObject(person.institution.department);
if (person.institution.address) {
person.institution.address.street = LocalizedValues.arrayToObject(person.institution.address.street);
person.institution.address.city = LocalizedValues.arrayToObject(person.institution.address.city);
if (person.institution.address.country) {
person.institution.address.country = person.institution.address.country.iso;
}
}
}
return person;
};
return this;
}]);
| obiba/mica2 | mica-webapp/src/main/webapp/app/contact/contact-service.js | JavaScript | gpl-3.0 | 3,513 |
# -*- coding: utf-8 -*-
"""
<license>
CSPLN_MaryKeelerEdition; Manages images to which notes can be added.
Copyright (C) 2015, Thomas Kercheval
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/>.
___________________________________________________________</license>
Description:
Updates README.txt file in the specified directory.
Inputs:
Functions that are in the specified directory.
discover_functions() detects them automatically.
Outputs:
README.txt file, with Scope&&Details listed.
Covers functions in specified directory.
Currently:
To Do:
Done:
Update readme file with current functions&&their docstrings.
"""
import os
def discover_functions(directory):
"""Discorvers python modules in current directory."""
function_names = []
curr_dir = os.listdir(directory)
for name in curr_dir:
if name[-3:] == '.py':
function_names.append(str(name))
return function_names
def grab_docstrings(directory):
""""Grabs the docstrings of all python modules specified."""
import ast
docstrings = {}
for name in discover_functions(directory):
path_name = os.path.join(directory, name)
thing = ast.parse(''.join(open(path_name)))
docstring = ast.get_docstring(thing)
docstrings[name] = docstring
return docstrings
def create_readme(doc_dic, directory):
"""Strips off license statement, formats readme, returns readme text."""
end_lisence = "</license>"
scope = '''Scope:
{}'''
details = '''Details:{}'''
scopelist = []
detaillist = []
scopestuff = ''
detailstuff = ''
# Now to create the contents of the README...
for script in doc_dic.keys().sort():
print " Creating readme entry for: {}...".format(script)
if doc_dic[script] == None:
print " But it has no docstring..."
continue
scopelist.append(script+'\n ')
docstring = doc_dic[script].replace('\n', '\n ')
doc_index = docstring.find(end_lisence) + 11
# Stripping off the license in the docstring...
docstring = docstring[doc_index:]
detaillist.append('\n\n'+script+'\n')
detaillist.append(' '+docstring)
for item in scopelist:
scopestuff += item
for ano_item in detaillist:
detailstuff += ano_item
# Now to put the contents in their correct place...
readme = (scope.format(scopestuff[:-4]) + '\n'
+ details.format(detailstuff) + '\n')
# And write the README in its directory...
write_readme(readme, directory)
return None
def write_readme(r_text, directory):
"""Writes the readme!"""
readme_path = os.path.join(directory, 'subreadme.txt')
with open(readme_path, 'w') as readme:
readme.write(r_text)
return None
def update_readme(directory):
"""Updates the readme everytime this script is called."""
documentation_dict = grab_docstrings(directory)
create_readme(documentation_dict, directory)
return None
if __name__ == "__main__":
CURR_DIR = os.path.abspath(os.path.dirname(__file__))
update_readme(CURR_DIR)
| jjs0sbw/CSPLN | test/update_test_subreadme.py | Python | gpl-3.0 | 3,717 |
package org.labcrypto.edusys.domain.jpa.dao.membership;
import org.labcrypto.edusys.domain.jpa.dao.EntityDao;
import org.labcrypto.edusys.domain.jpa.entity.membership.Token;
public interface TokenDao extends EntityDao<Token> {
Token getLatestActiveToken(Long userId);
Token getTokenByValue(String tokenValue);
}
| ckpp/edusys | src/edusys/domain/src/main/java/org/labcrypto/edusys/domain/jpa/dao/membership/TokenDao.java | Java | gpl-3.0 | 324 |
/**
* Marlin 3D Printer Firmware
* Copyright (C) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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/>.
*
*/
#include "../../../inc/MarlinConfig.h"
#if HAS_TRINAMIC
#include "../../gcode.h"
#include "../../../feature/tmc_util.h"
#include "../../../module/stepper_indirection.h"
#include "../../../module/planner.h"
#include "../../queue.h"
#if ENABLED(MONITOR_DRIVER_STATUS)
#define M91x_USE(ST) (AXIS_DRIVER_TYPE(ST, TMC2130) || AXIS_DRIVER_TYPE(ST, TMC2160) || AXIS_DRIVER_TYPE(ST, TMC2208) || AXIS_DRIVER_TYPE(ST, TMC2660) || AXIS_DRIVER_TYPE(ST, TMC5130) || AXIS_DRIVER_TYPE(ST, TMC5160))
#define M91x_USE_E(N) (E_STEPPERS > N && M91x_USE(E##N))
#define M91x_SOME_X (M91x_USE(X) || M91x_USE(X2))
#define M91x_SOME_Y (M91x_USE(Y) || M91x_USE(Y2))
#define M91x_SOME_Z (M91x_USE(Z) || M91x_USE(Z2) || M91x_USE(Z3))
#define M91x_SOME_E (M91x_USE_E(0) || M91x_USE_E(1) || M91x_USE_E(2) || M91x_USE_E(3) || M91x_USE_E(4) || M91x_USE_E(5))
#if !M91x_SOME_X && !M91x_SOME_Y && !M91x_SOME_Z && !M91x_SOME_E
#error "MONITOR_DRIVER_STATUS requires at least one TMC2130, TMC2208, or TMC2660."
#endif
/**
* M911: Report TMC stepper driver overtemperature pre-warn flag
* This flag is held by the library, persisting until cleared by M912
*/
void GcodeSuite::M911() {
#if M91x_USE(X)
tmc_report_otpw(stepperX);
#endif
#if M91x_USE(X2)
tmc_report_otpw(stepperX2);
#endif
#if M91x_USE(Y)
tmc_report_otpw(stepperY);
#endif
#if M91x_USE(Y2)
tmc_report_otpw(stepperY2);
#endif
#if M91x_USE(Z)
tmc_report_otpw(stepperZ);
#endif
#if M91x_USE(Z2)
tmc_report_otpw(stepperZ2);
#endif
#if M91x_USE(Z3)
tmc_report_otpw(stepperZ3);
#endif
#if M91x_USE_E(0)
tmc_report_otpw(stepperE0);
#endif
#if M91x_USE_E(1)
tmc_report_otpw(stepperE1);
#endif
#if M91x_USE_E(2)
tmc_report_otpw(stepperE2);
#endif
#if M91x_USE_E(3)
tmc_report_otpw(stepperE3);
#endif
#if M91x_USE_E(4)
tmc_report_otpw(stepperE4);
#endif
#if M91x_USE_E(5)
tmc_report_otpw(stepperE5);
#endif
}
/**
* M912: Clear TMC stepper driver overtemperature pre-warn flag held by the library
* Specify one or more axes with X, Y, Z, X1, Y1, Z1, X2, Y2, Z2, Z3 and E[index].
* If no axes are given, clear all.
*
* Examples:
* M912 X ; clear X and X2
* M912 X1 ; clear X1 only
* M912 X2 ; clear X2 only
* M912 X E ; clear X, X2, and all E
* M912 E1 ; clear E1 only
*/
void GcodeSuite::M912() {
#if M91x_SOME_X
const bool hasX = parser.seen(axis_codes[X_AXIS]);
#else
constexpr bool hasX = false;
#endif
#if M91x_SOME_Y
const bool hasY = parser.seen(axis_codes[Y_AXIS]);
#else
constexpr bool hasY = false;
#endif
#if M91x_SOME_Z
const bool hasZ = parser.seen(axis_codes[Z_AXIS]);
#else
constexpr bool hasZ = false;
#endif
#if M91x_SOME_E
const bool hasE = parser.seen(axis_codes[E_AXIS]);
#else
constexpr bool hasE = false;
#endif
const bool hasNone = !hasX && !hasY && !hasZ && !hasE;
#if M91x_SOME_X
const int8_t xval = int8_t(parser.byteval(axis_codes[X_AXIS], 0xFF));
#if M91x_USE(X)
if (hasNone || xval == 1 || (hasX && xval < 0)) tmc_clear_otpw(stepperX);
#endif
#if M91x_USE(X2)
if (hasNone || xval == 2 || (hasX && xval < 0)) tmc_clear_otpw(stepperX2);
#endif
#endif
#if M91x_SOME_Y
const int8_t yval = int8_t(parser.byteval(axis_codes[Y_AXIS], 0xFF));
#if M91x_USE(Y)
if (hasNone || yval == 1 || (hasY && yval < 0)) tmc_clear_otpw(stepperY);
#endif
#if M91x_USE(Y2)
if (hasNone || yval == 2 || (hasY && yval < 0)) tmc_clear_otpw(stepperY2);
#endif
#endif
#if M91x_SOME_Z
const int8_t zval = int8_t(parser.byteval(axis_codes[Z_AXIS], 0xFF));
#if M91x_USE(Z)
if (hasNone || zval == 1 || (hasZ && zval < 0)) tmc_clear_otpw(stepperZ);
#endif
#if M91x_USE(Z2)
if (hasNone || zval == 2 || (hasZ && zval < 0)) tmc_clear_otpw(stepperZ2);
#endif
#if M91x_USE(Z3)
if (hasNone || zval == 3 || (hasZ && zval < 0)) tmc_clear_otpw(stepperZ3);
#endif
#endif
#if M91x_SOME_E
const int8_t eval = int8_t(parser.byteval(axis_codes[E_AXIS], 0xFF));
#if M91x_USE_E(0)
if (hasNone || eval == 0 || (hasE && eval < 0)) tmc_clear_otpw(stepperE0);
#endif
#if M91x_USE_E(1)
if (hasNone || eval == 1 || (hasE && eval < 0)) tmc_clear_otpw(stepperE1);
#endif
#if M91x_USE_E(2)
if (hasNone || eval == 2 || (hasE && eval < 0)) tmc_clear_otpw(stepperE2);
#endif
#if M91x_USE_E(3)
if (hasNone || eval == 3 || (hasE && eval < 0)) tmc_clear_otpw(stepperE3);
#endif
#if M91x_USE_E(4)
if (hasNone || eval == 4 || (hasE && eval < 0)) tmc_clear_otpw(stepperE4);
#endif
#if M91x_USE_E(5)
if (hasNone || eval == 5 || (hasE && eval < 0)) tmc_clear_otpw(stepperE5);
#endif
#endif
}
#endif // MONITOR_DRIVER_STATUS
/**
* M913: Set HYBRID_THRESHOLD speed.
*/
#if ENABLED(HYBRID_THRESHOLD)
void GcodeSuite::M913() {
#define TMC_SAY_PWMTHRS(A,Q) tmc_print_pwmthrs(stepper##Q)
#define TMC_SET_PWMTHRS(A,Q) stepper##Q.set_pwm_thrs(value)
#define TMC_SAY_PWMTHRS_E(E) tmc_print_pwmthrs(stepperE##E)
#define TMC_SET_PWMTHRS_E(E) stepperE##E.set_pwm_thrs(value)
bool report = true;
#if AXIS_IS_TMC(X) || AXIS_IS_TMC(X2) || AXIS_IS_TMC(Y) || AXIS_IS_TMC(Y2) || AXIS_IS_TMC(Z) || AXIS_IS_TMC(Z2) || AXIS_IS_TMC(Z3)
const uint8_t index = parser.byteval('I');
#endif
LOOP_XYZE(i) if (int32_t value = parser.longval(axis_codes[i])) {
report = false;
switch (i) {
case X_AXIS:
#if AXIS_HAS_STEALTHCHOP(X)
if (index < 2) TMC_SET_PWMTHRS(X,X);
#endif
#if AXIS_HAS_STEALTHCHOP(X2)
if (!(index & 1)) TMC_SET_PWMTHRS(X,X2);
#endif
break;
case Y_AXIS:
#if AXIS_HAS_STEALTHCHOP(Y)
if (index < 2) TMC_SET_PWMTHRS(Y,Y);
#endif
#if AXIS_HAS_STEALTHCHOP(Y2)
if (!(index & 1)) TMC_SET_PWMTHRS(Y,Y2);
#endif
break;
case Z_AXIS:
#if AXIS_HAS_STEALTHCHOP(Z)
if (index < 2) TMC_SET_PWMTHRS(Z,Z);
#endif
#if AXIS_HAS_STEALTHCHOP(Z2)
if (index == 0 || index == 2) TMC_SET_PWMTHRS(Z,Z2);
#endif
#if AXIS_HAS_STEALTHCHOP(Z3)
if (index == 0 || index == 3) TMC_SET_PWMTHRS(Z,Z3);
#endif
break;
case E_AXIS: {
#if E_STEPPERS
const int8_t target_extruder = get_target_extruder_from_command();
if (target_extruder < 0) return;
switch (target_extruder) {
#if AXIS_HAS_STEALTHCHOP(E0)
case 0: TMC_SET_PWMTHRS_E(0); break;
#endif
#if E_STEPPERS > 1 && AXIS_HAS_STEALTHCHOP(E1)
case 1: TMC_SET_PWMTHRS_E(1); break;
#endif
#if E_STEPPERS > 2 && AXIS_HAS_STEALTHCHOP(E2)
case 2: TMC_SET_PWMTHRS_E(2); break;
#endif
#if E_STEPPERS > 3 && AXIS_HAS_STEALTHCHOP(E3)
case 3: TMC_SET_PWMTHRS_E(3); break;
#endif
#if E_STEPPERS > 4 && AXIS_HAS_STEALTHCHOP(E4)
case 4: TMC_SET_PWMTHRS_E(4); break;
#endif
#if E_STEPPERS > 5 && AXIS_HAS_STEALTHCHOP(E5)
case 5: TMC_SET_PWMTHRS_E(5); break;
#endif
}
#endif // E_STEPPERS
} break;
}
}
if (report) {
#if AXIS_HAS_STEALTHCHOP(X)
TMC_SAY_PWMTHRS(X,X);
#endif
#if AXIS_HAS_STEALTHCHOP(X2)
TMC_SAY_PWMTHRS(X,X2);
#endif
#if AXIS_HAS_STEALTHCHOP(Y)
TMC_SAY_PWMTHRS(Y,Y);
#endif
#if AXIS_HAS_STEALTHCHOP(Y2)
TMC_SAY_PWMTHRS(Y,Y2);
#endif
#if AXIS_HAS_STEALTHCHOP(Z)
TMC_SAY_PWMTHRS(Z,Z);
#endif
#if AXIS_HAS_STEALTHCHOP(Z2)
TMC_SAY_PWMTHRS(Z,Z2);
#endif
#if AXIS_HAS_STEALTHCHOP(Z3)
TMC_SAY_PWMTHRS(Z,Z3);
#endif
#if E_STEPPERS && AXIS_HAS_STEALTHCHOP(E0)
TMC_SAY_PWMTHRS_E(0);
#endif
#if E_STEPPERS > 1 && AXIS_HAS_STEALTHCHOP(E1)
TMC_SAY_PWMTHRS_E(1);
#endif
#if E_STEPPERS > 2 && AXIS_HAS_STEALTHCHOP(E2)
TMC_SAY_PWMTHRS_E(2);
#endif
#if E_STEPPERS > 3 && AXIS_HAS_STEALTHCHOP(E3)
TMC_SAY_PWMTHRS_E(3);
#endif
#if E_STEPPERS > 4 && AXIS_HAS_STEALTHCHOP(E4)
TMC_SAY_PWMTHRS_E(4);
#endif
#if E_STEPPERS > 5 && AXIS_HAS_STEALTHCHOP(E5)
TMC_SAY_PWMTHRS_E(5);
#endif
}
}
#endif // HYBRID_THRESHOLD
/**
* M914: Set StallGuard sensitivity.
*/
#if USE_SENSORLESS
void GcodeSuite::M914() {
bool report = true;
const uint8_t index = parser.byteval('I');
LOOP_XYZ(i) if (parser.seen(axis_codes[i])) {
const int8_t value = (int8_t)constrain(parser.value_int(), -64, 63);
report = false;
switch (i) {
#if X_SENSORLESS
case X_AXIS:
#if AXIS_HAS_STALLGUARD(X)
if (index < 2) stepperX.sgt(value);
#endif
#if AXIS_HAS_STALLGUARD(X2)
if (!(index & 1)) stepperX2.sgt(value);
#endif
break;
#endif
#if Y_SENSORLESS
case Y_AXIS:
#if AXIS_HAS_STALLGUARD(Y)
if (index < 2) stepperY.sgt(value);
#endif
#if AXIS_HAS_STALLGUARD(Y2)
if (!(index & 1)) stepperY2.sgt(value);
#endif
break;
#endif
#if Z_SENSORLESS
case Z_AXIS:
#if AXIS_HAS_STALLGUARD(Z)
if (index < 2) stepperZ.sgt(value);
#endif
#if AXIS_HAS_STALLGUARD(Z2)
if (index == 0 || index == 2) stepperZ2.sgt(value);
#endif
#if AXIS_HAS_STALLGUARD(Z3)
if (index == 0 || index == 3) stepperZ3.sgt(value);
#endif
break;
#endif
}
}
if (report) {
#if X_SENSORLESS
#if AXIS_HAS_STALLGUARD(X)
tmc_print_sgt(stepperX);
#endif
#if AXIS_HAS_STALLGUARD(X2)
tmc_print_sgt(stepperX2);
#endif
#endif
#if Y_SENSORLESS
#if AXIS_HAS_STALLGUARD(Y)
tmc_print_sgt(stepperY);
#endif
#if AXIS_HAS_STALLGUARD(Y2)
tmc_print_sgt(stepperY2);
#endif
#endif
#if Z_SENSORLESS
#if AXIS_HAS_STALLGUARD(Z)
tmc_print_sgt(stepperZ);
#endif
#if AXIS_HAS_STALLGUARD(Z2)
tmc_print_sgt(stepperZ2);
#endif
#if AXIS_HAS_STALLGUARD(Z3)
tmc_print_sgt(stepperZ3);
#endif
#endif
}
}
#endif // USE_SENSORLESS
#endif // HAS_TRINAMIC
| teemuatlut/Marlin | Marlin/src/gcode/feature/trinamic/M911-M914.cpp | C++ | gpl-3.0 | 12,013 |
<?php
/* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
* Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
* Copyright (C) 2005-2015 Regis Houssin <regis.houssin@capnetworks.com>
* Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
* Copyright (C) 2010-2012 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2012 Christophe Battarel <christophe.battarel@altairis.fr>
* Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
* Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
* Copyright (C) 2015-2016 Ferran Marcet <fmarcet@2byte.es>
*
* 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/>.
*/
/**
* \file htdocs/compta/facture/list.php
* \ingroup facture
* \brief Page to create/see an invoice
*/
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
if (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
if (! empty($conf->projet->enabled))
{
require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
}
$langs->load('bills');
$langs->load('companies');
$langs->load('products');
$langs->load('main');
$sall=trim(GETPOST('sall'));
$projectid=(GETPOST('projectid')?GETPOST('projectid','int'):0);
$id=(GETPOST('id','int')?GETPOST('id','int'):GETPOST('facid','int')); // For backward compatibility
$ref=GETPOST('ref','alpha');
$socid=GETPOST('socid','int');
$action=GETPOST('action','alpha');
$massaction=GETPOST('massaction','alpha');
$confirm=GETPOST('confirm','alpha');
$lineid=GETPOST('lineid','int');
$userid=GETPOST('userid','int');
$search_product_category=GETPOST('search_product_category','int');
$search_ref=GETPOST('sf_ref')?GETPOST('sf_ref','alpha'):GETPOST('search_ref','alpha');
$search_refcustomer=GETPOST('search_refcustomer','alpha');
$search_societe=GETPOST('search_societe','alpha');
$search_montant_ht=GETPOST('search_montant_ht','alpha');
$search_montant_ttc=GETPOST('search_montant_ttc','alpha');
$search_status=GETPOST('search_status','int');
$search_paymentmode=GETPOST('search_paymentmode','int');
$option = GETPOST('option');
if ($option == 'late') $filter = 'paye:0';
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$limit = GETPOST('limit')?GETPOST('limit','int'):$conf->liste_limit;
$page = GETPOST("page",'int');
if ($page == -1) {
$page = 0;
}
$offset = $limit * $page;
if (! $sortorder && ! empty($conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER) && $search_status == 1) $sortorder=$conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER;
if (! $sortorder) $sortorder='DESC';
if (! $sortfield) $sortfield='f.datef';
$pageprev = $page - 1;
$pagenext = $page + 1;
$search_user = GETPOST('search_user','int');
$search_sale = GETPOST('search_sale','int');
$day = GETPOST('day','int');
$month = GETPOST('month','int');
$year = GETPOST('year','int');
$day_lim = GETPOST('day_lim','int');
$month_lim = GETPOST('month_lim','int');
$year_lim = GETPOST('year_lim','int');
$filtre = GETPOST('filtre');
$toselect = GETPOST('toselect', 'array');
// Security check
$fieldid = (! empty($ref)?'facnumber':'rowid');
if (! empty($user->societe_id)) $socid=$user->societe_id;
$result = restrictedArea($user, 'facture', $id,'','','fk_soc',$fieldid);
$object=new Facture($db);
// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
$hookmanager->initHooks(array('invoicelist'));
$now=dol_now();
// List of fields to search into when doing a "search in all"
$fieldstosearchall = array(
'f.facnumber'=>'Ref',
'f.ref_client'=>'RefCustomer',
'fd.description'=>'Description',
's.nom'=>"ThirdParty",
'f.note_public'=>'NotePublic',
);
if (empty($user->socid)) $fieldstosearchall["f.note_private"]="NotePrivate";
/*
* Actions
*/
if (GETPOST('cancel')) { $action='list'; $massaction=''; }
$parameters=array('socid'=>$socid);
$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
if (empty($reshook))
{
// Mass actions
if (! empty($massaction) && count($toselect) < 1)
{
$error++;
setEventMessages($langs->trans("NoLineChecked"), null, "warnings");
}
if (! $error && $massaction == 'confirm_presend')
{
$resaction = '';
$nbsent = 0;
$nbignored = 0;
$langs->load("mails");
include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
if (!isset($user->email))
{
$error++;
setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
}
if (! $error)
{
$thirdparty=new Societe($db);
$objecttmp=new Facture($db);
$listofobjectid=array();
$listofobjectthirdparties=array();
$listofobjectref=array();
foreach($toselect as $toselectid)
{
$objecttmp=new Facture($db); // must create new instance because instance is saved into $listofobjectref array for future use
$result=$objecttmp->fetch($toselectid);
if ($result > 0)
{
$listoinvoicesid[$toselectid]=$toselectid;
$thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid;
$listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
$listofobjectref[$thirdpartyid][$toselectid]=$objecttmp;
}
}
//var_dump($listofobjectthirdparties);exit;
foreach ($listofobjectthirdparties as $thirdpartyid)
{
$result = $thirdparty->fetch($thirdpartyid);
if ($result < 0)
{
dol_print_error($db);
exit;
}
// Define recipient $sendto and $sendtocc
if (trim($_POST['sendto']))
{
// Recipient is provided into free text
$sendto = trim($_POST['sendto']);
$sendtoid = 0;
}
elseif ($_POST['receiver'] != '-1')
{
// Recipient was provided from combo list
if ($_POST['receiver'] == 'thirdparty') // Id of third party
{
$sendto = $thirdparty->email;
$sendtoid = 0;
}
else // Id du contact
{
$sendto = $thirdparty->contact_get_property((int) $_POST['receiver'],'email');
$sendtoid = $_POST['receiver'];
}
}
if (trim($_POST['sendtocc']))
{
$sendtocc = trim($_POST['sendtocc']);
}
elseif ($_POST['receivercc'] != '-1')
{
// Recipient was provided from combo list
if ($_POST['receivercc'] == 'thirdparty') // Id of third party
{
$sendtocc = $thirdparty->email;
}
else // Id du contact
{
$sendtocc = $thirdparty->contact_get_property((int) $_POST['receivercc'],'email');
}
}
//var_dump($listofobjectref[$thirdpartyid]); // Array of invoice for this thirdparty
$attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
$listofqualifiedinvoice=array();
$listofqualifiedref=array();
foreach($listofobjectref[$thirdpartyid] as $objectid => $object)
{
//var_dump($object);
//var_dump($thirdpartyid.' - '.$objectid.' - '.$object->statut);
if ($object->statut != Facture::STATUS_VALIDATED)
{
$nbignored++;
continue; // Payment done or started or canceled
}
// Read document
// TODO Use future field $object->fullpathdoc to know where is stored default file
// TODO If not defined, use $object->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc.
$filename=dol_sanitizeFileName($object->ref).'.pdf';
$filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref);
$file = $filedir . '/' . $filename;
$mime = dol_mimetype($file);
if (dol_is_file($file))
{
if (empty($sendto)) // For the case, no recipient were set (multi thirdparties send)
{
$object->fetch_thirdparty();
$sendto = $object->thirdparty->email;
}
if (empty($sendto))
{
//print "No recipient for thirdparty ".$object->thirdparty->name;
$nbignored++;
continue;
}
if (dol_strlen($sendto))
{
// Create form object
$attachedfiles=array(
'paths'=>array_merge($attachedfiles['paths'],array($file)),
'names'=>array_merge($attachedfiles['names'],array($filename)),
'mimes'=>array_merge($attachedfiles['mimes'],array($mime))
);
}
$listofqualifiedinvoice[$objectid]=$object;
$listofqualifiedref[$objectid]=$object->ref;
}
else
{
$nbignored++;
$langs->load("other");
$resaction.='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div>';
dol_syslog('Failed to read file: '.$file, LOG_WARNING);
continue;
}
//var_dump($listofqualifiedref);
}
if (count($listofqualifiedinvoice) > 0)
{
$langs->load("commercial");
$from = $user->getFullName($langs) . ' <' . $user->email .'>';
$replyto = $from;
$subject = GETPOST('subject');
$message = GETPOST('message');
$sendtocc = GETPOST('sentocc');
$sendtobcc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO);
$substitutionarray=array(
'__ID__' => join(', ',array_keys($listofqualifiedinvoice)),
'__EMAIL__' => $thirdparty->email,
'__CHECK_READ__' => '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$thirdparty->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>',
//'__LASTNAME__' => $obj2->lastname,
//'__FIRSTNAME__' => $obj2->firstname,
'__FACREF__' => join(', ',$listofqualifiedref), // For backward compatibility
'__REF__' => join(', ',$listofqualifiedref),
'__REFCLIENT__' => $thirdparty->name
);
$subject=make_substitutions($subject, $substitutionarray);
$message=make_substitutions($message, $substitutionarray);
$filepath = $attachedfiles['paths'];
$filename = $attachedfiles['names'];
$mimetype = $attachedfiles['mimes'];
//var_dump($filepath);
// Send mail
require_once(DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php');
$mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1);
if ($mailfile->error)
{
$resaction.='<div class="error">'.$mailfile->error.'</div>';
}
else
{
$result=$mailfile->sendfile();
if ($result)
{
$resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'<br>'; // Must not contain "
$error=0;
// Insert logs into agenda
foreach($listofqualifiedinvoice as $invid => $object)
{
$actiontypecode='AC_FAC';
$actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
if ($message)
{
if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject);
$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
$actionmsg = dol_concatdesc($actionmsg, $message);
}
// Initialisation donnees
$object->sendtoid = 0;
$object->actiontypecode = $actiontypecode;
$object->actionmsg = $actionmsg; // Long text
$object->actionmsg2 = $actionmsg2; // Short text
$object->fk_element = $invid;
$object->elementtype = $object->element;
// Appel des triggers
include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
$interface=new Interfaces($db);
$result=$interface->run_triggers('BILL_SENTBYMAIL',$object,$user,$langs,$conf);
if ($result < 0) { $error++; $errors=$interface->errors; }
// Fin appel triggers
if ($error)
{
setEventMessages($db->lasterror(), $errors, 'errors');
dol_syslog("Error in trigger BILL_SENTBYMAIL ".$db->lasterror(), LOG_ERR);
}
$nbsent++;
}
}
else
{
$langs->load("other");
if ($mailfile->error)
{
$resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
$resaction.='<br><div class="error">'.$mailfile->error.'</div>';
}
else
{
$resaction.='<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
}
}
}
}
}
$resaction.=($resaction?'<br>':$resaction);
$resaction.='<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
$resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n<br>";
$resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n<br>";
$resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n<br>";
if ($nbsent)
{
$action=''; // Do not show form post if there was at least one successfull sent
setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
setEventMessages($resaction, null, 'mesgs');
}
else
{
//setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file
setEventMessages($resaction, null, 'warnings');
}
}
$action='list';
$massaction='';
}
}
// Do we click on purge search criteria ?
if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers
{
$search_user='';
$search_sale='';
$search_product_category='';
$search_ref='';
$search_refcustomer='';
$search_societe='';
$search_montant_ht='';
$search_montant_ttc='';
$search_status='';
$search_paymentmode='';
$day='';
$year='';
$month='';
$toselect='';
$option='';
$filter='';
$day_lim='';
$year_lim='';
$month_lim='';
}
/*
* View
*/
llxHeader('',$langs->trans('Bill'),'EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes');
$form = new Form($db);
$formother = new FormOther($db);
$formfile = new FormFile($db);
$bankaccountstatic=new Account($db);
$facturestatic=new Facture($db);
$sql = 'SELECT';
if ($sall || $search_product_category > 0) $sql = 'SELECT DISTINCT';
$sql.= ' f.rowid as facid, f.facnumber, f.ref_client, f.type, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.total as total_ht, f.tva as total_tva, f.total_ttc,';
$sql.= ' f.datef as df, f.date_lim_reglement as datelimite,';
$sql.= ' f.paye as paye, f.fk_statut,';
$sql.= ' s.nom as name, s.rowid as socid, s.code_client, s.client ';
if (! $sall) $sql.= ', SUM(pf.amount) as am'; // To be able to sort on status
$sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s';
$sql.= ', '.MAIN_DB_PREFIX.'facture as f';
if (! $sall) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON pf.fk_facture = f.rowid';
else $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'facturedet as fd ON fd.fk_facture = f.rowid';
if ($sall || $search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'facturedet as pd ON f.rowid=pd.fk_facture';
if ($search_product_category > 0) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product';
// We'll need this table joined to the select in order to filter by sale
if ($search_sale > 0 || (! $user->rights->societe->client->voir && ! $socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
if ($search_user > 0)
{
$sql.=", ".MAIN_DB_PREFIX."element_contact as ec";
$sql.=", ".MAIN_DB_PREFIX."c_type_contact as tc";
}
$sql.= ' WHERE f.fk_soc = s.rowid';
$sql.= " AND f.entity = ".$conf->entity;
if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
if ($search_product_category > 0) $sql.=" AND cp.fk_categorie = ".$search_product_category;
if ($socid > 0) $sql.= ' AND s.rowid = '.$socid;
if ($userid)
{
if ($userid == -1) $sql.=' AND f.fk_user_author IS NULL';
else $sql.=' AND f.fk_user_author = '.$userid;
}
if ($filtre)
{
$aFilter = explode(',', $filtre);
foreach ($aFilter as $filter)
{
$filt = explode(':', $filter);
$sql .= ' AND ' . trim($filt[0]) . ' = ' . trim($filt[1]);
}
}
if ($search_ref) $sql .= natural_search('f.facnumber', $search_ref);
if ($search_refcustomer) $sql .= natural_search('f.ref_client', $search_refcustomer);
if ($search_societe) $sql .= natural_search('s.nom', $search_societe);
if ($search_montant_ht != '') $sql.= natural_search('f.total', $search_montant_ht, 1);
if ($search_montant_ttc != '') $sql.= natural_search('f.total_ttc', $search_montant_ttc, 1);
if ($search_status != '' && $search_status >= 0) $sql.= " AND f.fk_statut = ".$db->escape($search_status);
if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".$search_paymentmode."";
if ($month > 0)
{
if ($year > 0 && empty($day))
$sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'";
else if ($year > 0 && ! empty($day))
$sql.= " AND f.datef BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'";
else
$sql.= " AND date_format(f.datef, '%m') = '".$month."'";
}
else if ($year > 0)
{
$sql.= " AND f.datef BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'";
}
if ($month_lim > 0)
{
if ($year_lim > 0 && empty($day_lim))
$sql.= " AND f.date_lim_reglement BETWEEN '".$db->idate(dol_get_first_day($year_lim,$month_lim,false))."' AND '".$db->idate(dol_get_last_day($year_lim,$month_lim,false))."'";
else if ($year_lim > 0 && ! empty($day_lim))
$sql.= " AND f.date_lim_reglement BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_lim, $day_lim, $year_lim))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month_lim, $day_lim, $year_lim))."'";
else
$sql.= " AND date_format(f.date_lim_reglement, '%m') = '".$month_lim."'";
}
else if ($year_lim > 0)
{
$sql.= " AND f.date_lim_reglement BETWEEN '".$db->idate(dol_get_first_day($year_lim,1,false))."' AND '".$db->idate(dol_get_last_day($year_lim,12,false))."'";
}
if ($option == 'late') $sql.=" AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->client->warning_delay)."'";
if ($filter == 'paye:0') $sql.= " AND f.fk_statut = 1";
if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$search_sale;
if ($search_user > 0)
{
$sql.= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='facture' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user;
}
if (! $sall)
{
$sql.= ' GROUP BY f.rowid, f.facnumber, ref_client, f.type, f.note_private, f.note_public, f.increment, f.total, f.tva, f.total_ttc,';
$sql.= ' f.datef, f.date_lim_reglement,';
$sql.= ' f.paye, f.fk_statut,';
$sql.= ' s.nom, s.rowid, s.code_client, s.client';
}
else
{
$sql .= natural_search(array_keys($fieldstosearchall), $sall);
}
$sql.= ' ORDER BY ';
$listfield=explode(',',$sortfield);
foreach ($listfield as $key => $value) $sql.= $listfield[$key].' '.$sortorder.',';
$sql.= ' f.rowid DESC ';
$nbtotalofrecords = 0;
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
}
$sql.= $db->plimit($limit+1,$offset);
//print $sql;
$resql = $db->query($sql);
if ($resql)
{
$num = $db->num_rows($resql);
$arrayofselected=is_array($toselect)?$toselect:array();
if ($socid)
{
$soc = new Societe($db);
$soc->fetch($socid);
}
$param='&socid='.$socid;
if ($day) $param.='&day='.$day;
if ($month) $param.='&month='.$month;
if ($year) $param.='&year=' .$year;
if ($day_lim) $param.='&day_lim='.$day_lim;
if ($month_lim) $param.='&month_lim='.$month_lim;
if ($year_lim) $param.='&year_lim=' .$year_lim;
if ($search_ref) $param.='&search_ref=' .$search_ref;
if ($search_refcustomer) $param.='&search_refcustomer=' .$search_refcustomer;
if ($search_societe) $param.='&search_societe=' .$search_societe;
if ($search_sale > 0) $param.='&search_sale=' .$search_sale;
if ($search_user > 0) $param.='&search_user=' .$search_user;
if ($search_product_category > 0) $param.='$search_product_category=' .$search_product_category;
if ($search_montant_ht != '') $param.='&search_montant_ht='.$search_montant_ht;
if ($search_montant_ttc != '') $param.='&search_montant_ttc='.$search_montant_ttc;
if ($search_status != '') $param.='&search_status='.$search_status;
if ($search_paymentmode > 0) $param.='search_paymentmode='.$search_paymentmode;
$param.=(! empty($option)?"&option=".$option:"");
$massactionbutton=$form->selectMassAction('', $massaction ? array() : array('presend'=>$langs->trans("SendByMail")));
$i = 0;
print '<form method="POST" name="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n";
print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->name:''),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,$massactionbutton,$num,$nbtotalofrecords,'title_accountancy.png');
if ($massaction == 'presend')
{
$langs->load("mails");
if (! GETPOST('cancel'))
{
$objecttmp=new Facture($db);
$listofselectedid=array();
$listofselectedthirdparties=array();
$listofselectedref=array();
foreach($arrayofselected as $toselectid)
{
$result=$objecttmp->fetch($toselectid);
if ($result > 0)
{
$listofselectedid[$toselectid]=$toselectid;
$thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid;
$listofselectedthirdparties[$thirdpartyid]=$thirdpartyid;
$listofselectedref[$thirdpartyid][$toselectid]=$objecttmp->ref;
}
}
}
print '<input type="hidden" name="massaction" value="confirm_presend">';
include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
$formmail = new FormMail($db);
dol_fiche_head(null, '', '');
$topicmail="SendBillRef";
$modelmail="facture_send";
// Cree l'objet formulaire mail
include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
$formmail = new FormMail($db);
$formmail->withform=-1;
$formmail->fromtype = 'user';
$formmail->fromid = $user->id;
$formmail->fromname = $user->getFullName($langs);
$formmail->frommail = $user->email;
if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 1)) // If bit 1 is set
{
$formmail->trackid='inv'.$object->id;
}
if (! empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set
{
include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
$formmail->frommail=dolAddEmailTrackId($formmail->frommail, 'inv'.$object->id);
}
$formmail->withfrom=1;
$liste=$langs->trans("AllRecipientSelected");
if (count($listofselectedthirdparties) == 1)
{
$liste=array();
$thirdpartyid=array_shift($listofselectedthirdparties);
$soc=new Societe($db);
$soc->fetch($thirdpartyid);
foreach ($soc->thirdparty_and_contact_email_array(1) as $key=>$value)
{
$liste[$key]=$value;
}
$formmail->withtoreadonly=0;
}
else
{
$formmail->withtoreadonly=1;
}
$formmail->withto=$liste;
$formmail->withtofree=0;
$formmail->withtocc=1;
$formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC;
$formmail->withtopic=$langs->transnoentities($topicmail, '__REF__', '__REFCLIENT__');
$formmail->withfile=$langs->trans("OnlyPDFattachmentSupported");
$formmail->withbody=1;
$formmail->withdeliveryreceipt=1;
$formmail->withcancel=1;
// Tableau des substitutions
$formmail->substit['__REF__']='__REF__'; // We want to keep the tag
$formmail->substit['__SIGNATURE__']=$user->signature;
$formmail->substit['__REFCLIENT__']='__REFCLIENT__'; // We want to keep the tag
$formmail->substit['__PERSONALIZED__']='';
$formmail->substit['__CONTACTCIVNAME__']='';
// Tableau des parametres complementaires du post
$formmail->param['action']=$action;
$formmail->param['models']=$modelmail;
$formmail->param['models_id']=GETPOST('modelmailselected','int');
$formmail->param['facid']=join(',',$arrayofselected);
//$formmail->param['returnurl']=$_SERVER["PHP_SELF"].'?id='.$object->id;
print $formmail->get_form();
dol_fiche_end();
}
if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="action" value="list">';
print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
print '<input type="hidden" name="viewstatut" value="'.$viewstatut.'">';
if ($sall)
{
foreach($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val);
print $langs->trans("FilterOnInto", $sall) . join(', ',$fieldstosearchall);
}
// If the user can view prospects other than his'
$moreforfilter='';
if ($user->rights->societe->client->voir || $socid)
{
$langs->load("commercial");
$moreforfilter.='<div class="divsearchfield">';
$moreforfilter.=$langs->trans('ThirdPartiesOfSaleRepresentative'). ': ';
$moreforfilter.=$formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth300');
$moreforfilter.='</div>';
}
// If the user can view prospects other than his'
if ($user->rights->societe->client->voir || $socid)
{
$moreforfilter.='<div class="divsearchfield">';
$moreforfilter.=$langs->trans('LinkedToSpecificUsers'). ': ';
$moreforfilter.=$form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300');
$moreforfilter.='</div>';
}
// If the user can view prospects other than his'
if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire))
{
include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
$moreforfilter.='<div class="divsearchfield">';
$moreforfilter.=$langs->trans('IncludingProductWithTag'). ': ';
$cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, null, 'parent', null, null, 1);
$moreforfilter.=$form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, '', 1);
$moreforfilter.='</div>';
}
$parameters=array();
$reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters); // Note that $action and $object may have been modified by hook
if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
else $moreforfilter = $hookmanager->resPrint;
if ($moreforfilter)
{
print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter;
print '</div>';
}
print '<table class="liste '.($moreforfilter?"listwithfilterbefore":"").'">';
print '<tr class="liste_titre">';
print_liste_field_titre($langs->trans('Ref'),$_SERVER['PHP_SELF'],'f.facnumber','',$param,'',$sortfield,$sortorder);
print_liste_field_titre($langs->trans('RefCustomer'),$_SERVER["PHP_SELF"],'f.ref_client','',$param,'',$sortfield,$sortorder);
print_liste_field_titre($langs->trans('Date'),$_SERVER['PHP_SELF'],'f.datef','',$param,'align="center"',$sortfield,$sortorder);
print_liste_field_titre($langs->trans("DateDue"),$_SERVER['PHP_SELF'],"f.date_lim_reglement",'',$param,'align="center"',$sortfield,$sortorder);
print_liste_field_titre($langs->trans('ThirdParty'),$_SERVER['PHP_SELF'],'s.nom','',$param,'',$sortfield,$sortorder);
print_liste_field_titre($langs->trans("PaymentModeShort"),$_SERVER["PHP_SELF"],"f.fk_mode_reglement","",$param,"",$sortfield,$sortorder);
print_liste_field_titre($langs->trans('AmountHT'),$_SERVER['PHP_SELF'],'f.total','',$param,'align="right"',$sortfield,$sortorder);
print_liste_field_titre($langs->trans('Taxes'),$_SERVER['PHP_SELF'],'f.tva','',$param,'align="right"',$sortfield,$sortorder);
print_liste_field_titre($langs->trans('AmountTTC'),$_SERVER['PHP_SELF'],'f.total_ttc','',$param,'align="right"',$sortfield,$sortorder);
print_liste_field_titre($langs->trans('Received'),$_SERVER['PHP_SELF'],'am','',$param,'align="right"',$sortfield,$sortorder);
print_liste_field_titre($langs->trans('Status'),$_SERVER['PHP_SELF'],'fk_statut,paye,am','',$param,'align="right"',$sortfield,$sortorder);
print_liste_field_titre('',$_SERVER["PHP_SELF"],"",'','','',$sortfield,$sortorder,'maxwidthsearch ');
print "</tr>\n";
// Filters lines
print '<tr class="liste_titre">';
print '<td class="liste_titre" align="left">';
print '<input class="flat" size="6" type="text" name="search_ref" value="'.$search_ref.'">';
print '</td>';
print '<td class="liste_titre">';
print '<input class="flat" size="6" type="text" name="search_refcustomer" value="'.$search_refcustomer.'">';
print '</td>';
print '<td class="liste_titre" align="center">';
if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day" value="'.$day.'">';
print '<input class="flat" type="text" size="1" maxlength="2" name="month" value="'.$month.'">';
$formother->select_year($year?$year:-1,'year',1, 20, 5);
print '</td>';
print '<td class="liste_titre" align="center">';
if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat" type="text" size="1" maxlength="2" name="day_lim" value="'.$day_lim.'">';
print '<input class="flat" type="text" size="1" maxlength="2" name="month_lim" value="'.$month_lim.'">';
$formother->select_year($year_lim?$year_lim:-1,'year_lim',1, 20, 5);
print '<br><input type="checkbox" name="option" value="late"'.($option == 'late'?' checked':'').'> '.$langs->trans("Late");
print '</td>';
print '<td class="liste_titre" align="left"><input class="flat" type="text" size="8" name="search_societe" value="'.$search_societe.'"></td>';
print '<td class="liste_titre" align="left">';
$form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 0, 1, 10);
print '</td>';
print '<td class="liste_titre" align="right"><input class="flat" type="text" size="6" name="search_montant_ht" value="'.$search_montant_ht.'"></td>';
print '<td class="liste_titre"></td>';
print '<td class="liste_titre" align="right"><input class="flat" type="text" size="6" name="search_montant_ttc" value="'.$search_montant_ttc.'"></td>';
print '<td class="liste_titre"></td>';
print '<td class="liste_titre" align="right">';
$liststatus=array('0'=>$langs->trans("BillShortStatusDraft"), '1'=>$langs->trans("BillShortStatusNotPaid"), '2'=>$langs->trans("BillShortStatusPaid"), '3'=>$langs->trans("BillShortStatusCanceled"));
print $form->selectarray('search_status', $liststatus, $search_status, 1);
print '</td>';
print '<td class="liste_titre" align="right"><input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"),'search.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
print '<input type="image" class="liste_titre" name="button_removefilter" src="'.img_picto($langs->trans("Search"),'searchclear.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">';
print "</td></tr>\n";
if ($num > 0)
{
$var=true;
$total_ht=0;
$total_tva=0;
$total_ttc=0;
$totalrecu=0;
while ($i < min($num,$limit))
{
$objp = $db->fetch_object($resql);
$var=!$var;
$datelimit=$db->jdate($objp->datelimite);
print '<tr '.$bc[$var].'>';
print '<td class="nowrap">';
$facturestatic->id=$objp->facid;
$facturestatic->ref=$objp->facnumber;
$facturestatic->type=$objp->type;
$facturestatic->statut=$objp->fk_statut;
$facturestatic->date_lim_reglement=$db->jdate($objp->datelimite);
$notetoshow=dol_string_nohtmltag(($user->societe_id>0?$objp->note_public:$objp->note_private),1);
$paiement = $facturestatic->getSommePaiement();
print '<table class="nobordernopadding"><tr class="nocellnopadd">';
print '<td class="nobordernopadding nowrap">';
print $facturestatic->getNomUrl(1,'',200,0,$notetoshow);
print $objp->increment;
print '</td>';
print '<td style="min-width: 20px" class="nobordernopadding nowrap">';
if (! empty($objp->note_private))
{
print ' <span class="note">';
print '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$objp->facid.'">'.img_picto($langs->trans("ViewPrivateNote"),'object_generic').'</a>';
print '</span>';
}
$filename=dol_sanitizeFileName($objp->facnumber);
$filedir=$conf->facture->dir_output . '/' . dol_sanitizeFileName($objp->facnumber);
$urlsource=$_SERVER['PHP_SELF'].'?id='.$objp->facid;
print $formfile->getDocumentsLink($facturestatic->element, $filename, $filedir);
print '</td>';
print '</tr>';
print '</table>';
print "</td>\n";
// Customer ref
print '<td class="nowrap">';
print $objp->ref_client;
print '</td>';
// Date
print '<td align="center" class="nowrap">';
print dol_print_date($db->jdate($objp->df),'day');
print '</td>';
// Date limit
print '<td align="center" class="nowrap">'.dol_print_date($datelimit,'day');
if ($facturestatic->hasDelay())
{
print img_warning($langs->trans('Late'));
}
print '</td>';
print '<td>';
$thirdparty=new Societe($db);
$thirdparty->id=$objp->socid;
$thirdparty->name=$objp->name;
$thirdparty->client=$objp->client;
$thirdparty->code_client=$objp->code_client;
print $thirdparty->getNomUrl(1,'customer');
print '</td>';
// Payment mode
print '<td>';
$form->form_modes_reglement($_SERVER['PHP_SELF'], $objp->fk_mode_reglement, 'none', '', -1);
print '</td>';
print '<td align="right">'.price($objp->total_ht,0,$langs).'</td>';
print '<td align="right">'.price($objp->total_tva,0,$langs).'</td>';
print '<td align="right">'.price($objp->total_ttc,0,$langs).'</td>';
print '<td align="right">'.(! empty($paiement)?price($paiement,0,$langs):' ').'</td>';
// Status
print '<td align="right" class="nowrap">';
print $facturestatic->LibStatut($objp->paye,$objp->fk_statut,5,$paiement,$objp->type);
print "</td>";
// Checkbox
print '<td class="nowrap" align="center">';
$selected=0;
if (in_array($objp->facid, $arrayofselected)) $selected=1;
print '<input id="cb'.$objp->facid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$objp->facid.'"'.($selected?' checked="checked"':'').'>';
print '</td>' ;
print "</tr>\n";
$total_ht+=$objp->total_ht;
$total_tva+=$objp->total_tva;
$total_ttc+=$objp->total_ttc;
$totalrecu+=$paiement;
$i++;
}
if (($offset + $num) <= $limit)
{
// Print total
print '<tr class="liste_total">';
print '<td class="liste_total" colspan="6" align="left">'.$langs->trans('Total').'</td>';
print '<td class="liste_total" align="right">'.price($total_ht,0,$langs).'</td>';
print '<td class="liste_total" align="right">'.price($total_tva,0,$langs).'</td>';
print '<td class="liste_total" align="right">'.price($total_ttc,0,$langs).'</td>';
print '<td class="liste_total" align="right">'.price($totalrecu,0,$langs).'</td>';
print '<td class="liste_total"></td>';
print '<td class="liste_total"></td>';
print '</tr>';
}
}
print "</table>\n";
print "</form>\n";
$db->free($resql);
}
else
{
dol_print_error($db);
}
llxFooter();
$db->close();
| IndustriaLeuven/dolibarr | htdocs/compta/facture/list.php | PHP | gpl-3.0 | 38,537 |
/*!
* web-SplayChat v0.4.0 - messaging web application for MTProto
* http://SplayChat.com/
* Copyright (C) 2014 SplayChat Messenger <igor.beatle@gmail.com>
* http://SplayChat.com//blob/master/LICENSE
*/
chrome.app.runtime.onLaunched.addListener(function(launchData) {
chrome.app.window.create('../index.html', {
id: 'web-SplayChat-chat',
innerBounds: {
width: 1000,
height: 700
},
minWidth: 320,
minHeight: 400,
frame: 'chrome'
});
});
| ishmaelchibvuri/splayweb.io | app/js/background.js | JavaScript | gpl-3.0 | 481 |
<?php
namespace CartBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
class CartController extends Controller {
/**
* @Route("/cart/current", name="admin_cart_current")
* @Method({"GET"})
*/
public function currentAction()
{
$users = $this->getDoctrine()->getRepository('UserBundle:User')->findAll();
$priceCalculator = $this->get('price_calculator');
$usersPrice = array();
foreach ($users as $key => $user) {
$usersPrice[$key]['user'] = $user;
$usersPrice[$key]['price'] = $priceCalculator->getPricing($user);
}
return $this->render('CartBundle:Cart:current.html.twig', array(
'usersPrice' => $usersPrice
));
}
}
| stephanfo/AWG | src/CartBundle/Controller/CartController.php | PHP | gpl-3.0 | 914 |
/**
* Copyright (C) 2019 Takima
*
* This file is part of OSM Contributor.
*
* OSM Contributor 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.
*
* OSM Contributor 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 OSM Contributor. If not, see <http://www.gnu.org/licenses/>.
*/
package io.jawg.osmcontributor.ui.utils;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.view.ScaleGestureDetector;
import android.view.animation.DecelerateInterpolator;
import java.util.Queue;
import io.jawg.osmcontributor.utils.LimitedQueue;
/**
* @author Tommy Buonomo on 16/06/16.
*/
public abstract class ZoomAnimationGestureDetector extends ScaleGestureDetector.SimpleOnScaleGestureListener {
private static final float MAX_SPEED = 50.0f;
private static final float MIN_SPEED = 2.0f;
private Queue<Float> previousSpeedQueue = new LimitedQueue<>(5);
@Override
public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) {
previousSpeedQueue.clear();
return true;
}
@Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
float currentSpeed = scaleGestureDetector.getPreviousSpan() - scaleGestureDetector.getCurrentSpan();
previousSpeedQueue.add(currentSpeed);
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector scaleGestureDetector) {
float sum = 0;
for (Float speed : previousSpeedQueue) {
sum += speed;
}
float moy = sum / previousSpeedQueue.size();
if (Math.abs(moy) > MAX_SPEED) {
moy = moy > 0 ? MAX_SPEED : -MAX_SPEED;
}
ValueAnimator valueAnimator = ObjectAnimator.ofFloat(-moy / 1000, 0);
int duration = (int) (Math.abs(moy) * 12);
valueAnimator.setDuration(duration);
valueAnimator.setInterpolator(new DecelerateInterpolator());
onZoomAnimationEnd(valueAnimator);
if (Math.abs(moy) > MIN_SPEED) {
onZoomAnimationEnd(valueAnimator);
}
}
public abstract void onZoomAnimationEnd(ValueAnimator animator);
}
| mapsquare/osm-contributor | src/main/java/io/jawg/osmcontributor/ui/utils/ZoomAnimationGestureDetector.java | Java | gpl-3.0 | 2,599 |
#region License
/*
Microsoft Public License (Ms-PL)
MonoGame - Copyright © 2009 The MonoGame Team
All rights reserved.
This license governs use of the accompanying software. If you use the software, you accept this license. If you do not
accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under
U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software,
your patent license from such contributor to the software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution
notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only under this license by including
a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object
code form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees
or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent
permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular
purpose and non-infringement.
*/
#endregion License
//
// Author: Kenneth James Pouncey
//
using System;
using Microsoft.Xna.Framework.Content;
namespace Microsoft.Xna.Framework.Content
{
internal class TimeSpanReader : ContentTypeReader<TimeSpan>
{
internal TimeSpanReader ()
{
}
protected internal override TimeSpan Read (ContentReader input, TimeSpan existingInstance)
{
// Could not find any information on this really but from all the searching it looks
// like the constructor of number of ticks is long so I have placed that here for now
// long is a Int64 so we read with 64
// <Duration>PT2S</Duration>
//
return new TimeSpan(input.ReadInt64 ());
}
}
}
| Blucky87/Otiose2D | src/libs/MonoGame/MonoGame.Framework/Content/ContentReaders/TimeSpanReader.cs | C# | gpl-3.0 | 3,388 |
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
#include "AP_TECS.h"
#include <AP_HAL.h>
extern const AP_HAL::HAL& hal;
#if CONFIG_HAL_BOARD == HAL_BOARD_AVR_SITL
#include <stdio.h>
# define Debug(fmt, args ...) do {printf("%s:%d: " fmt "\n", __FUNCTION__, __LINE__, ## args); hal.scheduler->delay(1); } while(0)
#else
# define Debug(fmt, args ...)
#endif
//Debug("%.2f %.2f %.2f %.2f \n", var1, var2, var3, var4);
// table of user settable parameters
const AP_Param::GroupInfo AP_TECS::var_info[] PROGMEM = {
// @Param: CLMB_MAX
// @DisplayName: Maximum Climb Rate (metres/sec)
// @Description: This is the best climb rate that the aircraft can achieve with the throttle set to THR_MAX and the airspeed set to the default value. For electric aircraft make sure this number can be achieved towards the end of flight when the battery voltage has reduced. The setting of this parameter can be checked by commanding a positive altitude change of 100m in loiter, RTL or guided mode. If the throttle required to climb is close to THR_MAX and the aircraft is maintaining airspeed, then this parameter is set correctly. If the airspeed starts to reduce, then the parameter is set to high, and if the throttle demand require to climb and maintain speed is noticeably less than THR_MAX, then either CLMB_MAX should be increased or THR_MAX reduced.
// @Increment: 0.1
// @User: User
AP_GROUPINFO("CLMB_MAX", 0, AP_TECS, _maxClimbRate, 5.0f),
// @Param: SINK_MIN
// @DisplayName: Minimum Sink Rate (metres/sec)
// @Description: This is the sink rate of the aircraft with the throttle set to THR_MIN and the same airspeed as used to measure CLMB_MAX.
// @Increment: 0.1
// @User: User
AP_GROUPINFO("SINK_MIN", 1, AP_TECS, _minSinkRate, 2.0f),
// @Param: TIME_CONST
// @DisplayName: Controller time constant (sec)
// @Description: This is the time constant of the TECS control algorithm. Smaller values make it faster to respond, large values make it slower to respond.
// @Range: 3.0-10.0
// @Increment: 0.2
// @User: Advanced
AP_GROUPINFO("TIME_CONST", 2, AP_TECS, _timeConst, 5.0f),
// @Param: THR_DAMP
// @DisplayName: Controller throttle damping
// @Description: This is the damping gain for the throttle demand loop. Increase to add damping to correct for oscillations in speed and height.
// @Range: 0.1-1.0
// @Increment: 0.1
// @User: Advanced
AP_GROUPINFO("THR_DAMP", 3, AP_TECS, _thrDamp, 0.5f),
// @Param: INTEG_GAIN
// @DisplayName: Controller integrator
// @Description: This is the integrator gain on the control loop. Increase to increase the rate at which speed and height offsets are trimmed out
// @Range: 0.0-0.5
// @Increment: 0.02
// @User: Advanced
AP_GROUPINFO("INTEG_GAIN", 4, AP_TECS, _integGain, 0.1f),
// @Param: VERT_ACC
// @DisplayName: Vertical Acceleration Limit (metres/sec^2)
// @Description: This is the maximum vertical acceleration either up or down that the controller will use to correct speed or height errors.
// @Range: 1.0-10.0
// @Increment: 0.5
// @User: Advanced
AP_GROUPINFO("VERT_ACC", 5, AP_TECS, _vertAccLim, 7.0f),
// @Param: HGT_OMEGA
// @DisplayName: Height complementary filter frequency (radians/sec)
// @Description: This is the cross-over frequency of the complementary filter used to fuse vertical acceleration and baro alt to obtain an estimate of height rate and height.
// @Range: 1.0-5.0
// @Increment: 0.05
// @User: Advanced
AP_GROUPINFO("HGT_OMEGA", 6, AP_TECS, _hgtCompFiltOmega, 3.0f),
// @Param: SPD_OMEGA
// @DisplayName: Speed complementary filter frequency (radians/sec)
// @Description: This is the cross-over frequency of the complementary filter used to fuse longitudinal acceleration and airspeed to obtain a lower noise and lag estimate of airspeed.
// @Range: 0.5-2.0
// @Increment: 0.05
// @User: Advanced
AP_GROUPINFO("SPD_OMEGA", 7, AP_TECS, _spdCompFiltOmega, 2.0f),
// @Param: RLL2THR
// @DisplayName: Bank angle compensation gain
// @Description: Increasing this gain turn increases the amount of throttle that will be used to compensate for the additional drag created by turning. Ideally this should be set to approximately 10 x the extra sink rate in m/s created by a 45 degree bank turn. Increase this gain if the aircraft initially loses energy in turns and reduce if the aircraft initially gains energy in turns. Efficient high aspect-ratio aircraft (eg powered sailplanes) can use a lower value, whereas inefficient low aspect-ratio models (eg delta wings) can use a higher value.
// @Range: 5.0 to 30.0
// @Increment: 1.0
// @User: Advanced
AP_GROUPINFO("RLL2THR", 8, AP_TECS, _rollComp, 10.0f),
// @Param: SPDWEIGHT
// @DisplayName: Weighting applied to speed control
// @Description: This parameter adjusts the amount of weighting that the pitch control applies to speed vs height errors. Setting it to 0.0 will cause the pitch control to control height and ignore speed errors. This will normally improve height accuracy but give larger airspeed errors. Setting it to 2.0 will cause the pitch control loop to control speed and ignore height errors. This will normally reduce airsped errors, but give larger height errors. A value of 1.0 gives a balanced response and is the default.
// @Range: 0.0 to 2.0
// @Increment: 0.1
// @User: Advanced
AP_GROUPINFO("SPDWEIGHT", 9, AP_TECS, _spdWeight, 1.0f),
// @Param: PTCH_DAMP
// @DisplayName: Controller pitch damping
// @Description: This is the damping gain for the pitch demand loop. Increase to add damping to correct for oscillations in speed and height.
// @Range: 0.1-1.0
// @Increment: 0.1
// @User: Advanced
AP_GROUPINFO("PTCH_DAMP", 10, AP_TECS, _ptchDamp, 0.0f),
// @Param: SINK_MAX
// @DisplayName: Maximum Descent Rate (metres/sec)
// @Description: This sets the maximum descent rate that the controller will use. If this value is too large, the aircraft will reach the pitch angle limit first and be enable to achieve the descent rate. This should be set to a value that can be achieved at the lower pitch angle limit.
// @Increment: 0.1
// @User: User
AP_GROUPINFO("SINK_MAX", 11, AP_TECS, _maxSinkRate, 5.0f),
// @Param: LAND_ARSPD
// @DisplayName: Airspeed during landing approach (m/s)
// @Description: When performing an autonomus landing, this value is used as the goal airspeed during approach. Note that this parameter is not useful if your platform does not have an airspeed sensor (use TECS_LAND_THR instead). If negative then this value is not used during landing.
// @Range: -1 to 127
// @Increment: 1
// @User: User
AP_GROUPINFO("LAND_ARSPD", 12, AP_TECS, _landAirspeed, -1),
// @Param: LAND_THR
// @DisplayName: Cruise throttle during landing approach (percentage)
// @Description: Use this parameter instead of LAND_ASPD if your platform does not have an airspeed sensor. It is the cruise throttle during landing approach. If it is negative if TECS_LAND_ASPD is in use then this value is not used during landing.
// @Range: -1 to 100
// @Increment: 0.1
// @User: User
AP_GROUPINFO("LAND_THR", 13, AP_TECS, _landThrottle, -1),
// @Param: LAND_SPDWGT
// @DisplayName: Weighting applied to speed control during landing.
// @Description: Same as SPDWEIGHT parameter, with the exception that this parameter is applied during landing flight stages. A value closer to 2 will result in the plane ignoring height error during landing and our experience has been that the plane will therefore keep the nose up -- sometimes good for a glider landing (with the side effect that you will likely glide a ways past the landing point). A value closer to 0 results in the plane ignoring speed error -- use caution when lowering the value below 1 -- ignoring speed could result in a stall.
// @Range: 0.0 to 2.0
// @Increment: 0.1
// @User: Advanced
AP_GROUPINFO("LAND_SPDWGT", 14, AP_TECS, _spdWeightLand, 1.0f),
// @Param: PITCH_MAX
// @DisplayName: Maximum pitch in auto flight
// @Description: This controls maximum pitch up in automatic throttle modes. If this is set to zero then LIM_PITCH_MAX is used instead. The purpose of this parameter is to allow the use of a smaller pitch range when in automatic flight than what is used in FBWA mode.
// @Range: 0 45
// @Increment: 1
// @User: Advanced
AP_GROUPINFO("PITCH_MAX", 15, AP_TECS, _pitch_max, 0),
// @Param: PITCH_MIN
// @DisplayName: Minimum pitch in auto flight
// @Description: This controls minimum pitch in automatic throttle modes. If this is set to zero then LIM_PITCH_MIN is used instead. The purpose of this parameter is to allow the use of a smaller pitch range when in automatic flight than what is used in FBWA mode. Note that TECS_PITCH_MIN should be a negative number.
// @Range: -45 0
// @Increment: 1
// @User: Advanced
AP_GROUPINFO("PITCH_MIN", 16, AP_TECS, _pitch_min, 0),
// @Param: LAND_SINK
// @DisplayName: Sink rate for final landing stage
// @Description: The sink rate in meters/second for the final stage of landing.
// @Range: 0.0 to 2.0
// @Increment: 0.1
// @User: Advanced
AP_GROUPINFO("LAND_SINK", 17, AP_TECS, _land_sink, 0.25f),
// @Param: TECS_LAND_TCONST
// @DisplayName: Land controller time constant (sec)
// @Description: This is the time constant of the TECS control algorithm when in final landing stage of flight. It should be smaller than TECS_TIME_CONST to allow for faster flare
// @Range: 1.0-5.0
// @Increment: 0.2
// @User: Advanced
AP_GROUPINFO("LAND_TCONST", 18, AP_TECS, _landTimeConst, 2.0f),
AP_GROUPEND
};
/*
* Written by Paul Riseborough 2013 to provide:
* - Combined control of speed and height using throttle to control
* total energy and pitch angle to control exchange of energy between
* potential and kinetic.
* Selectable speed or height priority modes when calculating pitch angle
* - Fallback mode when no airspeed measurement is available that
* sets throttle based on height rate demand and switches pitch angle control to
* height priority
* - Underspeed protection that demands maximum throttle and switches pitch angle control
* to speed priority mode
* - Relative ease of tuning through use of intuitive time constant, integrator and damping gains and the use
* of easy to measure aircraft performance data
*
*/
void AP_TECS::update_50hz(float hgt_afe)
{
// Implement third order complementary filter for height and height rate
// estimted height rate = _climb_rate
// estimated height above field elevation = _integ3_state
// Reference Paper :
// Optimising the Gains of the Baro-Inertial Vertical Channel
// Widnall W.S, Sinha P.K,
// AIAA Journal of Guidance and Control, 78-1307R
// Calculate time in seconds since last update
uint32_t now = hal.scheduler->micros();
float DT = max((now - _update_50hz_last_usec),0)*1.0e-6f;
if (DT > 1.0f) {
_integ3_state = hgt_afe;
_climb_rate = 0.0f;
_integ1_state = 0.0f;
DT = 0.02f; // when first starting TECS, use a
// small time constant
}
_update_50hz_last_usec = now;
// USe inertial nav verical velocity and height if available
Vector3f posned, velned;
if (_ahrs.get_velocity_NED(velned) && _ahrs.get_relative_position_NED(posned)) {
_climb_rate = - velned.z;
_integ3_state = - posned.z;
} else {
// Get height acceleration
float hgt_ddot_mea = -(_ahrs.get_accel_ef().z + GRAVITY_MSS);
// Perform filter calculation using backwards Euler integration
// Coefficients selected to place all three filter poles at omega
float omega2 = _hgtCompFiltOmega*_hgtCompFiltOmega;
float hgt_err = hgt_afe - _integ3_state;
float integ1_input = hgt_err * omega2 * _hgtCompFiltOmega;
_integ1_state = _integ1_state + integ1_input * DT;
float integ2_input = _integ1_state + hgt_ddot_mea + hgt_err * omega2 * 3.0f;
_climb_rate = _climb_rate + integ2_input * DT;
float integ3_input = _climb_rate + hgt_err * _hgtCompFiltOmega * 3.0f;
// If more than 1 second has elapsed since last update then reset the integrator state
// to the measured height
if (DT > 1.0f) {
_integ3_state = hgt_afe;
} else {
_integ3_state = _integ3_state + integ3_input*DT;
}
}
// Update and average speed rate of change
// Get DCM
const Matrix3f &rotMat = _ahrs.get_dcm_matrix();
// Calculate speed rate of change
float temp = rotMat.c.x * GRAVITY_MSS + _ahrs.get_ins().get_accel().x;
// take 5 point moving average
_vel_dot = _vdot_filter.apply(temp);
}
void AP_TECS::_update_speed(void)
{
// Calculate time in seconds since last update
uint32_t now = hal.scheduler->micros();
float DT = max((now - _update_speed_last_usec),0)*1.0e-6f;
_update_speed_last_usec = now;
// Convert equivalent airspeeds to true airspeeds
float EAS2TAS = _ahrs.get_EAS2TAS();
_TAS_dem = _EAS_dem * EAS2TAS;
_TASmax = aparm.airspeed_max * EAS2TAS;
_TASmin = aparm.airspeed_min * EAS2TAS;
if (_landAirspeed >= 0 && _ahrs.airspeed_sensor_enabled() &&
(_flight_stage == FLIGHT_LAND_APPROACH || _flight_stage== FLIGHT_LAND_FINAL)) {
_TAS_dem = _landAirspeed * EAS2TAS;
if (_TASmin > _TAS_dem) {
_TASmin = _TAS_dem;
}
}
// Reset states of time since last update is too large
if (DT > 1.0f) {
_integ5_state = (_EAS * EAS2TAS);
_integ4_state = 0.0f;
DT = 0.1f; // when first starting TECS, use a
// small time constant
}
// Get airspeed or default to halfway between min and max if
// airspeed is not being used and set speed rate to zero
if (!_ahrs.airspeed_sensor_enabled() || !_ahrs.airspeed_estimate(&_EAS)) {
// If no airspeed available use average of min and max
_EAS = 0.5f * (aparm.airspeed_min.get() + (float)aparm.airspeed_max.get());
}
// Implement a second order complementary filter to obtain a
// smoothed airspeed estimate
// airspeed estimate is held in _integ5_state
float aspdErr = (_EAS * EAS2TAS) - _integ5_state;
float integ4_input = aspdErr * _spdCompFiltOmega * _spdCompFiltOmega;
// Prevent state from winding up
if (_integ5_state < 3.1f){
integ4_input = max(integ4_input , 0.0f);
}
_integ4_state = _integ4_state + integ4_input * DT;
float integ5_input = _integ4_state + _vel_dot + aspdErr * _spdCompFiltOmega * 1.4142f;
_integ5_state = _integ5_state + integ5_input * DT;
// limit the airspeed to a minimum of 3 m/s
_integ5_state = max(_integ5_state, 3.0f);
}
void AP_TECS::_update_speed_demand(void)
{
// Set the airspeed demand to the minimum value if an underspeed condition exists
// or a bad descent condition exists
// This will minimise the rate of descent resulting from an engine failure,
// enable the maximum climb rate to be achieved and prevent continued full power descent
// into the ground due to an unachievable airspeed value
if ((_badDescent) || (_underspeed))
{
_TAS_dem = _TASmin;
}
// Constrain speed demand
_TAS_dem = constrain_float(_TAS_dem, _TASmin, _TASmax);
// calculate velocity rate limits based on physical performance limits
// provision to use a different rate limit if bad descent or underspeed condition exists
// Use 50% of maximum energy rate to allow margin for total energy contgroller
float velRateMax;
float velRateMin;
if ((_badDescent) || (_underspeed))
{
velRateMax = 0.5f * _STEdot_max / _integ5_state;
velRateMin = 0.5f * _STEdot_min / _integ5_state;
}
else
{
velRateMax = 0.5f * _STEdot_max / _integ5_state;
velRateMin = 0.5f * _STEdot_min / _integ5_state;
}
// Apply rate limit
if ((_TAS_dem - _TAS_dem_adj) > (velRateMax * 0.1f))
{
_TAS_dem_adj = _TAS_dem_adj + velRateMax * 0.1f;
_TAS_rate_dem = velRateMax;
}
else if ((_TAS_dem - _TAS_dem_adj) < (velRateMin * 0.1f))
{
_TAS_dem_adj = _TAS_dem_adj + velRateMin * 0.1f;
_TAS_rate_dem = velRateMin;
}
else
{
_TAS_dem_adj = _TAS_dem;
_TAS_rate_dem = (_TAS_dem - _TAS_dem_last) / 0.1f;
}
// Constrain speed demand again to protect against bad values on initialisation.
_TAS_dem_adj = constrain_float(_TAS_dem_adj, _TASmin, _TASmax);
_TAS_dem_last = _TAS_dem;
}
void AP_TECS::_update_height_demand(void)
{
// Apply 2 point moving average to demanded height
// This is required because height demand is only updated at 5Hz
_hgt_dem = 0.5f * (_hgt_dem + _hgt_dem_in_old);
_hgt_dem_in_old = _hgt_dem;
// Limit height rate of change
if ((_hgt_dem - _hgt_dem_prev) > (_maxClimbRate * 0.1f))
{
_hgt_dem = _hgt_dem_prev + _maxClimbRate * 0.1f;
}
else if ((_hgt_dem - _hgt_dem_prev) < (-_maxSinkRate * 0.1f))
{
_hgt_dem = _hgt_dem_prev - _maxSinkRate * 0.1f;
}
_hgt_dem_prev = _hgt_dem;
// Apply first order lag to height demand
_hgt_dem_adj = 0.05f * _hgt_dem + 0.95f * _hgt_dem_adj_last;
_hgt_dem_adj_last = _hgt_dem_adj;
// in final landing stage force height rate demand to the
// configured sink rate
if (_flight_stage == FLIGHT_LAND_FINAL) {
if (_flare_counter == 0) {
_hgt_rate_dem = _climb_rate;
}
// bring it in over 1s to prevent overshoot
if (_flare_counter < 10) {
_hgt_rate_dem = _hgt_rate_dem * 0.8f - 0.2f * _land_sink;
_flare_counter++;
} else {
_hgt_rate_dem = - _land_sink;
}
} else {
_hgt_rate_dem = (_hgt_dem_adj - _hgt_dem_adj_last) / 0.1f;
_flare_counter = 0;
}
}
void AP_TECS::_detect_underspeed(void)
{
if (((_integ5_state < _TASmin * 0.9f) &&
(_throttle_dem >= _THRmaxf * 0.95f) &&
_flight_stage != AP_TECS::FLIGHT_LAND_FINAL) ||
((_integ3_state < _hgt_dem_adj) && _underspeed))
{
_underspeed = true;
}
else
{
_underspeed = false;
}
}
void AP_TECS::_update_energies(void)
{
// Calculate specific energy demands
_SPE_dem = _hgt_dem_adj * GRAVITY_MSS;
_SKE_dem = 0.5f * _TAS_dem_adj * _TAS_dem_adj;
// Calculate specific energy rate demands
_SPEdot_dem = _hgt_rate_dem * GRAVITY_MSS;
_SKEdot_dem = _integ5_state * _TAS_rate_dem;
// Calculate specific energy
_SPE_est = _integ3_state * GRAVITY_MSS;
_SKE_est = 0.5f * _integ5_state * _integ5_state;
// Calculate specific energy rate
_SPEdot = _climb_rate * GRAVITY_MSS;
_SKEdot = _integ5_state * _vel_dot;
}
/*
current time constant. It is lower in landing to try to give a precise approach
*/
float AP_TECS::timeConstant(void)
{
if (_flight_stage==FLIGHT_LAND_FINAL ||
_flight_stage==FLIGHT_LAND_APPROACH) {
return _landTimeConst;
}
return _timeConst;
}
void AP_TECS::_update_throttle(void)
{
// Calculate limits to be applied to potential energy error to prevent over or underspeed occurring due to large height errors
float SPE_err_max = 0.5f * _TASmax * _TASmax - _SKE_dem;
float SPE_err_min = 0.5f * _TASmin * _TASmin - _SKE_dem;
// Calculate total energy error
_STE_error = constrain_float((_SPE_dem - _SPE_est), SPE_err_min, SPE_err_max) + _SKE_dem - _SKE_est;
float STEdot_dem = constrain_float((_SPEdot_dem + _SKEdot_dem), _STEdot_min, _STEdot_max);
float STEdot_error = STEdot_dem - _SPEdot - _SKEdot;
// Apply 0.5 second first order filter to STEdot_error
// This is required to remove accelerometer noise from the measurement
STEdot_error = 0.2f*STEdot_error + 0.8f*_STEdotErrLast;
_STEdotErrLast = STEdot_error;
// Calculate throttle demand
// If underspeed condition is set, then demand full throttle
if (_underspeed)
{
_throttle_dem_unc = 1.0f;
}
else
{
// Calculate gain scaler from specific energy error to throttle
float K_STE2Thr = 1 / (timeConstant() * (_STEdot_max - _STEdot_min));
// Calculate feed-forward throttle
float ff_throttle = 0;
float nomThr = aparm.throttle_cruise * 0.01f;
const Matrix3f &rotMat = _ahrs.get_dcm_matrix();
// Use the demanded rate of change of total energy as the feed-forward demand, but add
// additional component which scales with (1/cos(bank angle) - 1) to compensate for induced
// drag increase during turns.
float cosPhi = sqrtf((rotMat.a.y*rotMat.a.y) + (rotMat.b.y*rotMat.b.y));
STEdot_dem = STEdot_dem + _rollComp * (1.0f/constrain_float(cosPhi * cosPhi , 0.1f, 1.0f) - 1.0f);
ff_throttle = nomThr + STEdot_dem / (_STEdot_max - _STEdot_min) * (_THRmaxf - _THRminf);
// Calculate PD + FF throttle
_throttle_dem = (_STE_error + STEdot_error * _thrDamp) * K_STE2Thr + ff_throttle;
// Rate limit PD + FF throttle
// Calculate the throttle increment from the specified slew time
if (aparm.throttle_slewrate != 0) {
float thrRateIncr = _DT * (_THRmaxf - _THRminf) * aparm.throttle_slewrate * 0.01f;
_throttle_dem = constrain_float(_throttle_dem,
_last_throttle_dem - thrRateIncr,
_last_throttle_dem + thrRateIncr);
_last_throttle_dem = _throttle_dem;
}
// Calculate integrator state upper and lower limits
// Set to a value thqat will allow 0.1 (10%) throttle saturation to allow for noise on the demand
float integ_max = (_THRmaxf - _throttle_dem + 0.1f);
float integ_min = (_THRminf - _throttle_dem - 0.1f);
// Calculate integrator state, constraining state
// Set integrator to a max throttle value during climbout
_integ6_state = _integ6_state + (_STE_error * _integGain) * _DT * K_STE2Thr;
if (_flight_stage == AP_TECS::FLIGHT_TAKEOFF)
{
_integ6_state = integ_max;
}
else
{
_integ6_state = constrain_float(_integ6_state, integ_min, integ_max);
}
// Sum the components.
// Only use feed-forward component if airspeed is not being used
if (_ahrs.airspeed_sensor_enabled()) {
_throttle_dem = _throttle_dem + _integ6_state;
} else {
_throttle_dem = ff_throttle;
}
}
// Constrain throttle demand
_throttle_dem = constrain_float(_throttle_dem, _THRminf, _THRmaxf);
}
void AP_TECS::_update_throttle_option(int16_t throttle_nudge)
{
// Calculate throttle demand by interpolating between pitch and throttle limits
float nomThr;
//If landing and we don't have an airspeed sensor and we have a non-zero
//TECS_LAND_THR param then use it
if ((_flight_stage == FLIGHT_LAND_APPROACH || _flight_stage== FLIGHT_LAND_FINAL) &&
_landThrottle >= 0) {
nomThr = (_landThrottle + throttle_nudge) * 0.01f;
} else { //not landing or not using TECS_LAND_THR parameter
nomThr = (aparm.throttle_cruise + throttle_nudge)* 0.01f;
}
if (_flight_stage == AP_TECS::FLIGHT_TAKEOFF)
{
_throttle_dem = _THRmaxf;
}
else if (_pitch_dem > 0.0f && _PITCHmaxf > 0.0f)
{
_throttle_dem = nomThr + (_THRmaxf - nomThr) * _pitch_dem / _PITCHmaxf;
}
else if (_pitch_dem < 0.0f && _PITCHminf < 0.0f)
{
_throttle_dem = nomThr + (_THRminf - nomThr) * _pitch_dem / _PITCHminf;
}
else
{
_throttle_dem = nomThr;
}
// Calculate additional throttle for turn drag compensation including throttle nudging
const Matrix3f &rotMat = _ahrs.get_dcm_matrix();
// Use the demanded rate of change of total energy as the feed-forward demand, but add
// additional component which scales with (1/cos(bank angle) - 1) to compensate for induced
// drag increase during turns.
float cosPhi = sqrtf((rotMat.a.y*rotMat.a.y) + (rotMat.b.y*rotMat.b.y));
float STEdot_dem = _rollComp * (1.0f/constrain_float(cosPhi * cosPhi , 0.1f, 1.0f) - 1.0f);
_throttle_dem = _throttle_dem + STEdot_dem / (_STEdot_max - _STEdot_min) * (_THRmaxf - _THRminf);
}
void AP_TECS::_detect_bad_descent(void)
{
// Detect a demanded airspeed too high for the aircraft to achieve. This will be
// evident by the the following conditions:
// 1) Underspeed protection not active
// 2) Specific total energy error > 200 (greater than ~20m height error)
// 3) Specific total energy reducing
// 4) throttle demand > 90%
// If these four conditions exist simultaneously, then the protection
// mode will be activated.
// Once active, the following condition are required to stay in the mode
// 1) Underspeed protection not active
// 2) Specific total energy error > 0
// This mode will produce an undulating speed and height response as it cuts in and out but will prevent the aircraft from descending into the ground if an unachievable speed demand is set
float STEdot = _SPEdot + _SKEdot;
if ((!_underspeed && (_STE_error > 200.0f) && (STEdot < 0.0f) && (_throttle_dem >= _THRmaxf * 0.9f)) || (_badDescent && !_underspeed && (_STE_error > 0.0f)))
{
_badDescent = true;
}
else
{
_badDescent = false;
}
}
void AP_TECS::_update_pitch(void)
{
// Calculate Speed/Height Control Weighting
// This is used to determine how the pitch control prioritises speed and height control
// A weighting of 1 provides equal priority (this is the normal mode of operation)
// A SKE_weighting of 0 provides 100% priority to height control. This is used when no airspeed measurement is available
// A SKE_weighting of 2 provides 100% priority to speed control. This is used when an underspeed condition is detected. In this instance, if airspeed
// rises above the demanded value, the pitch angle will be increased by the TECS controller.
float SKE_weighting = constrain_float(_spdWeight, 0.0f, 2.0f);
if (!_ahrs.airspeed_sensor_enabled()) {
SKE_weighting = 0.0f;
} else if ( _underspeed || _flight_stage == AP_TECS::FLIGHT_TAKEOFF) {
SKE_weighting = 2.0f;
} else if (_flight_stage == AP_TECS::FLIGHT_LAND_APPROACH || _flight_stage == AP_TECS::FLIGHT_LAND_FINAL) {
SKE_weighting = constrain_float(_spdWeightLand, 0.0f, 2.0f);
}
float SPE_weighting = 2.0f - SKE_weighting;
// Calculate Specific Energy Balance demand, and error
float SEB_dem = _SPE_dem * SPE_weighting - _SKE_dem * SKE_weighting;
float SEBdot_dem = _SPEdot_dem * SPE_weighting - _SKEdot_dem * SKE_weighting;
float SEB_error = SEB_dem - (_SPE_est * SPE_weighting - _SKE_est * SKE_weighting);
float SEBdot_error = SEBdot_dem - (_SPEdot * SPE_weighting - _SKEdot * SKE_weighting);
// Calculate integrator state, constraining input if pitch limits are exceeded
float integ7_input = SEB_error * _integGain;
if (_pitch_dem_unc > _PITCHmaxf)
{
integ7_input = min(integ7_input, _PITCHmaxf - _pitch_dem_unc);
}
else if (_pitch_dem_unc < _PITCHminf)
{
integ7_input = max(integ7_input, _PITCHminf - _pitch_dem_unc);
}
_integ7_state = _integ7_state + integ7_input * _DT;
// Apply max and min values for integrator state that will allow for no more than
// 5deg of saturation. This allows for some pitch variation due to gusts before the
// integrator is clipped. Otherwise the effectiveness of the integrator will be reduced in turbulence
// During climbout/takeoff, bias the demanded pitch angle so that zero speed error produces a pitch angle
// demand equal to the minimum value (which is )set by the mission plan during this mode). Otherwise the
// integrator has to catch up before the nose can be raised to reduce speed during climbout.
float gainInv = (_integ5_state * timeConstant() * GRAVITY_MSS);
float temp = SEB_error + SEBdot_error * _ptchDamp + SEBdot_dem * timeConstant();
if (_flight_stage == AP_TECS::FLIGHT_TAKEOFF)
{
temp += _PITCHminf * gainInv;
}
_integ7_state = constrain_float(_integ7_state, (gainInv * (_PITCHminf - 0.0783f)) - temp, (gainInv * (_PITCHmaxf + 0.0783f)) - temp);
// Calculate pitch demand from specific energy balance signals
_pitch_dem_unc = (temp + _integ7_state) / gainInv;
// Constrain pitch demand
_pitch_dem = constrain_float(_pitch_dem_unc, _PITCHminf, _PITCHmaxf);
_pitch_dem = constrain_float(_pitch_dem_unc, _PITCHminf, _PITCHmaxf);
// Rate limit the pitch demand to comply with specified vertical
// acceleration limit
float ptchRateIncr = _DT * _vertAccLim / _integ5_state;
if ((_pitch_dem - _last_pitch_dem) > ptchRateIncr)
{
_pitch_dem = _last_pitch_dem + ptchRateIncr;
}
else if ((_pitch_dem - _last_pitch_dem) < -ptchRateIncr)
{
_pitch_dem = _last_pitch_dem - ptchRateIncr;
}
_last_pitch_dem = _pitch_dem;
}
void AP_TECS::_initialise_states(int32_t ptchMinCO_cd, float hgt_afe)
{
// Initialise states and variables if DT > 1 second or in climbout
if (_DT > 1.0f)
{
_integ6_state = 0.0f;
_integ7_state = 0.0f;
_last_throttle_dem = aparm.throttle_cruise * 0.01f;
_last_pitch_dem = _ahrs.pitch;
_hgt_dem_adj_last = hgt_afe;
_hgt_dem_adj = _hgt_dem_adj_last;
_hgt_dem_prev = _hgt_dem_adj_last;
_hgt_dem_in_old = _hgt_dem_adj_last;
_TAS_dem_last = _TAS_dem;
_TAS_dem_adj = _TAS_dem;
_underspeed = false;
_badDescent = false;
_DT = 0.1f; // when first starting TECS, use a
// small time constant
}
else if (_flight_stage == AP_TECS::FLIGHT_TAKEOFF)
{
_PITCHminf = 0.000174533f * ptchMinCO_cd;
_THRminf = _THRmaxf - 0.01f;
_hgt_dem_adj_last = hgt_afe;
_hgt_dem_adj = _hgt_dem_adj_last;
_hgt_dem_prev = _hgt_dem_adj_last;
_TAS_dem_last = _TAS_dem;
_TAS_dem_adj = _TAS_dem;
_underspeed = false;
_badDescent = false;
}
}
void AP_TECS::_update_STE_rate_lim(void)
{
// Calculate Specific Total Energy Rate Limits
// This is a trivial calculation at the moment but will get bigger once we start adding altitude effects
_STEdot_max = _maxClimbRate * GRAVITY_MSS;
_STEdot_min = - _minSinkRate * GRAVITY_MSS;
}
void AP_TECS::update_pitch_throttle(int32_t hgt_dem_cm,
int32_t EAS_dem_cm,
enum FlightStage flight_stage,
int32_t ptchMinCO_cd,
int16_t throttle_nudge,
float hgt_afe)
{
// Calculate time in seconds since last update
uint32_t now = hal.scheduler->micros();
_DT = max((now - _update_pitch_throttle_last_usec),0)*1.0e-6f;
_update_pitch_throttle_last_usec = now;
// Update the speed estimate using a 2nd order complementary filter
_update_speed();
// Convert inputs
_hgt_dem = hgt_dem_cm * 0.01f;
_EAS_dem = EAS_dem_cm * 0.01f;
_THRmaxf = aparm.throttle_max * 0.01f;
_THRminf = aparm.throttle_min * 0.01f;
// work out the maximum and minimum pitch
// if TECS_PITCH_{MAX,MIN} isn't set then use
// LIM_PITCH_{MAX,MIN}. Don't allow TECS_PITCH_{MAX,MIN} to be
// larger than LIM_PITCH_{MAX,MIN}
if (_pitch_max <= 0) {
_PITCHmaxf = aparm.pitch_limit_max_cd * 0.01f;
} else {
_PITCHmaxf = min(_pitch_max, aparm.pitch_limit_max_cd * 0.01f);
}
if (_pitch_min >= 0) {
_PITCHminf = aparm.pitch_limit_min_cd * 0.01f;
} else {
_PITCHminf = max(_pitch_min, aparm.pitch_limit_min_cd * 0.01f);
}
if (flight_stage == FLIGHT_LAND_FINAL) {
// in flare use min pitch from LAND_PITCH_CD
_PITCHminf = max(_PITCHminf, aparm.land_pitch_cd * 0.01f);
// and allow zero throttle
_THRminf = 0;
}
// convert to radians
_PITCHmaxf = radians(_PITCHmaxf);
_PITCHminf = radians(_PITCHminf);
_flight_stage = flight_stage;
// initialise selected states and variables if DT > 1 second or in climbout
_initialise_states(ptchMinCO_cd, hgt_afe);
// Calculate Specific Total Energy Rate Limits
_update_STE_rate_lim();
// Calculate the speed demand
_update_speed_demand();
// Calculate the height demand
_update_height_demand();
// Detect underspeed condition
_detect_underspeed();
// Calculate specific energy quantitiues
_update_energies();
// Calculate throttle demand - use simple pitch to throttle if no airspeed sensor
if (_ahrs.airspeed_sensor_enabled()) {
_update_throttle();
} else {
_update_throttle_option(throttle_nudge);
}
// Detect bad descent due to demanded airspeed being too high
_detect_bad_descent();
// Calculate pitch demand
_update_pitch();
// Write internal variables to the log_tuning structure. This
// structure will be logged in dataflash at 10Hz
log_tuning.hgt_dem = _hgt_dem_adj;
log_tuning.hgt = _integ3_state;
log_tuning.dhgt_dem = _hgt_rate_dem;
log_tuning.dhgt = _climb_rate;
log_tuning.spd_dem = _TAS_dem_adj;
log_tuning.spd = _integ5_state;
log_tuning.dspd = _vel_dot;
log_tuning.ithr = _integ6_state;
log_tuning.iptch = _integ7_state;
log_tuning.thr = _throttle_dem;
log_tuning.ptch = _pitch_dem;
log_tuning.dspd_dem = _TAS_rate_dem;
log_tuning.time_ms = hal.scheduler->millis();
}
// log the contents of the log_tuning structure to dataflash
void AP_TECS::log_data(DataFlash_Class &dataflash, uint8_t msgid)
{
log_tuning.head1 = HEAD_BYTE1;
log_tuning.head2 = HEAD_BYTE2;
log_tuning.msgid = msgid;
dataflash.WriteBlock(&log_tuning, sizeof(log_tuning));
}
| mrpollo/ardupilot | libraries/AP_TECS/AP_TECS.cpp | C++ | gpl-3.0 | 33,291 |
'use strict';
/**
* A class representation of the BSON Double type.
*/
class Double {
/**
* Create a Double type
*
* @param {number} value the number we want to represent as a double.
* @return {Double}
*/
constructor(value) {
this.value = value;
}
/**
* Access the number value.
*
* @method
* @return {number} returns the wrapped double number.
*/
valueOf() {
return this.value;
}
/**
* @ignore
*/
toJSON() {
return this.value;
}
/**
* @ignore
*/
toExtendedJSON(options) {
if (options && options.relaxed && isFinite(this.value)) return this.value;
return { $numberDouble: this.value.toString() };
}
/**
* @ignore
*/
static fromExtendedJSON(doc, options) {
return options && options.relaxed
? parseFloat(doc.$numberDouble)
: new Double(parseFloat(doc.$numberDouble));
}
}
Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' });
module.exports = Double;
| TamataOcean/TamataSpiru | node_modules/bson/lib/double.js | JavaScript | gpl-3.0 | 993 |
/*
* Copyright (C) 2013-2014 Dominik Schürmann <dominik@dominikschuermann.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 org.sufficientlysecure.keychain.ui.adapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.keyimport.ImportKeysListEntry;
import org.sufficientlysecure.keychain.pgp.KeyRing;
import org.sufficientlysecure.keychain.ui.util.FormattingUtils;
import org.sufficientlysecure.keychain.ui.util.Highlighter;
import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils;
import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils.State;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class ImportKeysAdapter extends ArrayAdapter<ImportKeysListEntry> {
protected LayoutInflater mInflater;
protected Activity mActivity;
protected List<ImportKeysListEntry> mData;
static class ViewHolder {
public TextView mainUserId;
public TextView mainUserIdRest;
public TextView keyId;
public TextView fingerprint;
public TextView algorithm;
public ImageView status;
public View userIdsDivider;
public LinearLayout userIdsList;
public CheckBox checkBox;
}
public ImportKeysAdapter(Activity activity) {
super(activity, -1);
mActivity = activity;
mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setData(List<ImportKeysListEntry> data) {
clear();
if (data != null) {
this.mData = data;
// add data to extended ArrayAdapter
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
addAll(data);
} else {
for (ImportKeysListEntry entry : data) {
add(entry);
}
}
}
}
public List<ImportKeysListEntry> getData() {
return mData;
}
/** This method returns a list of all selected entries, with public keys sorted
* before secret keys, see ImportExportOperation for specifics.
* @see org.sufficientlysecure.keychain.operations.ImportExportOperation
*/
public ArrayList<ImportKeysListEntry> getSelectedEntries() {
ArrayList<ImportKeysListEntry> result = new ArrayList<>();
ArrayList<ImportKeysListEntry> secrets = new ArrayList<>();
if (mData == null) {
return result;
}
for (ImportKeysListEntry entry : mData) {
if (entry.isSelected()) {
// add this entry to either the secret or the public list
(entry.isSecretKey() ? secrets : result).add(entry);
}
}
// add secret keys at the end of the list
result.addAll(secrets);
return result;
}
@Override
public boolean hasStableIds() {
return true;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImportKeysListEntry entry = mData.get(position);
Highlighter highlighter = new Highlighter(mActivity, entry.getQuery());
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.import_keys_list_item, null);
holder.mainUserId = (TextView) convertView.findViewById(R.id.import_item_user_id);
holder.mainUserIdRest = (TextView) convertView.findViewById(R.id.import_item_user_id_email);
holder.keyId = (TextView) convertView.findViewById(R.id.import_item_key_id);
holder.fingerprint = (TextView) convertView.findViewById(R.id.import_item_fingerprint);
holder.algorithm = (TextView) convertView.findViewById(R.id.import_item_algorithm);
holder.status = (ImageView) convertView.findViewById(R.id.import_item_status);
holder.userIdsDivider = convertView.findViewById(R.id.import_item_status_divider);
holder.userIdsList = (LinearLayout) convertView.findViewById(R.id.import_item_user_ids_list);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.import_item_selected);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// main user id
String userId = entry.getUserIds().get(0);
KeyRing.UserId userIdSplit = KeyRing.splitUserId(userId);
// name
if (userIdSplit.name != null) {
// show red user id if it is a secret key
if (entry.isSecretKey()) {
holder.mainUserId.setText(mActivity.getString(R.string.secret_key)
+ " " + userIdSplit.name);
} else {
holder.mainUserId.setText(highlighter.highlight(userIdSplit.name));
}
} else {
holder.mainUserId.setText(R.string.user_id_no_name);
}
// email
if (userIdSplit.email != null) {
holder.mainUserIdRest.setVisibility(View.VISIBLE);
holder.mainUserIdRest.setText(highlighter.highlight(userIdSplit.email));
} else {
holder.mainUserIdRest.setVisibility(View.GONE);
}
holder.keyId.setText(KeyFormattingUtils.beautifyKeyIdWithPrefix(getContext(), entry.getKeyIdHex()));
// don't show full fingerprint on key import
holder.fingerprint.setVisibility(View.GONE);
if (entry.getAlgorithm() != null) {
holder.algorithm.setText(entry.getAlgorithm());
holder.algorithm.setVisibility(View.VISIBLE);
} else {
holder.algorithm.setVisibility(View.GONE);
}
if (entry.isRevoked()) {
KeyFormattingUtils.setStatusImage(getContext(), holder.status, null, State.REVOKED, R.color.bg_gray);
} else if (entry.isExpired()) {
KeyFormattingUtils.setStatusImage(getContext(), holder.status, null, State.EXPIRED, R.color.bg_gray);
}
if (entry.isRevoked() || entry.isExpired()) {
holder.status.setVisibility(View.VISIBLE);
// no more space for algorithm display
holder.algorithm.setVisibility(View.GONE);
holder.mainUserId.setTextColor(getContext().getResources().getColor(R.color.bg_gray));
holder.mainUserIdRest.setTextColor(getContext().getResources().getColor(R.color.bg_gray));
holder.keyId.setTextColor(getContext().getResources().getColor(R.color.bg_gray));
} else {
holder.status.setVisibility(View.GONE);
holder.algorithm.setVisibility(View.VISIBLE);
if (entry.isSecretKey()) {
holder.mainUserId.setTextColor(Color.RED);
} else {
holder.mainUserId.setTextColor(Color.WHITE);
}
holder.mainUserIdRest.setTextColor(Color.WHITE);
holder.keyId.setTextColor(Color.WHITE);
}
if (entry.getUserIds().size() == 1) {
holder.userIdsList.setVisibility(View.GONE);
holder.userIdsDivider.setVisibility(View.GONE);
} else {
holder.userIdsList.setVisibility(View.VISIBLE);
holder.userIdsDivider.setVisibility(View.VISIBLE);
// destroyLoader view from holder
holder.userIdsList.removeAllViews();
// we want conventional gpg UserIDs first, then Keybase ”proofs”
HashMap<String, HashSet<String>> mergedUserIds = entry.getMergedUserIds();
ArrayList<Map.Entry<String, HashSet<String>>> sortedIds = new ArrayList<Map.Entry<String, HashSet<String>>>(mergedUserIds.entrySet());
java.util.Collections.sort(sortedIds, new java.util.Comparator<Map.Entry<String, HashSet<String>>>() {
@Override
public int compare(Map.Entry<String, HashSet<String>> entry1, Map.Entry<String, HashSet<String>> entry2) {
// sort keybase UserIds after non-Keybase
boolean e1IsKeybase = entry1.getKey().contains(":");
boolean e2IsKeybase = entry2.getKey().contains(":");
if (e1IsKeybase != e2IsKeybase) {
return (e1IsKeybase) ? 1 : -1;
}
return entry1.getKey().compareTo(entry2.getKey());
}
});
for (Map.Entry<String, HashSet<String>> pair : sortedIds) {
String cUserId = pair.getKey();
HashSet<String> cEmails = pair.getValue();
TextView uidView = (TextView) mInflater.inflate(
R.layout.import_keys_list_entry_user_id, null);
uidView.setText(highlighter.highlight(cUserId));
uidView.setPadding(0, 0, FormattingUtils.dpToPx(getContext(), 8), 0);
if (entry.isRevoked() || entry.isExpired()) {
uidView.setTextColor(getContext().getResources().getColor(R.color.bg_gray));
} else {
uidView.setTextColor(getContext().getResources().getColor(R.color.black));
}
holder.userIdsList.addView(uidView);
for (String email : cEmails) {
TextView emailView = (TextView) mInflater.inflate(
R.layout.import_keys_list_entry_user_id, null);
emailView.setPadding(
FormattingUtils.dpToPx(getContext(), 16), 0,
FormattingUtils.dpToPx(getContext(), 8), 0);
emailView.setText(highlighter.highlight(email));
if (entry.isRevoked() || entry.isExpired()) {
emailView.setTextColor(getContext().getResources().getColor(R.color.bg_gray));
} else {
emailView.setTextColor(getContext().getResources().getColor(R.color.black));
}
holder.userIdsList.addView(emailView);
}
}
}
holder.checkBox.setChecked(entry.isSelected());
return convertView;
}
}
| bresalio/apg | OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/adapter/ImportKeysAdapter.java | Java | gpl-3.0 | 11,323 |
package engine.gameScene;
import engine.gameController.GameController;
import engine.gameScene.url.Url;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.CacheHint;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.ToolBar;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import static javafx.scene.input.KeyCode.E;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
*
* @author Saeed
*/
public class SceneBuilder {
/**
* change stage to full screen
* @param stage Game Stage
* @return Stage
*/
public static Stage setFullScreen(Stage stage){
stage.setFullScreen(true);
stage.setResizable(true);
stage.setFullScreenExitHint("");
stage.setTitle("Stupid Warriors V1.0");
stage.getIcons().add(new Image(Url.ICON));
return stage ;
}
/**
*
* @param url url needed to create a fxmlLoader
* @param obj controller to set in fxml loader
* @return return Parent to add to scene
* @throws IOException
*/
public static Parent setFxmlLoader(URL url, Object obj) throws IOException{
FXMLLoader fxmlLoader = new FXMLLoader(url);
fxmlLoader.setController(obj);
return fxmlLoader.load();
}
public static ToolBar createGameToolBar(ToolBar toolbar){
Region spacer = new Region();
spacer.getStyleClass().setAll("spacer");
HBox buttonBar = new HBox();
buttonBar.getStyleClass().setAll("segmented-button-bar");
Button sampleButton = new Button("Tasks");
sampleButton.getStyleClass().addAll("first");
Button sampleButton2 = new Button("Administrator");
Button sampleButton3 = new Button("Search");
Button sampleButton4 = new Button("Line");
Button sampleButton5 = new Button("Process");
sampleButton5.getStyleClass().addAll("last", "capsule");
buttonBar.getChildren().addAll(sampleButton, sampleButton2, sampleButton3, sampleButton4, sampleButton5);
toolbar.getItems().addAll(spacer, buttonBar);
return toolbar;
}
public static void createTableBoardRight(ImageView scoutTower,
ImageView hammerHeadTower,
ImageView bulletTower,
ImageView teamUpgrade2,
ImageView teamUpgrade3,
ImageView teamUpgrade,
StackPane mainStack) {
//add to stack
mainStack.getChildren().addAll(scoutTower,hammerHeadTower,bulletTower,teamUpgrade,teamUpgrade2,teamUpgrade3);
//set position
StackPane.setAlignment(scoutTower, Pos.BOTTOM_RIGHT);
StackPane.setAlignment(hammerHeadTower, Pos.BOTTOM_RIGHT);
StackPane.setAlignment(bulletTower, Pos.BOTTOM_RIGHT);
StackPane.setAlignment(teamUpgrade, Pos.BOTTOM_RIGHT);
StackPane.setAlignment(teamUpgrade2, Pos.BOTTOM_RIGHT);
StackPane.setAlignment(teamUpgrade3, Pos.BOTTOM_RIGHT);
//set translate x,y
scoutTower.setTranslateX(-10);
scoutTower.setTranslateY(-80);
hammerHeadTower.setTranslateX(-200);
hammerHeadTower.setTranslateY(-90);
bulletTower.setTranslateX(-100);
bulletTower.setTranslateY(-80);
teamUpgrade.setTranslateX(-10);
teamUpgrade.setTranslateY(-10);
teamUpgrade2.setTranslateX(-200);
teamUpgrade2.setTranslateY(-10);
teamUpgrade3.setTranslateX(-100);
teamUpgrade3.setTranslateY(-10);
}
public static void createTableBoardLeftSoldier(ImageView infantrySoldier, ImageView tankSoldier, StackPane mainStack) {
StackPane.setAlignment(infantrySoldier, Pos.BOTTOM_LEFT);
StackPane.setAlignment(tankSoldier, Pos.BOTTOM_LEFT);
double x = 40;
double y = -50;
double imgX = infantrySoldier.getImage().getWidth();
infantrySoldier.setTranslateX(x);
infantrySoldier.setTranslateY(y);
tankSoldier.setTranslateX(x+imgX+30);
tankSoldier.setTranslateY(y);
mainStack.getChildren().addAll(infantrySoldier,tankSoldier);
}
public static void createTableBoarderLeftTower(ImageView towerAutoRepair, ImageView towerPowerUpgrade, ImageView towerRangeUpgrade, ImageView towerReloadUpgrade,StackPane mainStack) {
StackPane.setAlignment(towerReloadUpgrade, Pos.BOTTOM_LEFT);
StackPane.setAlignment(towerPowerUpgrade, Pos.BOTTOM_LEFT);
StackPane.setAlignment(towerRangeUpgrade, Pos.BOTTOM_LEFT);
StackPane.setAlignment(towerAutoRepair, Pos.BOTTOM_LEFT);
//posotion
double x = 20;
double y = -78;
double imgX = towerRangeUpgrade.getImage().getWidth();
towerPowerUpgrade.setTranslateX(x);
towerPowerUpgrade.setTranslateY(y);
towerRangeUpgrade.setTranslateX(imgX+x+10);
towerRangeUpgrade.setTranslateY(y);
towerReloadUpgrade.setTranslateX(imgX*2+x+20);
towerReloadUpgrade.setTranslateY(y);
towerAutoRepair.setTranslateX(120);
towerAutoRepair.setTranslateY(-10);
//tooltip
mainStack.getChildren().addAll(towerAutoRepair,towerPowerUpgrade,towerRangeUpgrade,towerReloadUpgrade);
}
public static void createTableBoardLeftMap(StackPane mainStack) {
}
}
| smasoumi/stupidwarriors | src/engine/gameScene/SceneBuilder.java | Java | gpl-3.0 | 5,638 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Measure
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* Implement needed classes
*/
// require_once 'Zend/Measure/Abstract.php';
// require_once 'Zend/Locale.php';
/**
* Class for handling capacitance conversions
*
* @category Zend
* @package Zend_Measure
* @subpackage Zend_Measure_Capacitance
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Measure_Capacitance extends Zend_Measure_Abstract
{
const STANDARD = 'FARAD';
const ABFARAD = 'ABFARAD';
const AMPERE_PER_SECOND_VOLT = 'AMPERE_PER_SECOND_VOLT';
const CENTIFARAD = 'CENTIFARAD';
const COULOMB_PER_VOLT = 'COULOMB_PER_VOLT';
const DECIFARAD = 'DECIFARAD';
const DEKAFARAD = 'DEKAFARAD';
const ELECTROMAGNETIC_UNIT = 'ELECTROMAGNETIC_UNIT';
const ELECTROSTATIC_UNIT = 'ELECTROSTATIC_UNIT';
const FARAD = 'FARAD';
const FARAD_INTERNATIONAL = 'FARAD_INTERNATIONAL';
const GAUSSIAN = 'GAUSSIAN';
const GIGAFARAD = 'GIGAFARAD';
const HECTOFARAD = 'HECTOFARAD';
const JAR = 'JAR';
const KILOFARAD = 'KILOFARAD';
const MEGAFARAD = 'MEGAFARAD';
const MICROFARAD = 'MICROFARAD';
const MILLIFARAD = 'MILLIFARAD';
const NANOFARAD = 'NANOFARAD';
const PICOFARAD = 'PICOFARAD';
const PUFF = 'PUFF';
const SECOND_PER_OHM = 'SECOND_PER_OHM';
const STATFARAD = 'STATFARAD';
const TERAFARAD = 'TERAFARAD';
/**
* Calculations for all capacitance units
*
* @var array
*/
protected $_units = array(
'ABFARAD' => array('1.0e+9', 'abfarad'),
'AMPERE_PER_SECOND_VOLT' => array('1', 'A/sV'),
'CENTIFARAD' => array('0.01', 'cF'),
'COULOMB_PER_VOLT' => array('1', 'C/V'),
'DECIFARAD' => array('0.1', 'dF'),
'DEKAFARAD' => array('10', 'daF'),
'ELECTROMAGNETIC_UNIT' => array('1.0e+9', 'capacity emu'),
'ELECTROSTATIC_UNIT' => array('1.11265e-12', 'capacity esu'),
'FARAD' => array('1', 'F'),
'FARAD_INTERNATIONAL' => array('0.99951', 'F'),
'GAUSSIAN' => array('1.11265e-12', 'G'),
'GIGAFARAD' => array('1.0e+9', 'GF'),
'HECTOFARAD' => array('100', 'hF'),
'JAR' => array('1.11265e-9', 'jar'),
'KILOFARAD' => array('1000', 'kF'),
'MEGAFARAD' => array('1000000', 'MF'),
'MICROFARAD' => array('0.000001', 'µF'),
'MILLIFARAD' => array('0.001', 'mF'),
'NANOFARAD' => array('1.0e-9', 'nF'),
'PICOFARAD' => array('1.0e-12', 'pF'),
'PUFF' => array('1.0e-12', 'pF'),
'SECOND_PER_OHM' => array('1', 's/Ohm'),
'STATFARAD' => array('1.11265e-12', 'statfarad'),
'TERAFARAD' => array('1.0e+12', 'TF'),
'STANDARD' => 'FARAD'
);
}
| boydjd/openfisma | library/Zend/Measure/Capacitance.php | PHP | gpl-3.0 | 4,107 |
/// <reference path = "EscenaActividad.ts" />
/// <reference path = "../../dependencias/pilasweb.d.ts"/>
/// <reference path = "../actores/Cuadricula.ts"/>
/// <reference path = "../actores/PerroCohete.ts"/>
/// <reference path = "../comportamientos/MovimientosEnCuadricula.ts"/>
/**
* @class TresNaranjas
*
*/
class TresNaranjas extends EscenaActividad {
fondo;
automata;
cuadricula;
objetos = [];
iniciar() {
this.fondo = new Fondo('fondo.tresNaranjas.png',0,0);
this.cuadricula = new Cuadricula(0,0,1,4,
{separacionEntreCasillas: 5},
{grilla: 'casilla.tresNaranjas.png', ancho:100,alto:100});
//se cargan los Naranjas
var hayAlMenosUno = false;
for(var i = 0; i < 3; i++) {
if (Math.random() < .5) {
hayAlMenosUno = true;
this.agregarNaranja(i+1);
}
}
if (!hayAlMenosUno) {
var columna = 1;
var rand = Math.random()
if (rand> 0.33 && rand<0.66) {
columna = 2;
} else if (rand > 0.66) {
columna = 3
}
this.agregarNaranja(columna);
}
// se crea el personaje
this.automata = new MarcianoAnimado(0,0);
this.cuadricula.agregarActor(this.automata,0,0);
}
agregarNaranja(columna) {
var objeto = new NaranjaAnimada(0,0);
this.cuadricula.agregarActor(objeto,0,columna);
this.objetos.push(objeto);
}
estaResueltoElProblema(){
return this.contarActoresConEtiqueta('NaranjaAnimada')==0 && this.automata.estaEnCasilla(null,3);
}
}
| bit0Ar/pilas-bloques | releases/pilas-engine-bloques-linux-ia32/resources/app/ejerciciosPilas/src/escenas/TresNaranjas.ts | TypeScript | gpl-3.0 | 1,676 |
/*
* Copyright (C) 2015-2016 Willi Ye <williye97@gmail.com>
*
* This file is part of Kernel Adiutor.
*
* Kernel Adiutor 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.
*
* Kernel Adiutor 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 Kernel Adiutor. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.grarak.kerneladiutor.activities;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.grarak.kerneladiutor.R;
import com.grarak.kerneladiutor.utils.Prefs;
import com.grarak.kerneladiutor.utils.Utils;
import com.grarak.kerneladiutor.utils.ViewUtils;
import java.util.HashMap;
/**
* Created by willi on 14.04.16.
*/
public class BaseActivity extends AppCompatActivity {
private static HashMap<String, Integer> sAccentColors = new HashMap<>();
private static HashMap<String, Integer> sAccentDarkColors = new HashMap<>();
static {
sAccentColors.put("red_accent", R.style.Theme_Red);
sAccentColors.put("pink_accent", R.style.Theme_Pink);
sAccentColors.put("purple_accent", R.style.Theme_Purple);
sAccentColors.put("blue_accent", R.style.Theme_Blue);
sAccentColors.put("green_accent", R.style.Theme_Green);
sAccentColors.put("orange_accent", R.style.Theme_Orange);
sAccentColors.put("brown_accent", R.style.Theme_Brown);
sAccentColors.put("grey_accent", R.style.Theme_Grey);
sAccentColors.put("blue_grey_accent", R.style.Theme_BlueGrey);
sAccentColors.put("teal_accent", R.style.Theme_Teal);
sAccentDarkColors.put("red_accent", R.style.Theme_Red_Dark);
sAccentDarkColors.put("pink_accent", R.style.Theme_Pink_Dark);
sAccentDarkColors.put("purple_accent", R.style.Theme_Purple_Dark);
sAccentDarkColors.put("blue_accent", R.style.Theme_Blue_Dark);
sAccentDarkColors.put("green_accent", R.style.Theme_Green_Dark);
sAccentDarkColors.put("orange_accent", R.style.Theme_Orange_Dark);
sAccentDarkColors.put("brown_accent", R.style.Theme_Brown_Dark);
sAccentDarkColors.put("grey_accent", R.style.Theme_Grey_Dark);
sAccentDarkColors.put("blue_grey_accent", R.style.Theme_BlueGrey_Dark);
sAccentDarkColors.put("teal_accent", R.style.Theme_Teal_Dark);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
Utils.DARK_THEME = Prefs.getBoolean("darktheme", false, this);
int theme;
String accent = Prefs.getString("accent_color", "pink_accent", this);
if (Utils.DARK_THEME) {
theme = sAccentDarkColors.get(accent);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
theme = sAccentColors.get(accent);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
setTheme(theme);
super.onCreate(savedInstanceState);
if (Prefs.getBoolean("forceenglish", false, this)) {
Utils.setLocale("en_US", this);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && setStatusBarColor()) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(statusBarColor());
}
}
public AppBarLayout getAppBarLayout() {
return (AppBarLayout) findViewById(R.id.appbarlayout);
}
public Toolbar getToolBar() {
return (Toolbar) findViewById(R.id.toolbar);
}
public void initToolBar() {
Toolbar toolbar = getToolBar();
if (toolbar != null) {
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
protected boolean setStatusBarColor() {
return true;
}
protected int statusBarColor() {
return ViewUtils.getColorPrimaryDarkColor(this);
}
}
| randomstuffpaul/KernelAdiutor | app/src/main/java/com/grarak/kerneladiutor/activities/BaseActivity.java | Java | gpl-3.0 | 5,069 |
/*
* Copyright (C) 2007-2017 Crafter Software Corporation.
*
* 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 org.craftercms.commons.logging;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation used to indicate that a method (or all methods of a class, if used in a class) should be logged.
*
* @author avasquez
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Logged {
}
| dejan-brkic/commons | utilities/src/main/java/org/craftercms/commons/logging/Logged.java | Java | gpl-3.0 | 1,171 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.ComponentModel;
using System.Data;
namespace ECommerce.Utility.DataAccess.Database.Config
{
[XmlRoot("dataOperations", Namespace = "http://oversea.ECommerce.com/DataOperation")]
public partial class DataOperations
{
[XmlElement("dataCommand")]
public DataCommandConfig[] DataCommand
{
get;
set;
}
}
[XmlRoot("dataCommand")]
public partial class DataCommandConfig
{
private CommandType m_CommandType = CommandType.Text;
private int m_TimeOut = 300;
[XmlElement("commandText")]
public string CommandText
{
get;
set;
}
[XmlElement("parameters")]
public Parameters Parameters
{
get;
set;
}
[XmlAttribute("name")]
public string Name
{
get;
set;
}
[XmlAttributeAttribute("database")]
public string Database
{
get;
set;
}
[XmlAttributeAttribute("commandType")]
[DefaultValueAttribute(CommandType.Text)]
public CommandType CommandType
{
get
{
return this.m_CommandType;
}
set
{
this.m_CommandType = value;
}
}
[XmlAttributeAttribute("timeOut")]
[DefaultValueAttribute(300)]
public int TimeOut
{
get
{
return this.m_TimeOut;
}
set
{
this.m_TimeOut = value;
}
}
public DataCommandConfig Clone()
{
DataCommandConfig config = new DataCommandConfig();
config.CommandText = this.CommandText;
config.CommandType = this.CommandType;
config.Database = this.Database;
config.Name = this.Name;
config.Parameters = this.Parameters == null ? null : this.Parameters.Clone();
config.TimeOut = this.TimeOut;
return config;
}
}
[XmlRoot("parameters")]
public partial class Parameters
{
[XmlElement("param")]
public Param[] Param
{
get;
set;
}
public Parameters Clone()
{
Parameters p = new Parameters();
if (this.Param != null)
{
p.Param = new Param[this.Param.Length];
for (int i = 0; i < this.Param.Length; i++)
{
p.Param[i] = this.Param[i].Clone();
}
}
return p;
}
}
[XmlRoot("param")]
public partial class Param
{
private ParameterDirection m_Direction = ParameterDirection.Input;
private int m_Size = -1;
private byte m_Scale = 0;
private byte m_Precision = 0;
public Param Clone()
{
Param p = new Param();
p.DbType = this.DbType;
p.Direction = this.Direction;
p.Name = this.Name;
p.Precision = this.Precision;
p.Property = this.Property;
p.Scale = this.Scale;
p.Size = this.Size;
return p;
}
[XmlAttribute("name")]
public string Name
{
get;
set;
}
[XmlAttribute("dbType")]
public DbType DbType
{
get;
set;
}
[XmlAttribute("direction")]
[DefaultValue(ParameterDirection.Input)]
public ParameterDirection Direction
{
get
{
return this.m_Direction;
}
set
{
this.m_Direction = value;
}
}
[XmlAttribute("size")]
[DefaultValue(-1)]
public int Size
{
get
{
return this.m_Size;
}
set
{
this.m_Size = value;
}
}
[XmlAttribute("scale")]
[DefaultValue(0)]
public byte Scale
{
get
{
return this.m_Scale;
}
set
{
this.m_Scale = value;
}
}
[XmlAttribute("precision")]
[DefaultValue(0)]
public byte Precision
{
get
{
return this.m_Precision;
}
set
{
this.m_Precision = value;
}
}
[XmlAttribute("property")]
public string Property
{
get;
set;
}
}
}
| ZeroOne71/ql | 03_SellerPortal/ECommerce.Utility.DataAccess/RLDB/Config/DataOperations.cs | C# | gpl-3.0 | 4,968 |
using System;
using AutoMapper;
using Machete.Web.Helpers;
using static Machete.Web.Helpers.Extensions;
namespace Machete.Web.Maps
{
public class WorkerSigninProfile : Profile
{
public WorkerSigninProfile()
{
CreateMap<Domain.WorkerSignin, Service.DTO.WorkerSigninList>()
.ForMember(v => v.englishlevel, opt => opt.MapFrom(d => d == null ? 0 : d.worker.englishlevelID))
.ForMember(v => v.waid, opt => opt.MapFrom(d => d.WorkAssignmentID))
.ForMember(v => v.skill1, opt => opt.MapFrom(d => d == null ? null : d.worker.skill1))
.ForMember(v => v.skill2, opt => opt.MapFrom(d => d == null ? null : d.worker.skill2))
.ForMember(v => v.skill3, opt => opt.MapFrom(d => d == null ? null : d.worker.skill3))
.ForMember(v => v.program, opt => opt.MapFrom(d => d.worker.typeOfWork))
.ForMember(v => v.skillCodes, opt => opt.MapFrom(d => d.worker.skillCodes))
.ForMember(v => v.lotterySequence, opt => opt.MapFrom(d => d.lottery_sequence))
.ForMember(v => v.fullname, opt => opt.MapFrom(d =>
$"{d.worker.Person.firstname1} {d.worker.Person.firstname2} {d.worker.Person.lastname1} {d.worker.Person.lastname2}")
)
.ForMember(v => v.firstname1, opt => opt.MapFrom(d => d.worker.Person.firstname1))
.ForMember(v => v.firstname2, opt => opt.MapFrom(d => d.worker.Person.firstname2))
.ForMember(v => v.lastname1, opt => opt.MapFrom(d => d.worker.Person.lastname1))
.ForMember(v => v.lastname2, opt => opt.MapFrom(d => d.worker.Person.lastname2))
.ForMember(v => v.expirationDate, opt => opt.MapFrom(d => d.worker.memberexpirationdate))
.ForMember(v => v.memberStatusID, opt => opt.MapFrom(d => d.worker.memberStatusID))
.ForMember(v => v.memberStatusEN, opt => opt.MapFrom(d => d.worker.memberStatusEN))
.ForMember(v => v.memberStatusES, opt => opt.MapFrom(d => d.worker.memberStatusES))
.ForMember(v => v.memberExpired, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iExpired))
.ForMember(v => v.memberInactive, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iInactive))
.ForMember(v => v.memberSanctioned, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iSanctioned))
.ForMember(v => v.memberExpelled, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iExpelled))
.ForMember(v => v.imageRef, opt => opt.MapFrom(d => d.worker.ImageID == null ? "/Content/images/NO-IMAGE-AVAILABLE.jpg" : "/Image/GetImage/" + d.worker.ImageID))
.ForMember(v => v.imageID, opt => opt.MapFrom(d => d.worker.ImageID))
.ForMember(v => v.typeOfWorkID, opt => opt.MapFrom(d => d.worker.typeOfWorkID))
.ForMember(v => v.signinID, opt => opt.MapFrom(d => d.ID))
;
CreateMap<Domain.WorkerSignin, ViewModel.WorkerSignin>()
.ForMember(v => v.memberExpired, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iExpired))
.ForMember(v => v.memberInactive, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iInactive))
.ForMember(v => v.memberSanctioned, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iSanctioned))
.ForMember(v => v.memberExpelled, opt => opt.MapFrom(d => d.worker.memberStatusID == Domain.Worker.iExpelled))
.ForMember(v => v.imageRef, opt => opt.MapFrom(d => d.worker.ImageID == null ? "/Content/images/NO-IMAGE-AVAILABLE.jpg" : "/Image/GetImage/" + d.worker.ImageID))
.ForMember(v => v.message, opt => opt.MapFrom(src => "success"))
.ForMember(v => v.worker, opt => opt.Ignore())
.ForMember(v => v.def, opt => opt.Ignore())
.ForMember(v => v.idString, opt => opt.Ignore())
.ForMember(v => v.tabref, opt => opt.Ignore())
.ForMember(v => v.tablabel, opt => opt.Ignore())
;
CreateMap<Service.DTO.WorkerSigninList, ViewModel.WorkerSigninList>()
.ForMember(v => v.recordid, opt => opt.MapFrom(d => d.ID))
.ForMember(v => v.WSIID, opt => opt.MapFrom(d => d.ID))
.ForMember(v => v.expirationDate, opt => opt.MapFrom(d => d.expirationDate.ToShortDateString()))
.ForMember(v => v.memberStatus,
opt => opt.MapFrom(d => getCI() == "ES" ? d.memberStatusES : d.memberStatusEN))
.ForMember(v => v.dateforsignin, opt => opt.MapFrom(d => d.dateforsignin))
.ForMember(v => v.dateforsigninstring, opt => opt.MapFrom(d =>
d.dateforsignin.UtcToClientString("hh:mm:ss tt"))
)
;
}
}
}
| SavageLearning/Machete | Machete.Web/Maps/Legacy/WorkerSigninProfile.cs | C# | gpl-3.0 | 5,028 |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Quote\Model\GuestCartManagement\Plugin;
use Magento\Framework\Exception\StateException;
class Authorization
{
/**
* @var \Magento\Authorization\Model\UserContextInterface
*/
protected $userContext;
/**
* @param \Magento\Authorization\Model\UserContextInterface $userContext
*/
public function __construct(
\Magento\Authorization\Model\UserContextInterface $userContext
) {
$this->userContext = $userContext;
}
/**
* @param \Magento\Quote\Model\GuestCart\GuestCartManagement $subject
* @param string $cartId
* @param int $customerId
* @param int $storeId
* @throws StateException
* @return void
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function beforeAssignCustomer(
\Magento\Quote\Model\GuestCart\GuestCartManagement $subject,
$cartId,
$customerId,
$storeId
) {
if ($customerId !== (int)$this->userContext->getUserId()) {
throw new StateException(
__('Cannot assign customer to the given cart. You don\'t have permission for this operation.')
);
}
}
}
| rajmahesh/magento2-master | vendor/magento/module-quote/Model/GuestCartManagement/Plugin/Authorization.php | PHP | gpl-3.0 | 1,301 |
package nl.knaw.huygens.timbuctoo.v5.dropwizard.contenttypes;
import nl.knaw.huygens.timbuctoo.v5.dropwizard.SupportedExportFormats;
import java.util.HashMap;
import java.util.Optional;
import java.util.Set;
import static java.lang.String.format;
public class SerializerWriterRegistry implements SupportedExportFormats {
private HashMap<String, SerializerWriter> supportedMimeTypes;
public SerializerWriterRegistry(SerializerWriter... writers) {
supportedMimeTypes = new HashMap<>();
for (SerializerWriter writer : writers) {
register(writer);
}
}
@Override
public Set<String> getSupportedMimeTypes() {
return supportedMimeTypes.keySet();
}
private void register(SerializerWriter serializerWriter) {
String mimeType = serializerWriter.getMimeType();
SerializerWriter added = supportedMimeTypes.putIfAbsent(mimeType, serializerWriter);
if (added != null) {
throw new RuntimeException(format("Timbuctoo supports only one serializer writer for '%s'", mimeType));
}
}
public Optional<SerializerWriter> getBestMatch(String acceptHeader) {
return MimeParser.bestMatch(supportedMimeTypes.keySet(), acceptHeader).map(supportedMimeTypes::get);
}
}
| HuygensING/timbuctoo | timbuctoo-instancev4/src/main/java/nl/knaw/huygens/timbuctoo/v5/dropwizard/contenttypes/SerializerWriterRegistry.java | Java | gpl-3.0 | 1,216 |
package org.bukkit.craftbukkit.event;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import org.bukkit.event.player.PlayerInteractEvent;
public class CraftEventFactory
{
public static org.bukkit.event.player.PlayerInteractEvent callPlayerInteractEvent(EntityPlayer player, org.bukkit.event.block.Action action, ItemStack stack){
return callPlayerInteractEvent(player, action, 0, 256, 0, 0, stack);
}
public static org.bukkit.event.player.PlayerInteractEvent callPlayerInteractEvent(EntityPlayer player, org.bukkit.event.block.Action action, int x, int y, int z, int face, ItemStack stack){
return new PlayerInteractEvent();
}
} | GotoLink/Battlegear2 | src/api/java/org/bukkit/craftbukkit/event/CraftEventFactory.java | Java | gpl-3.0 | 693 |
package tsb.examenFinal.util;
import java.util.Stack;
/**
*
* Verifica el balanceo de caractertes de apertura y cierre
* como [] {} <>
*/
public abstract class Balance {
public static boolean isBalanced(final String str, final char c0, final char c1) {
boolean toReturn;
if (c0 == c1) {
toReturn = isSameBalanced(str, c0);
} else {
toReturn = isNotSameBalanced(str, c0, c1);
}
return toReturn;
}
private static boolean isSameBalanced(final String str, final char c0) {
char[] array = str.toCharArray();
int count = 0;
for (int i = 0; i < array.length; i++) {
char c = array[i];
if (c == c0) {
count++;
}
}
int proc = (count / 2) * 2;
return (count == proc);
}
private static boolean isNotSameBalanced(final String str, final char c0, final char c1) {
char[] array = str.toCharArray();
Stack<String> stack = new Stack<String>();
for (int i = 0; i < array.length; i++) {
char c = array[i];
if (c == c0) {
stack.add(String.valueOf(c));
} else if (c == c1) {
if (stack.isEmpty() == false && stack.peek().charAt(0) == c0) {
stack.pop();
} else {
stack.push(String.valueOf(c));
}
}
}
return stack.isEmpty();
}
}
| javiermatias/jbc-utn-frc | 3ro/TSB/final/util/src/tsb/examenFinal/util/Balance.java | Java | gpl-3.0 | 1,495 |
/*
Scripts for cnprog.com
Project Name: Lanai
All Rights Resevred 2008. CNPROG.COM
*/
var lanai = {
/**
* Finds any <pre><code></code></pre> tags which aren't registered for
* pretty printing, adds the appropriate class name and invokes prettify.
*/
highlightSyntax: function(){
var styled = false;
$("pre code").parent().each(function(){
if (!$(this).hasClass('prettyprint')){
$(this).addClass('prettyprint');
styled = true;
}
});
if (styled){
prettyPrint();
}
}
};
//todo: clean-up now there is utils:WaitIcon
function appendLoader(element) {
loading = gettext('loading...')
element.append('<img class="ajax-loader" ' +
'src="' + mediaUrl("media/images/indicator.gif") + '" title="' +
loading +
'" alt="' +
loading +
'" />');
}
function removeLoader() {
$("img.ajax-loader").remove();
}
function setSubmitButtonDisabled(form, isDisabled) {
form.find('input[type="submit"]').attr("disabled", isDisabled);
}
function enableSubmitButton(form) {
setSubmitButtonDisabled(form, false);
}
function disableSubmitButton(form) {
setSubmitButtonDisabled(form, true);
}
function setupFormValidation(form, validationRules, validationMessages, onSubmitCallback) {
enableSubmitButton(form);
form.validate({
debug: true,
rules: (validationRules ? validationRules : {}),
messages: (validationMessages ? validationMessages : {}),
errorElement: "span",
errorClass: "form-error",
errorPlacement: function(error, element) {
var span = element.next().find("span.form-error");
if (span.length === 0) {
span = element.parent().find("span.form-error");
if (span.length === 0){
//for resizable textarea
var element_id = element.attr('id');
span = $('label[for="' + element_id + '"]');
}
}
span.replaceWith(error);
},
submitHandler: function(form_dom) {
disableSubmitButton($(form_dom));
if (onSubmitCallback){
onSubmitCallback();
}
else{
form_dom.submit();
}
}
});
}
/**
* generic tag cleaning function, settings
* are from askbot live settings and askbot.const
*/
var cleanTag = function(tag_name, settings) {
var tag_regex = new RegExp(settings['tag_regex']);
if (tag_regex.test(tag_name) === false) {
throw settings['messages']['wrong_chars']
}
var max_length = settings['max_tag_length'];
if (tag_name.length > max_length) {
throw interpolate(
ngettext(
'must be shorter than %(max_chars)s character',
'must be shorter than %(max_chars)s characters',
max_length
),
{'max_chars': max_length },
true
);
}
if (settings['force_lowercase_tags']) {
return tag_name.toLowerCase();
} else {
return tag_name;
}
};
var validateTagLength = function(value){
var tags = getUniqueWords(value);
var are_tags_ok = true;
$.each(tags, function(index, value){
if (value.length > askbot['settings']['maxTagLength']){
are_tags_ok = false;
}
});
return are_tags_ok;
};
var validateTagCount = function(value){
var tags = getUniqueWords(value);
return (tags.length <= askbot['settings']['maxTagsPerPost']);
};
$.validator.addMethod('limit_tag_count', validateTagCount);
$.validator.addMethod('limit_tag_length', validateTagLength);
var CPValidator = function() {
return {
getQuestionFormRules : function() {
return {
tags: {
required: askbot['settings']['tagsAreRequired'],
maxlength: 105,
limit_tag_count: true,
limit_tag_length: true
},
text: {
minlength: askbot['settings']['minQuestionBodyLength']
},
title: {
minlength: askbot['settings']['minTitleLength']
}
};
},
getQuestionFormMessages: function(){
return {
tags: {
required: " " + gettext('tags cannot be empty'),
maxlength: askbot['messages']['tagLimits'],
limit_tag_count: askbot['messages']['maxTagsPerPost'],
limit_tag_length: askbot['messages']['maxTagLength']
},
text: {
required: " " + gettext('details are required'),
minlength: interpolate(
ngettext(
'details must have > %s character',
'details must have > %s characters',
askbot['settings']['minQuestionBodyLength']
),
[askbot['settings']['minQuestionBodyLength'], ]
)
},
title: {
required: " " + gettext('enter your question'),
minlength: interpolate(
ngettext(
'question must have > %s character',
'question must have > %s characters',
askbot['settings']['minTitleLength']
),
[askbot['settings']['minTitleLength'], ]
)
}
};
},
getAnswerFormRules : function(){
return {
text: {
minlength: askbot['settings']['minAnswerBodyLength']
},
};
},
getAnswerFormMessages: function(){
return {
text: {
required: " " + gettext('content cannot be empty'),
minlength: interpolate(
ngettext(
'answer must be > %s character',
'answer must be > %s characters',
askbot['settings']['minAnswerBodyLength']
),
[askbot['settings']['minAnswerBodyLength'], ]
)
},
}
}
};
}();
/**
* @constructor
*/
var ThreadUsersDialog = function() {
SimpleControl.call(this);
this._heading_text = 'Add heading with the setHeadingText()';
};
inherits(ThreadUsersDialog, SimpleControl);
ThreadUsersDialog.prototype.setHeadingText = function(text) {
this._heading_text = text;
};
ThreadUsersDialog.prototype.showUsers = function(html) {
this._dialog.setContent(html);
this._dialog.show();
};
ThreadUsersDialog.prototype.startShowingUsers = function() {
var me = this;
var threadId = this._threadId;
var url = this._url;
$.ajax({
type: 'GET',
data: {'thread_id': threadId},
dataType: 'json',
url: url,
cache: false,
success: function(data){
if (data['success'] == true){
me.showUsers(data['html']);
} else {
showMessage(me.getElement(), data['message'], 'after');
}
}
});
};
ThreadUsersDialog.prototype.decorate = function(element) {
this._element = element;
ThreadUsersDialog.superClass_.decorate.call(this, element);
this._threadId = element.data('threadId');
this._url = element.data('url');
var dialog = new ModalDialog();
dialog.setRejectButtonText('');
dialog.setAcceptButtonText(gettext('Back to the question'));
dialog.setHeadingText(this._heading_text);
dialog.setAcceptHandler(function(){ dialog.hide(); });
var dialog_element = dialog.getElement();
$(dialog_element).find('.modal-footer').css('text-align', 'center');
$(document).append(dialog_element);
this._dialog = dialog;
var me = this;
this.setHandler(function(){
me.startShowingUsers();
});
};
/**
* @constructor
*/
var DraftPost = function() {
WrappedElement.call(this);
};
inherits(DraftPost, WrappedElement);
/**
* @return {string}
*/
DraftPost.prototype.getUrl = function() {
throw 'Not Implemented';
};
/**
* @return {boolean}
*/
DraftPost.prototype.shouldSave = function() {
throw 'Not Implemented';
};
/**
* @return {object} data dict
*/
DraftPost.prototype.getData = function() {
throw 'Not Implemented';
};
DraftPost.prototype.backupData = function() {
this._old_data = this.getData();
};
DraftPost.prototype.showNotification = function() {
var note = $('.editor-status span');
note.hide();
note.html(gettext('draft saved...'));
note.fadeIn().delay(3000).fadeOut();
};
DraftPost.prototype.getSaveHandler = function() {
var me = this;
return function(save_synchronously) {
if (me.shouldSave()) {
$.ajax({
type: 'POST',
cache: false,
dataType: 'json',
async: save_synchronously ? false : true,
url: me.getUrl(),
data: me.getData(),
success: function(data) {
if (data['success'] && !save_synchronously) {
me.showNotification();
}
me.backupData();
}
});
}
};
};
DraftPost.prototype.decorate = function(element) {
this._element = element;
this.assignContentElements();
this.backupData();
setInterval(this.getSaveHandler(), 30000);//auto-save twice a minute
var me = this;
window.onbeforeunload = function() {
var saveHandler = me.getSaveHandler();
saveHandler(true);
//var msg = gettext("%s, we've saved your draft, but...");
//return interpolate(msg, [askbot['data']['userName']]);
};
};
/**
* @contstructor
*/
var DraftQuestion = function() {
DraftPost.call(this);
};
inherits(DraftQuestion, DraftPost);
DraftQuestion.prototype.getUrl = function() {
return askbot['urls']['saveDraftQuestion'];
};
DraftQuestion.prototype.shouldSave = function() {
var newd = this.getData();
var oldd = this._old_data;
return (
newd['title'] !== oldd['title'] ||
newd['text'] !== oldd['text'] ||
newd['tagnames'] !== oldd['tagnames']
);
};
DraftQuestion.prototype.getData = function() {
return {
'title': this._title_element.val(),
'text': this._text_element.val(),
'tagnames': this._tagnames_element.val()
};
};
DraftQuestion.prototype.assignContentElements = function() {
this._title_element = $('#id_title');
this._text_element = $('#editor');
this._tagnames_element = $('#id_tags');
};
var DraftAnswer = function() {
DraftPost.call(this);
};
inherits(DraftAnswer, DraftPost);
DraftAnswer.prototype.setThreadId = function(id) {
this._threadId = id;
};
DraftAnswer.prototype.getUrl = function() {
return askbot['urls']['saveDraftAnswer'];
};
DraftAnswer.prototype.shouldSave = function() {
return this.getData()['text'] !== this._old_data['text'];
};
DraftAnswer.prototype.getData = function() {
return {
'text': this._textElement.val(),
'thread_id': this._threadId
};
};
DraftAnswer.prototype.assignContentElements = function() {
this._textElement = $('#editor');
};
/**
* @constructor
* @extends {SimpleControl}
* @param {Comment} comment to upvote
*/
var CommentVoteButton = function(comment){
SimpleControl.call(this);
/**
* @param {Comment}
*/
this._comment = comment;
/**
* @type {boolean}
*/
this._voted = false;
/**
* @type {number}
*/
this._score = 0;
};
inherits(CommentVoteButton, SimpleControl);
/**
* @param {number} score
*/
CommentVoteButton.prototype.setScore = function(score){
this._score = score;
if (this._element){
this._element.html(score);
}
};
/**
* @param {boolean} voted
*/
CommentVoteButton.prototype.setVoted = function(voted){
this._voted = voted;
if (this._element){
this._element.addClass('upvoted');
}
};
CommentVoteButton.prototype.getVoteHandler = function(){
var me = this;
var comment = this._comment;
return function(){
var voted = me._voted;
var post_id = me._comment.getId();
var data = {
cancel_vote: voted ? true:false,
post_id: post_id
};
$.ajax({
type: 'POST',
data: data,
dataType: 'json',
url: askbot['urls']['upvote_comment'],
cache: false,
success: function(data){
if (data['success'] == true){
me.setScore(data['score']);
me.setVoted(true);
} else {
showMessage(comment.getElement(), data['message'], 'after');
}
}
});
};
};
CommentVoteButton.prototype.decorate = function(element){
this._element = element;
this.setHandler(this.getVoteHandler());
var element = this._element;
var comment = this._comment;
/* can't call comment.getElement() here due
* an issue in the getElement() of comment
* so use an "illegal" access to comment._element here
*/
comment._element.mouseenter(function(){
//outside height may not be known
//var height = comment.getElement().height();
//element.height(height);
element.addClass('hover');
});
comment._element.mouseleave(function(){
element.removeClass('hover');
});
};
CommentVoteButton.prototype.createDom = function(){
this._element = this.makeElement('div');
if (this._score > 0){
this._element.html(this._score);
}
this._element.addClass('upvote');
if (this._voted){
this._element.addClass('upvoted');
}
this.decorate(this._element);
};
/**
* legacy Vote class
* handles all sorts of vote-like operations
*/
var Vote = function(){
// All actions are related to a question
var questionId;
//question slug to build redirect urls
var questionSlug;
// The object we operate on actually. It can be a question or an answer.
var postId;
var questionAuthorId;
var currentUserId;
var answerContainerIdPrefix = 'post-id-';
var voteContainerId = 'vote-buttons';
var imgIdPrefixAccept = 'answer-img-accept-';
var classPrefixFollow= 'button follow';
var classPrefixFollowed= 'button followed';
var imgIdPrefixQuestionVoteup = 'question-img-upvote-';
var imgIdPrefixQuestionVotedown = 'question-img-downvote-';
var imgIdPrefixAnswerVoteup = 'answer-img-upvote-';
var imgIdPrefixAnswerVotedown = 'answer-img-downvote-';
var divIdFavorite = 'favorite-number';
var commentLinkIdPrefix = 'comment-';
var voteNumberClass = "vote-number";
var offensiveIdPrefixQuestionFlag = 'question-offensive-flag-';
var removeOffensiveIdPrefixQuestionFlag = 'question-offensive-remove-flag-';
var removeAllOffensiveIdPrefixQuestionFlag = 'question-offensive-remove-all-flag-';
var offensiveIdPrefixAnswerFlag = 'answer-offensive-flag-';
var removeOffensiveIdPrefixAnswerFlag = 'answer-offensive-remove-flag-';
var removeAllOffensiveIdPrefixAnswerFlag = 'answer-offensive-remove-all-flag-';
var offensiveClassFlag = 'offensive-flag';
var questionControlsId = 'question-controls';
var removeAnswerLinkIdPrefix = 'answer-delete-link-';
var questionSubscribeUpdates = 'question-subscribe-updates';
var questionSubscribeSidebar= 'question-subscribe-sidebar';
var acceptAnonymousMessage = gettext('insufficient privilege');
var acceptOwnAnswerMessage = gettext('cannot pick own answer as best');
var pleaseLogin = " <a href='" + askbot['urls']['user_signin'] + ">"
+ gettext('please login') + "</a>";
var favoriteAnonymousMessage = gettext('anonymous users cannot follow questions') + pleaseLogin;
var subscribeAnonymousMessage = gettext('anonymous users cannot subscribe to questions') + pleaseLogin;
var voteAnonymousMessage = gettext('anonymous users cannot vote') + pleaseLogin;
//there were a couple of more messages...
var offensiveConfirmation = gettext('please confirm offensive');
var removeOffensiveConfirmation = gettext('please confirm removal of offensive flag');
var offensiveAnonymousMessage = gettext('anonymous users cannot flag offensive posts') + pleaseLogin;
var removeConfirmation = gettext('confirm delete');
var removeAnonymousMessage = gettext('anonymous users cannot delete/undelete') + pleaseLogin;
var recoveredMessage = gettext('post recovered');
var deletedMessage = gettext('post deleted');
var VoteType = {
acceptAnswer : 0,
questionUpVote : 1,
questionDownVote : 2,
favorite : 4,
answerUpVote: 5,
answerDownVote:6,
offensiveQuestion : 7,
removeOffensiveQuestion : 7.5,
removeAllOffensiveQuestion : 7.6,
offensiveAnswer:8,
removeOffensiveAnswer:8.5,
removeAllOffensiveAnswer:8.6,
removeQuestion: 9,//deprecate
removeAnswer:10,//deprecate
questionSubscribeUpdates:11,
questionUnsubscribeUpdates:12
};
var getFavoriteButton = function(){
var favoriteButton = 'div.'+ voteContainerId +' a[class="'+ classPrefixFollow +'"]';
favoriteButton += ', div.'+ voteContainerId +' a[class="'+ classPrefixFollowed +'"]';
return $(favoriteButton);
};
var getFavoriteNumber = function(){
var favoriteNumber = '#'+ divIdFavorite ;
return $(favoriteNumber);
};
var getQuestionVoteUpButton = function(){
var questionVoteUpButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixQuestionVoteup +'"]';
return $(questionVoteUpButton);
};
var getQuestionVoteDownButton = function(){
var questionVoteDownButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixQuestionVotedown +'"]';
return $(questionVoteDownButton);
};
var getAnswerVoteUpButtons = function(){
var answerVoteUpButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixAnswerVoteup +'"]';
return $(answerVoteUpButton);
};
var getAnswerVoteDownButtons = function(){
var answerVoteDownButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixAnswerVotedown +'"]';
return $(answerVoteDownButton);
};
var getAnswerVoteUpButton = function(id){
var answerVoteUpButton = 'div.'+ voteContainerId +' div[id="'+ imgIdPrefixAnswerVoteup + id + '"]';
return $(answerVoteUpButton);
};
var getAnswerVoteDownButton = function(id){
var answerVoteDownButton = 'div.'+ voteContainerId +' div[id="'+ imgIdPrefixAnswerVotedown + id + '"]';
return $(answerVoteDownButton);
};
var getOffensiveQuestionFlag = function(){
var offensiveQuestionFlag = '.question-card span[id^="'+ offensiveIdPrefixQuestionFlag +'"]';
return $(offensiveQuestionFlag);
};
var getRemoveOffensiveQuestionFlag = function(){
var removeOffensiveQuestionFlag = '.question-card span[id^="'+ removeOffensiveIdPrefixQuestionFlag +'"]';
return $(removeOffensiveQuestionFlag);
};
var getRemoveAllOffensiveQuestionFlag = function(){
var removeAllOffensiveQuestionFlag = '.question-card span[id^="'+ removeAllOffensiveIdPrefixQuestionFlag +'"]';
return $(removeAllOffensiveQuestionFlag);
};
var getOffensiveAnswerFlags = function(){
var offensiveQuestionFlag = 'div.answer span[id^="'+ offensiveIdPrefixAnswerFlag +'"]';
return $(offensiveQuestionFlag);
};
var getRemoveOffensiveAnswerFlag = function(){
var removeOffensiveAnswerFlag = 'div.answer span[id^="'+ removeOffensiveIdPrefixAnswerFlag +'"]';
return $(removeOffensiveAnswerFlag);
};
var getRemoveAllOffensiveAnswerFlag = function(){
var removeAllOffensiveAnswerFlag = 'div.answer span[id^="'+ removeAllOffensiveIdPrefixAnswerFlag +'"]';
return $(removeAllOffensiveAnswerFlag);
};
var getquestionSubscribeUpdatesCheckbox = function(){
return $('#' + questionSubscribeUpdates);
};
var getquestionSubscribeSidebarCheckbox= function(){
return $('#' + questionSubscribeSidebar);
};
var getremoveAnswersLinks = function(){
var removeAnswerLinks = 'div.answer-controls a[id^="'+ removeAnswerLinkIdPrefix +'"]';
return $(removeAnswerLinks);
};
var setVoteImage = function(voteType, undo, object){
var flag = undo ? false : true;
if (object.hasClass("on")) {
object.removeClass("on");
}else{
object.addClass("on");
}
if(undo){
if(voteType == VoteType.questionUpVote || voteType == VoteType.questionDownVote){
$(getQuestionVoteUpButton()).removeClass("on");
$(getQuestionVoteDownButton()).removeClass("on");
}
else{
$(getAnswerVoteUpButton(postId)).removeClass("on");
$(getAnswerVoteDownButton(postId)).removeClass("on");
}
}
};
var setVoteNumber = function(object, number){
var voteNumber = object.parent('div.'+ voteContainerId).find('div.'+ voteNumberClass);
$(voteNumber).text(number);
};
var bindEvents = function(){
// accept answers
var acceptedButtons = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixAccept +'"]';
$(acceptedButtons).unbind('click').click(function(event){
Vote.accept($(event.target));
});
// set favorite question
var favoriteButton = getFavoriteButton();
favoriteButton.unbind('click').click(function(event){
//Vote.favorite($(event.target));
Vote.favorite(favoriteButton);
});
// question vote up
var questionVoteUpButton = getQuestionVoteUpButton();
questionVoteUpButton.unbind('click').click(function(event){
Vote.vote($(event.target), VoteType.questionUpVote);
});
var questionVoteDownButton = getQuestionVoteDownButton();
questionVoteDownButton.unbind('click').click(function(event){
Vote.vote($(event.target), VoteType.questionDownVote);
});
var answerVoteUpButton = getAnswerVoteUpButtons();
answerVoteUpButton.unbind('click').click(function(event){
Vote.vote($(event.target), VoteType.answerUpVote);
});
var answerVoteDownButton = getAnswerVoteDownButtons();
answerVoteDownButton.unbind('click').click(function(event){
Vote.vote($(event.target), VoteType.answerDownVote);
});
getOffensiveQuestionFlag().unbind('click').click(function(event){
Vote.offensive(this, VoteType.offensiveQuestion);
});
getRemoveOffensiveQuestionFlag().unbind('click').click(function(event){
Vote.remove_offensive(this, VoteType.removeOffensiveQuestion);
});
getRemoveAllOffensiveQuestionFlag().unbind('click').click(function(event){
Vote.remove_all_offensive(this, VoteType.removeAllOffensiveQuestion);
});
getOffensiveAnswerFlags().unbind('click').click(function(event){
Vote.offensive(this, VoteType.offensiveAnswer);
});
getRemoveOffensiveAnswerFlag().unbind('click').click(function(event){
Vote.remove_offensive(this, VoteType.removeOffensiveAnswer);
});
getRemoveAllOffensiveAnswerFlag().unbind('click').click(function(event){
Vote.remove_all_offensive(this, VoteType.removeAllOffensiveAnswer);
});
getquestionSubscribeUpdatesCheckbox().unbind('click').click(function(event){
//despeluchar esto
if (this.checked){
getquestionSubscribeSidebarCheckbox().attr({'checked': true});
Vote.vote($(event.target), VoteType.questionSubscribeUpdates);
}
else {
getquestionSubscribeSidebarCheckbox().attr({'checked': false});
Vote.vote($(event.target), VoteType.questionUnsubscribeUpdates);
}
});
getquestionSubscribeSidebarCheckbox().unbind('click').click(function(event){
if (this.checked){
getquestionSubscribeUpdatesCheckbox().attr({'checked': true});
Vote.vote($(event.target), VoteType.questionSubscribeUpdates);
}
else {
getquestionSubscribeUpdatesCheckbox().attr({'checked': false});
Vote.vote($(event.target), VoteType.questionUnsubscribeUpdates);
}
});
getremoveAnswersLinks().unbind('click').click(function(event){
Vote.remove(this, VoteType.removeAnswer);
});
};
var submit = function(object, voteType, callback) {
//this function submits votes
$.ajax({
type: "POST",
cache: false,
dataType: "json",
url: askbot['urls']['vote_url'],
data: { "type": voteType, "postId": postId },
error: handleFail,
success: function(data) {
callback(object, voteType, data);
}
});
};
var handleFail = function(xhr, msg){
alert("Callback invoke error: " + msg);
};
// callback function for Accept Answer action
var callback_accept = function(object, voteType, data){
if(data.allowed == "0" && data.success == "0"){
showMessage(object, acceptAnonymousMessage);
}
else if(data.allowed == "-1"){
showMessage(object, acceptOwnAnswerMessage);
}
else if(data.status == "1"){
$("#"+answerContainerIdPrefix+postId).removeClass("accepted-answer");
$("#"+commentLinkIdPrefix+postId).removeClass("comment-link-accepted");
}
else if(data.success == "1"){
var answers = ('div[id^="'+answerContainerIdPrefix +'"]');
$(answers).removeClass('accepted-answer');
var commentLinks = ('div[id^="'+answerContainerIdPrefix +'"] div[id^="'+ commentLinkIdPrefix +'"]');
$(commentLinks).removeClass("comment-link-accepted");
$("#"+answerContainerIdPrefix+postId).addClass("accepted-answer");
$("#"+commentLinkIdPrefix+postId).addClass("comment-link-accepted");
}
else{
showMessage(object, data.message);
}
};
var callback_favorite = function(object, voteType, data){
if(data.allowed == "0" && data.success == "0"){
showMessage(
object,
favoriteAnonymousMessage.replace(
'{{QuestionID}}',
questionId).replace(
'{{questionSlug}}',
''
)
);
}
else if(data.status == "1"){
var follow_html = gettext('Follow');
object.attr("class", 'button follow');
object.html(follow_html);
var fav = getFavoriteNumber();
fav.removeClass("my-favorite-number");
if(data.count === 0){
data.count = '';
fav.text('');
}else{
var fmts = ngettext('%s follower', '%s followers', data.count);
fav.text(interpolate(fmts, [data.count]));
}
}
else if(data.success == "1"){
var followed_html = gettext('<div>Following</div><div class="unfollow">Unfollow</div>');
object.html(followed_html);
object.attr("class", 'button followed');
var fav = getFavoriteNumber();
var fmts = ngettext('%s follower', '%s followers', data.count);
fav.text(interpolate(fmts, [data.count]));
fav.addClass("my-favorite-number");
}
else{
showMessage(object, data.message);
}
};
var callback_vote = function(object, voteType, data){
if (data.success == '0'){
showMessage(object, data.message);
return;
}
else {
if (data.status == '1'){
setVoteImage(voteType, true, object);
}
else {
setVoteImage(voteType, false, object);
}
setVoteNumber(object, data.count);
if (data.message && data.message.length > 0){
showMessage(object, data.message);
}
return;
}
//may need to take a look at this again
if (data.status == "1"){
setVoteImage(voteType, true, object);
setVoteNumber(object, data.count);
}
else if (data.success == "1"){
setVoteImage(voteType, false, object);
setVoteNumber(object, data.count);
if (data.message.length > 0){
showMessage(object, data.message);
}
}
};
var callback_offensive = function(object, voteType, data){
//todo: transfer proper translations of these from i18n.js
//to django.po files
//_('anonymous users cannot flag offensive posts') + pleaseLogin;
if (data.success == "1"){
if(data.count > 0)
$(object).children('span[class="darkred"]').text("("+ data.count +")");
else
$(object).children('span[class="darkred"]').text("");
// Change the link text and rebind events
$(object).find("a.question-flag").html(gettext("remove flag"));
var obj_id = $(object).attr("id");
$(object).attr("id", obj_id.replace("flag-", "remove-flag-"));
getRemoveOffensiveQuestionFlag().unbind('click').click(function(event){
Vote.remove_offensive(this, VoteType.removeOffensiveQuestion);
});
getRemoveOffensiveAnswerFlag().unbind('click').click(function(event){
Vote.remove_offensive(this, VoteType.removeOffensiveAnswer);
});
}
else {
object = $(object);
showMessage(object, data.message)
}
};
var callback_remove_offensive = function(object, voteType, data){
//todo: transfer proper translations of these from i18n.js
//to django.po files
//_('anonymous users cannot flag offensive posts') + pleaseLogin;
if (data.success == "1"){
if(data.count > 0){
$(object).children('span[class="darkred"]').text("("+ data.count +")");
}
else{
$(object).children('span[class="darkred"]').text("");
// Remove "remove all flags link" since there are no more flags to remove
var remove_all = $(object).siblings('span.offensive-flag[id*="-offensive-remove-all-flag-"]');
$(remove_all).next("span.sep").remove();
$(remove_all).remove();
}
// Change the link text and rebind events
$(object).find("a.question-flag").html(gettext("flag offensive"));
var obj_id = $(object).attr("id");
$(object).attr("id", obj_id.replace("remove-flag-", "flag-"));
getOffensiveQuestionFlag().unbind('click').click(function(event){
Vote.offensive(this, VoteType.offensiveQuestion);
});
getOffensiveAnswerFlags().unbind('click').click(function(event){
Vote.offensive(this, VoteType.offensiveAnswer);
});
}
else {
object = $(object);
showMessage(object, data.message)
}
};
var callback_remove_all_offensive = function(object, voteType, data){
//todo: transfer proper translations of these from i18n.js
//to django.po files
//_('anonymous users cannot flag offensive posts') + pleaseLogin;
if (data.success == "1"){
if(data.count > 0)
$(object).children('span[class="darkred"]').text("("+ data.count +")");
else
$(object).children('span[class="darkred"]').text("");
// remove the link. All flags are gone
var remove_own = $(object).siblings('span.offensive-flag[id*="-offensive-remove-flag-"]');
$(remove_own).find("a.question-flag").html(gettext("flag offensive"));
$(remove_own).attr("id", $(remove_own).attr("id").replace("remove-flag-", "flag-"));
$(object).next("span.sep").remove();
$(object).remove();
getOffensiveQuestionFlag().unbind('click').click(function(event){
Vote.offensive(this, VoteType.offensiveQuestion);
});
getOffensiveAnswerFlags().unbind('click').click(function(event){
Vote.offensive(this, VoteType.offensiveAnswer);
});
}
else {
object = $(object);
showMessage(object, data.message)
}
};
var callback_remove = function(object, voteType, data){
if (data.success == "1"){
if (removeActionType == 'delete'){
postNode.addClass('deleted');
postRemoveLink.innerHTML = gettext('undelete');
showMessage(object, deletedMessage);
}
else if (removeActionType == 'undelete') {
postNode.removeClass('deleted');
postRemoveLink.innerHTML = gettext('delete');
showMessage(object, recoveredMessage);
}
}
else {
showMessage(object, data.message)
}
};
return {
init : function(qId, qSlug, questionAuthor, userId){
questionId = qId;
questionSlug = qSlug;
questionAuthorId = questionAuthor;
currentUserId = '' + userId;//convert to string
bindEvents();
},
//accept answer
accept: function(object){
postId = object.attr("id").substring(imgIdPrefixAccept.length);
submit(object, VoteType.acceptAnswer, callback_accept);
},
//mark question as favorite
favorite: function(object){
if (!currentUserId || currentUserId.toUpperCase() == "NONE"){
showMessage(
object,
favoriteAnonymousMessage.replace(
"{{QuestionID}}",
questionId
).replace(
'{{questionSlug}}',
questionSlug
)
);
return false;
}
postId = questionId;
submit(object, VoteType.favorite, callback_favorite);
},
vote: function(object, voteType){
if (!currentUserId || currentUserId.toUpperCase() == "NONE") {
if (voteType == VoteType.questionSubscribeUpdates || voteType == VoteType.questionUnsubscribeUpdates){
getquestionSubscribeSidebarCheckbox().removeAttr('checked');
getquestionSubscribeUpdatesCheckbox().removeAttr('checked');
showMessage(object, subscribeAnonymousMessage);
} else {
showMessage(
$(object),
voteAnonymousMessage.replace(
"{{QuestionID}}",
questionId
).replace(
'{{questionSlug}}',
questionSlug
)
);
}
return false;
}
// up and downvote processor
if (voteType == VoteType.answerUpVote){
postId = object.attr("id").substring(imgIdPrefixAnswerVoteup.length);
} else if (voteType == VoteType.answerDownVote){
postId = object.attr("id").substring(imgIdPrefixAnswerVotedown.length);
} else {
postId = questionId;
}
submit(object, voteType, callback_vote);
},
//flag offensive
offensive: function(object, voteType){
if (!currentUserId || currentUserId.toUpperCase() == "NONE"){
showMessage(
$(object),
offensiveAnonymousMessage.replace(
"{{QuestionID}}",
questionId
).replace(
'{{questionSlug}}',
questionSlug
)
);
return false;
}
if (confirm(offensiveConfirmation)){
postId = object.id.substr(object.id.lastIndexOf('-') + 1);
submit(object, voteType, callback_offensive);
}
},
//remove flag offensive
remove_offensive: function(object, voteType){
if (!currentUserId || currentUserId.toUpperCase() == "NONE"){
showMessage(
$(object),
offensiveAnonymousMessage.replace(
"{{QuestionID}}",
questionId
).replace(
'{{questionSlug}}',
questionSlug
)
);
return false;
}
if (confirm(removeOffensiveConfirmation)){
postId = object.id.substr(object.id.lastIndexOf('-') + 1);
submit(object, voteType, callback_remove_offensive);
}
},
remove_all_offensive: function(object, voteType){
if (!currentUserId || currentUserId.toUpperCase() == "NONE"){
showMessage(
$(object),
offensiveAnonymousMessage.replace(
"{{QuestionID}}",
questionId
).replace(
'{{questionSlug}}',
questionSlug
)
);
return false;
}
if (confirm(removeOffensiveConfirmation)){
postId = object.id.substr(object.id.lastIndexOf('-') + 1);
submit(object, voteType, callback_remove_all_offensive);
}
},
//delete question or answer (comments are deleted separately)
remove: function(object, voteType){
if (!currentUserId || currentUserId.toUpperCase() == "NONE"){
showMessage(
$(object),
removeAnonymousMessage.replace(
'{{QuestionID}}',
questionId
).replace(
'{{questionSlug}}',
questionSlug
)
);
return false;
}
bits = object.id.split('-');
postId = bits.pop();/* this seems to be used within submit! */
postType = bits.shift();
var do_proceed = false;
postNode = $('#post-id-' + postId);
postRemoveLink = object;
if (postNode.hasClass('deleted')) {
removeActionType = 'undelete';
do_proceed = true;
} else {
removeActionType = 'delete';
do_proceed = confirm(removeConfirmation);
}
if (do_proceed) {
submit($(object), voteType, callback_remove);
}
}
};
} ();
var questionRetagger = function(){
var oldTagsHTML = '';
var tagInput = null;
var tagsDiv = null;
var retagLink = null;
var restoreEventHandlers = function(){
$(document).unbind('click');
};
var cancelRetag = function(){
tagsDiv.html(oldTagsHTML);
tagsDiv.removeClass('post-retag');
tagsDiv.addClass('post-tags');
restoreEventHandlers();
initRetagger();
};
var drawNewTags = function(new_tags){
tagsDiv.empty();
if (new_tags === ''){
return;
}
new_tags = new_tags.split(/\s+/);
var tags_html = ''
$.each(new_tags, function(index, name){
var tag = new Tag();
tag.setName(name);
tagsDiv.append(tag.getElement());
});
};
var doRetag = function(){
$.ajax({
type: "POST",
url: retagUrl,//todo add this url to askbot['urls']
dataType: "json",
data: { tags: getUniqueWords(tagInput.val()).join(' ') },
success: function(json) {
if (json['success'] === true){
new_tags = getUniqueWords(json['new_tags']);
oldTagsHtml = '';
cancelRetag();
drawNewTags(new_tags.join(' '));
if (json['message']) {
notify.show(json['message']);
}
}
else {
cancelRetag();
showMessage(tagsDiv, json['message']);
}
},
error: function(xhr, textStatus, errorThrown) {
showMessage(tagsDiv, gettext('sorry, something is not right here'));
cancelRetag();
}
});
return false;
}
var setupInputEventHandlers = function(input){
input.keydown(function(e){
if ((e.which && e.which == 27) || (e.keyCode && e.keyCode == 27)){
cancelRetag();
}
});
$(document).unbind('click').click(cancelRetag, false);
input.click(function(){return false});
};
var createRetagForm = function(old_tags_string){
var div = $('<form method="post"></form>');
tagInput = $('<input id="retag_tags" type="text" autocomplete="off" name="tags" size="30"/>');
//var tagLabel = $('<label for="retag_tags" class="error"></label>');
//populate input
var tagAc = new AutoCompleter({
url: askbot['urls']['get_tag_list'],
minChars: 1,
useCache: true,
matchInside: true,
maxCacheLength: 100,
delay: 10
});
tagAc.decorate(tagInput);
tagInput.val(old_tags_string);
div.append(tagInput);
//div.append(tagLabel);
setupInputEventHandlers(tagInput);
//button = $('<input type="submit" />');
//button.val(gettext('save tags'));
//div.append(button);
//setupButtonEventHandlers(button);
div.validate({//copy-paste from utils.js
rules: {
tags: {
required: askbot['settings']['tagsAreRequired'],
maxlength: askbot['settings']['maxTagsPerPost'] * askbot['settings']['maxTagLength'],
limit_tag_count: true,
limit_tag_length: true
}
},
messages: {
tags: {
required: gettext('tags cannot be empty'),
maxlength: askbot['messages']['tagLimits'],
limit_tag_count: askbot['messages']['maxTagsPerPost'],
limit_tag_length: askbot['messages']['maxTagLength']
}
},
submitHandler: doRetag,
errorClass: "retag-error"
});
return div;
};
var getTagsAsString = function(tags_div){
var links = tags_div.find('a');
var tags_str = '';
links.each(function(index, element){
if (index === 0){
//this is pretty bad - we should use Tag.getName()
tags_str = $(element).data('tagName');
}
else {
tags_str += ' ' + $(element).data('tagName');
}
});
return tags_str;
};
var noopHandler = function(){
tagInput.focus();
return false;
};
var deactivateRetagLink = function(){
retagLink.unbind('click').click(noopHandler);
retagLink.unbind('keypress').keypress(noopHandler);
};
var startRetag = function(){
tagsDiv = $('#question-tags');
oldTagsHTML = tagsDiv.html();//save to restore on cancel
var old_tags_string = getTagsAsString(tagsDiv);
var retag_form = createRetagForm(old_tags_string);
tagsDiv.html('');
tagsDiv.append(retag_form);
tagsDiv.removeClass('post-tags');
tagsDiv.addClass('post-retag');
tagInput.focus();
deactivateRetagLink();
return false;
};
var setupClickAndEnterHandler = function(element, callback){
element.unbind('click').click(callback);
element.unbind('keypress').keypress(function(e){
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)){
callback();
}
});
}
var initRetagger = function(){
setupClickAndEnterHandler(retagLink, startRetag);
};
return {
init: function(){
retagLink = $('#retag');
initRetagger();
}
};
}();
/**
* @constructor
* Controls vor voting for a post
*/
var VoteControls = function() {
WrappedElement.call(this);
this._postAuthorId = undefined;
this._postId = undefined;
};
inherits(VoteControls, WrappedElement);
VoteControls.prototype.setPostId = function(postId) {
this._postId = postId;
};
VoteControls.prototype.getPostId = function() {
return this._postId;
};
VoteControls.prototype.setPostAuthorId = function(userId) {
this._postAuthorId = userId;
};
VoteControls.prototype.setSlug = function(slug) {
this._slug = slug;
};
VoteControls.prototype.setPostType = function(postType) {
this._postType = postType;
};
VoteControls.prototype.getPostType = function() {
return this._postType;
};
VoteControls.prototype.clearVotes = function() {
this._upvoteButton.removeClass('on');
this._downvoteButton.removeClass('on');
};
VoteControls.prototype.toggleButton = function(button) {
if (button.hasClass('on')) {
button.removeClass('on');
} else {
button.addClass('on');
}
};
VoteControls.prototype.toggleVote = function(voteType) {
if (voteType === 'upvote') {
this.toggleButton(this._upvoteButton);
} else {
this.toggleButton(this._downvoteButton);
}
};
VoteControls.prototype.setVoteCount = function(count) {
this._voteCount.html(count);
};
VoteControls.prototype.updateDisplay = function(voteType, data) {
if (data['status'] == '1'){
this.clearVotes();
} else {
this.toggleVote(voteType);
}
this.setVoteCount(data['count']);
if (data['message'] && data['message'].length > 0){
showMessage(this._element, data.message);
}
};
VoteControls.prototype.getAnonymousMessage = function(message) {
var pleaseLogin = " <a href='" + askbot['urls']['user_signin'] + ">"
+ gettext('please login') + "</a>";
message += pleaseLogin;
message = message.replace("{{QuestionID}}", this._postId);
return message.replace('{{questionSlug}}', this._slug);
};
VoteControls.prototype.getVoteHandler = function(voteType) {
var me = this;
return function() {
if (askbot['data']['userIsAuthenticated'] === false) {
var message = me.getAnonymousMessage(gettext('anonymous users cannot vote'));
showMessage(me.getElement(), message);
} else {
//this function submits votes
var voteMap = {
'question': { 'upvote': 1, 'downvote': 2 },
'answer': { 'upvote': 5, 'downvote': 6 }
};
var legacyVoteType = voteMap[me.getPostType()][voteType];
$.ajax({
type: "POST",
cache: false,
dataType: "json",
url: askbot['urls']['vote_url'],
data: {
"type": legacyVoteType,
"postId": me.getPostId()
},
error: function() {
showMessage(me.getElement(), gettext('sorry, something is not right here'));
},
success: function(data) {
if (data['success']) {
me.updateDisplay(voteType, data);
} else {
showMessage(me.getElement(), data['message']);
}
}
});
}
};
};
VoteControls.prototype.decorate = function(element) {
this._element = element;
var upvoteButton = element.find('.upvote');
this._upvoteButton = upvoteButton;
setupButtonEventHandlers(upvoteButton, this.getVoteHandler('upvote'));
var downvoteButton = element.find('.downvote');
this._downvoteButton = downvoteButton;
setupButtonEventHandlers(downvoteButton, this.getVoteHandler('downvote'));
this._voteCount = element.find('.vote-number');
};
var DeletePostLink = function(){
SimpleControl.call(this);
this._post_id = null;
};
inherits(DeletePostLink, SimpleControl);
DeletePostLink.prototype.setPostId = function(id){
this._post_id = id;
};
DeletePostLink.prototype.getPostId = function(){
return this._post_id;
};
DeletePostLink.prototype.getPostElement = function(){
return $('#post-id-' + this.getPostId());
};
DeletePostLink.prototype.isPostDeleted = function(){
return this._post_deleted;
};
DeletePostLink.prototype.setPostDeleted = function(is_deleted){
var post = this.getPostElement();
if (is_deleted === true){
post.addClass('deleted');
this._post_deleted = true;
this.getElement().html(gettext('undelete'));
} else if (is_deleted === false){
post.removeClass('deleted');
this._post_deleted = false;
this.getElement().html(gettext('delete'));
}
};
DeletePostLink.prototype.getDeleteHandler = function(){
var me = this;
var post_id = this.getPostId();
return function(){
var data = {
'post_id': me.getPostId(),
//todo rename cancel_vote -> undo
'cancel_vote': me.isPostDeleted() ? true: false
};
$.ajax({
type: 'POST',
data: data,
dataType: 'json',
url: askbot['urls']['delete_post'],
cache: false,
success: function(data){
if (data['success'] == true){
me.setPostDeleted(data['is_deleted']);
} else {
showMessage(me.getElement(), data['message']);
}
}
});
};
};
DeletePostLink.prototype.decorate = function(element){
this._element = element;
this._post_deleted = this.getPostElement().hasClass('deleted');
this.setHandler(this.getDeleteHandler());
}
/**
* Form for editing and posting new comment
* supports 3 editors: markdown, tinymce and plain textarea.
* There is only one instance of this form in use on the question page.
* It can be attached to any comment on the page, or to a new blank
* comment.
*/
var EditCommentForm = function(){
WrappedElement.call(this);
this._comment = null;
this._comment_widget = null;
this._element = null;
this._editorReady = false;
this._text = '';
};
inherits(EditCommentForm, WrappedElement);
EditCommentForm.prototype.setWaitingStatus = function(isWaiting) {
if (isWaiting === true) {
this._editor.getElement().hide();
this._submit_btn.hide();
this._cancel_btn.hide();
this._minorEditBox.hide();
this._element.hide();
} else {
this._element.show();
this._editor.getElement().show();
this._submit_btn.show();
this._cancel_btn.show();
this._minorEditBox.show();
}
};
EditCommentForm.prototype.getEditorType = function() {
if (askbot['settings']['commentsEditorType'] === 'rich-text') {
return askbot['settings']['editorType'];
} else {
return 'plain-text';
}
};
EditCommentForm.prototype.startTinyMCEEditor = function() {
var editorId = this.makeId('comment-editor');
var opts = {
mode: 'exact',
content_css: mediaUrl('media/style/tinymce/comments-content.css'),
elements: editorId,
plugins: 'autoresize',
theme: 'advanced',
theme_advanced_toolbar_location: 'top',
theme_advanced_toolbar_align: 'left',
theme_advanced_buttons1: 'bold, italic, |, link, |, numlist, bullist',
theme_advanced_buttons2: '',
theme_advanced_path: false,
plugins: '',
width: '100%',
height: '70'
};
var editor = new TinyMCE(opts);
editor.setId(editorId);
editor.setText(this._text);
this._editorBox.prepend(editor.getElement());
editor.start();
this._editor = editor;
};
EditCommentForm.prototype.startWMDEditor = function() {
var editor = new WMD();
editor.setEnabledButtons('bold italic link code ol ul');
editor.setPreviewerEnabled(false);
editor.setText(this._text);
this._editorBox.prepend(editor.getElement());//attach DOM before start
editor.start();//have to start after attaching DOM
this._editor = editor;
};
EditCommentForm.prototype.startSimpleEditor = function() {
this._editor = new SimpleEditor();
this._editorBox.prepend(this._editor.getElement());
};
EditCommentForm.prototype.startEditor = function() {
var editorType = this.getEditorType();
if (editorType === 'tinymce') {
this.startTinyMCEEditor();
//@todo: implement save on enter and character counter in tinyMCE
return;
} else if (editorType === 'markdown') {
this.startWMDEditor();
} else {
this.startSimpleEditor();
}
//code below is common to SimpleEditor and WMD
var editorElement = this._editor.getElement();
var updateCounter = this.getCounterUpdater();
var escapeHandler = makeKeyHandler(27, this.getCancelHandler());
//todo: try this on the div
var editor = this._editor;
//this should be set on the textarea!
editorElement.blur(updateCounter);
editorElement.focus(updateCounter);
editorElement.keyup(updateCounter)
editorElement.keyup(escapeHandler);
if (askbot['settings']['saveCommentOnEnter']){
var save_handler = makeKeyHandler(13, this.getSaveHandler());
editor.getElement().keydown(save_handler);
}
};
/**
* attaches comment editor to a particular comment
*/
EditCommentForm.prototype.attachTo = function(comment, mode){
this._comment = comment;
this._type = mode;//action: 'add' or 'edit'
this._comment_widget = comment.getContainerWidget();
this._text = comment.getText();
comment.getElement().after(this.getElement());
comment.getElement().hide();
this._comment_widget.hideButton();//hide add comment button
//fix up the comment submit button, depending on the mode
if (this._type == 'add'){
this._submit_btn.html(gettext('add comment'));
if (this._minorEditBox) {
this._minorEditBox.hide();
}
}
else {
this._submit_btn.html(gettext('save comment'));
if (this._minorEditBox) {
this._minorEditBox.show();
}
}
//enable the editor
this.getElement().show();
this.enableForm();
this.startEditor();
this._editor.setText(this._text);
var ed = this._editor
var onFocus = function() {
ed.putCursorAtEnd();
};
this._editor.focus(onFocus);
setupButtonEventHandlers(this._submit_btn, this.getSaveHandler());
setupButtonEventHandlers(this._cancel_btn, this.getCancelHandler());
};
EditCommentForm.prototype.getCounterUpdater = function(){
//returns event handler
var counter = this._text_counter;
var editor = this._editor;
var handler = function(){
var length = editor.getText().length;
var length1 = maxCommentLength - 100;
if (length1 < 0){
length1 = Math.round(0.7*maxCommentLength);
}
var length2 = maxCommentLength - 30;
if (length2 < 0){
length2 = Math.round(0.9*maxCommentLength);
}
/* todo make smooth color transition, from gray to red
* or rather - from start color to end color */
var color = 'maroon';
var chars = 10;
if (length === 0){
var feedback = interpolate(gettext('enter at least %s characters'), [chars]);
} else if (length < 10){
var feedback = interpolate(gettext('enter at least %s more characters'), [chars - length]);
} else {
if (length > length2) {
color = '#f00';
} else if (length > length1) {
color = '#f60';
} else {
color = '#999';
}
chars = maxCommentLength - length;
var feedback = interpolate(gettext('%s characters left'), [chars]);
}
counter.html(feedback);
counter.css('color', color);
return true;
};
return handler;
};
/**
* @todo: clean up this method so it does just one thing
*/
EditCommentForm.prototype.canCancel = function(){
if (this._element === null){
return true;
}
if (this._editor === undefined) {
return true;
};
var ctext = this._editor.getText();
if ($.trim(ctext) == $.trim(this._text)){
return true;
} else if (this.confirmAbandon()){
return true;
}
this._editor.focus();
return false;
};
EditCommentForm.prototype.getCancelHandler = function(){
var form = this;
return function(evt){
if (form.canCancel()){
form.detach();
evt.preventDefault();
}
return false;
};
};
EditCommentForm.prototype.detach = function(){
if (this._comment === null){
return;
}
this._comment.getContainerWidget().showButton();
if (this._comment.isBlank()){
this._comment.dispose();
} else {
this._comment.getElement().show();
}
this.reset();
this._element = this._element.detach();
this._editor.dispose();
this._editor = undefined;
removeButtonEventHandlers(this._submit_btn);
removeButtonEventHandlers(this._cancel_btn);
};
EditCommentForm.prototype.createDom = function(){
this._element = $('<form></form>');
this._element.attr('class', 'post-comments');
var div = $('<div></div>');
this._element.append(div);
/** a stub container for the editor */
this._editorBox = div;
/**
* editor itself will live at this._editor
* and will be initialized by the attachTo()
*/
this._controlsBox = this.makeElement('div');
this._controlsBox.addClass('edit-comment-buttons');
div.append(this._controlsBox);
this._text_counter = $('<span></span>').attr('class', 'counter');
this._controlsBox.append(this._text_counter);
this._submit_btn = $('<button class="submit"></button>');
this._controlsBox.append(this._submit_btn);
this._cancel_btn = $('<button class="submit"></button>');
this._cancel_btn.html(gettext('cancel'));
this._controlsBox.append(this._cancel_btn);
//if email alerts are enabled, add a checkbox "suppress_email"
if (askbot['settings']['enableEmailAlerts'] === true) {
this._minorEditBox = this.makeElement('div');
this._minorEditBox.addClass('checkbox');
this._controlsBox.append(this._minorEditBox);
var checkBox = this.makeElement('input');
checkBox.attr('type', 'checkbox');
checkBox.attr('name', 'suppress_email');
this._minorEditBox.append(checkBox);
var label = this.makeElement('label');
label.attr('for', 'suppress_email');
label.html(gettext("minor edit (don't send alerts)"));
this._minorEditBox.append(label);
}
};
EditCommentForm.prototype.isEnabled = function() {
return (this._submit_btn.attr('disabled') !== 'disabled');//confusing! setters use boolean
};
EditCommentForm.prototype.enableForm = function() {
this._submit_btn.attr('disabled', false);
this._cancel_btn.attr('disabled', false);
};
EditCommentForm.prototype.disableForm = function() {
this._submit_btn.attr('disabled', true);
this._cancel_btn.attr('disabled', true);
};
EditCommentForm.prototype.reset = function(){
this._comment = null;
this._text = '';
this._editor.setText('');
this.enableForm();
};
EditCommentForm.prototype.confirmAbandon = function(){
this._editor.focus();
this._editor.getElement().scrollTop();
this._editor.setHighlight(true);
var answer = confirm(
gettext("Are you sure you don't want to post this comment?")
);
this._editor.setHighlight(false);
return answer;
};
EditCommentForm.prototype.getSuppressEmail = function() {
return this._element.find('input[name="suppress_email"]').is(':checked');
};
EditCommentForm.prototype.setSuppressEmail = function(bool) {
this._element.find('input[name="suppress_email"]').prop('checked', bool);
};
EditCommentForm.prototype.getSaveHandler = function(){
var me = this;
var editor = this._editor;
return function(){
if (me.isEnabled() === false) {//prevent double submits
return false;
}
me.disableForm();
var text = editor.getText();
if (text.length < askbot['settings']['minCommentBodyLength']){
editor.focus();
me.enableForm();
return false;
}
//display the comment and show that it is not yet saved
me.setWaitingStatus(true);
me._comment.getElement().show();
var commentData = me._comment.getData();
var timestamp = commentData['comment_added_at'] || gettext('just now');
var userName = commentData['user_display_name'] || askbot['data']['userName'];
me._comment.setContent({
'html': editor.getHtml(),
'text': text,
'user_display_name': userName,
'comment_added_at': timestamp
});
me._comment.setDraftStatus(true);
me._comment.getContainerWidget().showButton();
var post_data = {
comment: text
};
if (me._type == 'edit'){
post_data['comment_id'] = me._comment.getId();
post_url = askbot['urls']['editComment'];
post_data['suppress_email'] = me.getSuppressEmail();
me.setSuppressEmail(false);
}
else {
post_data['post_type'] = me._comment.getParentType();
post_data['post_id'] = me._comment.getParentId();
post_url = askbot['urls']['postComments'];
}
$.ajax({
type: "POST",
url: post_url,
dataType: "json",
data: post_data,
success: function(json) {
//type is 'edit' or 'add'
me._comment.setDraftStatus(false);
if (me._type == 'add'){
me._comment.dispose();
me._comment.getContainerWidget().reRenderComments(json);
} else {
me._comment.setContent(json);
}
me.setWaitingStatus(false);
me.detach();
},
error: function(xhr, textStatus, errorThrown) {
me._comment.getElement().show();
showMessage(me._comment.getElement(), xhr.responseText, 'after');
me._comment.setDraftStatus(false);
me.setWaitingStatus(false);
me.detach();
me.enableForm();
}
});
return false;
};
};
var Comment = function(widget, data){
WrappedElement.call(this);
this._container_widget = widget;
this._data = data || {};
this._blank = true;//set to false by setContent
this._element = null;
this._is_convertible = askbot['data']['userIsAdminOrMod'];
this.convert_link = null;
this._delete_prompt = gettext('delete this comment');
this._editorForm = undefined;
if (data && data['is_deletable']){
this._deletable = data['is_deletable'];
}
else {
this._deletable = false;
}
if (data && data['is_editable']){
this._editable = data['is_deletable'];
}
else {
this._editable = false;
}
};
inherits(Comment, WrappedElement);
Comment.prototype.getData = function() {
return this._data;
};
Comment.prototype.startEditing = function() {
var form = this._editorForm || new EditCommentForm();
this._editorForm = form;
// if new comment:
if (this.isBlank()) {
form.attachTo(this, 'add');
} else {
form.attachTo(this, 'edit');
}
};
Comment.prototype.decorate = function(element){
this._element = $(element);
var parent_type = this._element.parent().parent().attr('id').split('-')[2];
var comment_id = this._element.attr('id').replace('comment-','');
this._data = {id: comment_id};
this._contentBox = this._element.find('.comment-content');
var timestamp = this._element.find('abbr.timeago');
this._data['comment_added_at'] = timestamp.attr('title');
var userLink = this._element.find('a.author');
this._data['user_display_name'] = userLink.html();
// @todo: read other data
var commentBody = this._element.find('.comment-body');
if (commentBody.length > 0) {
this._comment_body = commentBody;
}
var delete_img = this._element.find('span.delete-icon');
if (delete_img.length > 0){
this._deletable = true;
this._delete_icon = new DeleteIcon(this.deletePrompt);
this._delete_icon.setHandler(this.getDeleteHandler());
this._delete_icon.decorate(delete_img);
}
var edit_link = this._element.find('a.edit');
if (edit_link.length > 0){
this._editable = true;
this._edit_link = new EditLink();
this._edit_link.setHandler(this.getEditHandler());
this._edit_link.decorate(edit_link);
}
var convert_link = this._element.find('form.convert-comment');
if (this._is_convertible){
this._convert_link = new CommentConvertLink(comment_id);
this._convert_link.decorate(convert_link);
}
var deleter = this._element.find('.comment-delete');
if (deleter.length > 0) {
this._comment_delete = deleter;
};
var vote = new CommentVoteButton(this);
vote.decorate(this._element.find('.comment-votes .upvote'));
this._blank = false;
};
Comment.prototype.setDraftStatus = function(isDraft) {
return;
//@todo: implement nice feedback about posting in progress
//maybe it should be an element that lasts at least a second
//to avoid the possible brief flash
if (isDraft === true) {
this._normalBackground = this._element.css('background');
this._element.css('background', 'rgb(255, 243, 195)');
} else {
this._element.css('background', this._normalBackground);
}
};
Comment.prototype.isBlank = function(){
return this._blank;
};
Comment.prototype.getId = function(){
return this._data['id'];
};
Comment.prototype.hasContent = function(){
return ('id' in this._data);
//shortcut for 'user_url' 'html' 'user_display_name' 'comment_age'
};
Comment.prototype.hasText = function(){
return ('text' in this._data);
}
Comment.prototype.getContainerWidget = function(){
return this._container_widget;
};
Comment.prototype.getParentType = function(){
return this._container_widget.getPostType();
};
Comment.prototype.getParentId = function(){
return this._container_widget.getPostId();
};
/**
* this function is basically an "updateDom"
* for which we don't have the convention
*/
Comment.prototype.setContent = function(data){
this._data = $.extend(this._data, data);
this._element.addClass('comment');
this._element.css('display', 'table');//@warning: hardcoded
//display is set to "block" if .show() is called, but we need table.
this._element.attr('id', 'comment-' + this._data['id']);
// 1) create the votes element if it is not there
var votesBox = this._element.find('.comment-votes');
if (votesBox.length === 0) {
votesBox = this.makeElement('div');
votesBox.addClass('comment-votes');
this._element.append(votesBox);
var vote = new CommentVoteButton(this);
if (this._data['upvoted_by_user']){
vote.setVoted(true);
}
vote.setScore(this._data['score']);
var voteElement = vote.getElement();
votesBox.append(vote.getElement());
}
// 2) create the comment content container
if (this._contentBox === undefined) {
var contentBox = this.makeElement('div');
contentBox.addClass('comment-content');
this._contentBox = contentBox;
this._element.append(contentBox);
}
// 2) create the comment deleter if it is not there
if (this._comment_delete === undefined) {
this._comment_delete = $('<div class="comment-delete"></div>');
if (this._deletable){
this._delete_icon = new DeleteIcon(this._delete_prompt);
this._delete_icon.setHandler(this.getDeleteHandler());
this._comment_delete.append(this._delete_icon.getElement());
}
this._contentBox.append(this._comment_delete);
}
// 3) create or replace the comment body
if (this._comment_body === undefined) {
this._comment_body = $('<div class="comment-body"></div>');
this._contentBox.append(this._comment_body);
}
if (EditCommentForm.prototype.getEditorType() === 'tinymce') {
var theComment = $('<div/>');
theComment.html(this._data['html']);
//sanitize, just in case
this._comment_body.empty();
this._comment_body.append(theComment);
this._data['text'] = this._data['html'];
} else {
this._comment_body.empty();
this._comment_body.html(this._data['html']);
}
//this._comment_body.append(' – ');
// 4) create user link if absent
if (this._user_link !== undefined) {
this._user_link.detach();
this._user_link = undefined;
}
this._user_link = $('<a></a>').attr('class', 'author');
this._user_link.attr('href', this._data['user_url']);
this._user_link.html(this._data['user_display_name']);
this._comment_body.append(' ');
this._comment_body.append(this._user_link);
// 5) create or update the timestamp
if (this._comment_added_at !== undefined) {
this._comment_added_at.detach();
this._comment_added_at = undefined;
}
this._comment_body.append(' (');
this._comment_added_at = $('<abbr class="timeago"></abbr>');
this._comment_added_at.html(this._data['comment_added_at']);
this._comment_added_at.attr('title', this._data['comment_added_at']);
this._comment_added_at.timeago();
this._comment_body.append(this._comment_added_at);
this._comment_body.append(')');
if (this._editable) {
if (this._edit_link !== undefined) {
this._edit_link.dispose();
}
this._edit_link = new EditLink();
this._edit_link.setHandler(this.getEditHandler())
this._comment_body.append(this._edit_link.getElement());
}
if (this._is_convertible) {
if (this._convert_link !== undefined) {
this._convert_link.dispose();
}
this._convert_link = new CommentConvertLink(this._data['id']);
this._comment_body.append(this._convert_link.getElement());
}
this._blank = false;
};
Comment.prototype.dispose = function(){
if (this._comment_body){
this._comment_body.remove();
}
if (this._comment_delete){
this._comment_delete.remove();
}
if (this._user_link){
this._user_link.remove();
}
if (this._comment_added_at){
this._comment_added_at.remove();
}
if (this._delete_icon){
this._delete_icon.dispose();
}
if (this._edit_link){
this._edit_link.dispose();
}
if (this._convert_link){
this._convert_link.dispose();
}
this._data = null;
Comment.superClass_.dispose.call(this);
};
Comment.prototype.getElement = function(){
Comment.superClass_.getElement.call(this);
if (this.isBlank() && this.hasContent()){
this.setContent();
if (askbot['settings']['mathjaxEnabled'] === true){
MathJax.Hub.Queue(['Typeset', MathJax.Hub]);
}
}
return this._element;
};
Comment.prototype.loadText = function(on_load_handler){
var me = this;
$.ajax({
type: "GET",
url: askbot['urls']['getComment'],
data: {id: this._data['id']},
success: function(json){
if (json['success']) {
me._data['text'] = json['text'];
on_load_handler()
} else {
showMessage(me.getElement(), json['message'], 'after');
}
},
error: function(xhr, textStatus, exception) {
showMessage(me.getElement(), xhr.responseText, 'after');
}
});
};
Comment.prototype.getText = function(){
if (!this.isBlank()){
if ('text' in this._data){
return this._data['text'];
}
}
return '';
}
Comment.prototype.getEditHandler = function(){
var me = this;
return function(){
if (me.hasText()){
me.startEditing();
} else {
me.loadText(function(){ me.startEditing() });
}
};
};
Comment.prototype.getDeleteHandler = function(){
var comment = this;
var del_icon = this._delete_icon;
return function(){
if (confirm(gettext('confirm delete comment'))){
comment.getElement().hide();
$.ajax({
type: 'POST',
url: askbot['urls']['deleteComment'],
data: { comment_id: comment.getId() },
success: function(json, textStatus, xhr) {
comment.dispose();
},
error: function(xhr, textStatus, exception) {
comment.getElement().show()
showMessage(del_icon.getElement(), xhr.responseText);
},
dataType: "json"
});
}
};
};
var PostCommentsWidget = function(){
WrappedElement.call(this);
this._denied = false;
};
inherits(PostCommentsWidget, WrappedElement);
PostCommentsWidget.prototype.decorate = function(element){
var element = $(element);
this._element = element;
var widget_id = element.attr('id');
var id_bits = widget_id.split('-');
this._post_id = id_bits[3];
this._post_type = id_bits[2];
this._is_truncated = askbot['data'][widget_id]['truncated'];
this._user_can_post = askbot['data'][widget_id]['can_post'];
//see if user can comment here
var controls = element.find('.controls');
this._activate_button = controls.find('.button');
if (this._user_can_post == false){
setupButtonEventHandlers(
this._activate_button,
this.getReadOnlyLoadHandler()
);
}
else {
setupButtonEventHandlers(
this._activate_button,
this.getActivateHandler()
);
}
this._cbox = element.find('.content');
var comments = new Array();
var me = this;
this._cbox.children('.comment').each(function(index, element){
var comment = new Comment(me);
comments.push(comment)
comment.decorate(element);
});
this._comments = comments;
};
PostCommentsWidget.prototype.getPostType = function(){
return this._post_type;
};
PostCommentsWidget.prototype.getPostId = function(){
return this._post_id;
};
PostCommentsWidget.prototype.hideButton = function(){
this._activate_button.hide();
};
PostCommentsWidget.prototype.showButton = function(){
if (this._is_truncated === false){
this._activate_button.html(askbot['messages']['addComment']);
}
this._activate_button.show();
}
PostCommentsWidget.prototype.startNewComment = function(){
var opts = {
'is_deletable': true,
'is_editable': true
};
var comment = new Comment(this, opts);
this._cbox.append(comment.getElement());
comment.startEditing();
};
PostCommentsWidget.prototype.needToReload = function(){
return this._is_truncated;
};
PostCommentsWidget.prototype.userCanPost = function() {
var data = askbot['data'];
if (data['userIsAuthenticated']) {
//true if admin, post owner or high rep user
if (data['userIsAdminOrMod']) {
return true;
} else if (this.getPostId() in data['user_posts']) {
return true;
}
}
return false;
};
PostCommentsWidget.prototype.getActivateHandler = function(){
var me = this;
var button = this._activate_button;
return function() {
if (me.needToReload()){
me.reloadAllComments(function(json){
me.reRenderComments(json);
//2) change button text to "post a comment"
button.html(gettext('post a comment'));
});
}
else {
//if user can't post, we tell him something and refuse
if (askbot['data']['userIsAuthenticated']) {
me.startNewComment();
} else {
var message = gettext('please sign in or register to post comments');
showMessage(button, message, 'after');
}
}
};
};
PostCommentsWidget.prototype.getReadOnlyLoadHandler = function(){
var me = this;
return function(){
me.reloadAllComments(function(json){
me.reRenderComments(json);
me._activate_button.remove();
});
};
};
PostCommentsWidget.prototype.reloadAllComments = function(callback){
var post_data = {post_id: this._post_id, post_type: this._post_type};
var me = this;
$.ajax({
type: "GET",
url: askbot['urls']['postComments'],
data: post_data,
success: function(json){
callback(json);
me._is_truncated = false;
},
dataType: "json"
});
};
PostCommentsWidget.prototype.reRenderComments = function(json){
$.each(this._comments, function(i, item){
item.dispose();
});
this._comments = new Array();
var me = this;
$.each(json, function(i, item){
var comment = new Comment(me, item);
me._cbox.append(comment.getElement());
me._comments.push(comment);
});
};
var socialSharing = function(){
var SERVICE_DATA = {
//url - template for the sharing service url, params are for the popup
identica: {
url: "http://identi.ca/notice/new?status_textarea={TEXT}%20{URL}",
params: "width=820, height=526,toolbar=1,status=1,resizable=1,scrollbars=1"
},
twitter: {
url: "http://twitter.com/share?url={URL}&ref=twitbtn&text={TEXT}",
params: "width=820,height=526,toolbar=1,status=1,resizable=1,scrollbars=1"
},
facebook: {
url: "http://www.facebook.com/sharer.php?u={URL}&ref=fbshare&t={TEXT}",
params: "width=630,height=436,toolbar=1,status=1,resizable=1,scrollbars=1"
},
linkedin: {
url: "http://www.linkedin.com/shareArticle?mini=true&url={URL}&title={TEXT}",
params: "width=630,height=436,toolbar=1,status=1,resizable=1,scrollbars=1"
}
};
var URL = "";
var TEXT = "";
var share_page = function(service_name){
if (SERVICE_DATA[service_name]){
var url = SERVICE_DATA[service_name]['url'];
url = url.replace('{TEXT}', TEXT);
url = url.replace('{URL}', URL);
var params = SERVICE_DATA[service_name]['params'];
if(!window.open(url, "sharing", params)){
window.location.href=url;
}
return false;
//@todo: change to some other url shortening service
$.ajax({
url: "http://json-tinyurl.appspot.com/?&callback=?",
dataType: "json",
data: {'url':URL},
success: function(data) {
url = url.replace('{URL}', data.tinyurl);
},
error: function(xhr, opts, error) {
url = url.replace('{URL}', URL);
},
complete: function(data) {
url = url.replace('{TEXT}', TEXT);
var params = SERVICE_DATA[service_name]['params'];
if(!window.open(url, "sharing", params)){
window.location.href=url;
}
}
});
}
}
return {
init: function(){
URL = window.location.href;
var urlBits = URL.split('/');
URL = urlBits.slice(0, -2).join('/') + '/';
TEXT = encodeURIComponent($('h1 > a').html());
var hashtag = encodeURIComponent(
askbot['settings']['sharingSuffixText']
);
TEXT = TEXT.substr(0, 134 - URL.length - hashtag.length);
TEXT = TEXT + '... ' + hashtag;
var fb = $('a.facebook-share')
var tw = $('a.twitter-share');
var ln = $('a.linkedin-share');
var ica = $('a.identica-share');
copyAltToTitle(fb);
copyAltToTitle(tw);
copyAltToTitle(ln);
copyAltToTitle(ica);
setupButtonEventHandlers(fb, function(){ share_page("facebook") });
setupButtonEventHandlers(tw, function(){ share_page("twitter") });
setupButtonEventHandlers(ln, function(){ share_page("linkedin") });
setupButtonEventHandlers(ica, function(){ share_page("identica") });
}
}
}();
/**
* @constructor
* @extends {SimpleControl}
*/
var QASwapper = function(){
SimpleControl.call(this);
this._ans_id = null;
};
inherits(QASwapper, SimpleControl);
QASwapper.prototype.decorate = function(element){
this._element = element;
this._ans_id = parseInt(element.attr('id').split('-').pop());
var me = this;
this.setHandler(function(){
me.startSwapping();
});
};
QASwapper.prototype.startSwapping = function(){
while (true){
var title = prompt(gettext('Please enter question title (>10 characters)'));
if (title.length >= 10){
var data = {new_title: title, answer_id: this._ans_id};
$.ajax({
type: "POST",
cache: false,
dataType: "json",
url: askbot['urls']['swap_question_with_answer'],
data: data,
success: function(data){
window.location.href = data['question_url'];
}
});
break;
}
}
};
/**
* @constructor
* An element that encloses an editor and everything inside it.
* By default editor is hidden and user sees a box with a prompt
* suggesting to make a post.
* When user clicks, editor becomes accessible.
*/
var FoldedEditor = function() {
WrappedElement.call(this);
};
inherits(FoldedEditor, WrappedElement);
FoldedEditor.prototype.getEditor = function() {
return this._editor;
};
FoldedEditor.prototype.getEditorInputId = function() {
return this._element.find('textarea').attr('id');
};
FoldedEditor.prototype.onAfterOpenHandler = function() {
var editor = this.getEditor();
if (editor) {
setTimeout(function() {editor.focus()}, 500);
}
};
FoldedEditor.prototype.getOpenHandler = function() {
var editorBox = this._editorBox;
var promptBox = this._prompt;
var externalTrigger = this._externalTrigger;
var me = this;
return function() {
promptBox.hide();
editorBox.show();
var element = me.getElement();
element.addClass('unfolded');
/* make the editor one shot - once it unfolds it's
* not accepting any events
*/
element.unbind('click');
element.unbind('focus');
/* this function will open the editor
* and focus cursor on the editor
*/
me.onAfterOpenHandler();
/* external trigger is a clickable target
* placed outside of the this._element
* that will cause the editor to unfold
*/
if (externalTrigger) {
var label = me.makeElement('label');
label.html(externalTrigger.html());
//set what the label is for
label.attr('for', me.getEditorInputId());
externalTrigger.replaceWith(label);
}
};
};
FoldedEditor.prototype.setExternalTrigger = function(element) {
this._externalTrigger = element;
};
FoldedEditor.prototype.decorate = function(element) {
this._element = element;
this._prompt = element.find('.prompt');
this._editorBox = element.find('.editor-proper');
var editorType = askbot['settings']['editorType'];
if (editorType === 'tinymce') {
var editor = new TinyMCE();
editor.decorate(element.find('textarea'));
this._editor = editor;
} else if (editorType === 'markdown') {
var editor = new WMD();
editor.decorate(element);
this._editor = editor;
}
var openHandler = this.getOpenHandler();
element.click(openHandler);
element.focus(openHandler);
if (this._externalTrigger) {
this._externalTrigger.click(openHandler);
}
};
/**
* @constructor
* a simple textarea-based editor
*/
var SimpleEditor = function(attrs) {
WrappedElement.call(this);
attrs = attrs || {};
this._rows = attrs['rows'] || 10;
this._cols = attrs['cols'] || 60;
this._maxlength = attrs['maxlength'] || 1000;
};
inherits(SimpleEditor, WrappedElement);
SimpleEditor.prototype.focus = function(onFocus) {
this._textarea.focus();
if (onFocus) {
onFocus();
}
};
SimpleEditor.prototype.putCursorAtEnd = function() {
putCursorAtEnd(this._textarea);
};
/**
* a noop function
*/
SimpleEditor.prototype.start = function() {};
SimpleEditor.prototype.setHighlight = function(isHighlighted) {
if (isHighlighted === true) {
this._textarea.addClass('highlight');
} else {
this._textarea.removeClass('highlight');
}
};
SimpleEditor.prototype.getText = function() {
return $.trim(this._textarea.val());
};
SimpleEditor.prototype.getHtml = function() {
return '<div class="transient-comment">' + this.getText() + '</div>';
};
SimpleEditor.prototype.setText = function(text) {
this._text = text;
if (this._textarea) {
this._textarea.val(text);
};
};
/**
* a textarea inside a div,
* the reason for this is that we subclass this
* in WMD, and that one requires a more complex structure
*/
SimpleEditor.prototype.createDom = function() {
this._element = this.makeElement('div');
this._element.addClass('wmd-container');
var textarea = this.makeElement('textarea');
this._element.append(textarea);
this._textarea = textarea;
if (this._text) {
textarea.val(this._text);
};
textarea.attr({
'cols': this._cols,
'rows': this._rows,
'maxlength': this._maxlength
});
}
/**
* @constructor
* a wrapper for the WMD editor
*/
var WMD = function(){
SimpleEditor.call(this);
this._text = undefined;
this._enabled_buttons = 'bold italic link blockquote code ' +
'image attachment ol ul heading hr';
this._is_previewer_enabled = true;
};
inherits(WMD, SimpleEditor);
//@todo: implement getHtml method that runs text through showdown renderer
WMD.prototype.setEnabledButtons = function(buttons){
this._enabled_buttons = buttons;
};
WMD.prototype.setPreviewerEnabled = function(state){
this._is_previewer_enabled = state;
if (this._previewer){
this._previewer.hide();
}
};
WMD.prototype.createDom = function(){
this._element = this.makeElement('div');
var clearfix = this.makeElement('div').addClass('clearfix');
this._element.append(clearfix);
var wmd_container = this.makeElement('div');
wmd_container.addClass('wmd-container');
this._element.append(wmd_container);
var wmd_buttons = this.makeElement('div')
.attr('id', this.makeId('wmd-button-bar'))
.addClass('wmd-panel');
wmd_container.append(wmd_buttons);
var editor = this.makeElement('textarea')
.attr('id', this.makeId('editor'));
wmd_container.append(editor);
this._textarea = editor;
if (this._text){
editor.val(this._text);
}
var previewer = this.makeElement('div')
.attr('id', this.makeId('previewer'))
.addClass('wmd-preview');
wmd_container.append(previewer);
this._previewer = previewer;
if (this._is_previewer_enabled === false) {
previewer.hide();
}
};
WMD.prototype.decorate = function(element) {
this._element = element;
this._textarea = element.find('textarea');
this._previewer = element.find('.wmd-preview');
};
WMD.prototype.start = function(){
Attacklab.Util.startEditor(true, this._enabled_buttons, this.getIdSeed());
};
/**
* @constructor
*/
var TinyMCE = function(config) {
WrappedElement.call(this);
this._config = config || {};
this._id = 'editor';//desired id of the textarea
};
inherits(TinyMCE, WrappedElement);
/*
* not passed onto prototoype on purpose!!!
*/
TinyMCE.onInitHook = function() {
//set initial content
var ed = tinyMCE.activeEditor;
ed.setContent(askbot['data']['editorContent'] || '');
//if we have spellchecker - enable it by default
if (inArray('spellchecker', askbot['settings']['tinyMCEPlugins'])) {
setTimeout(function() {
ed.controlManager.setActive('spellchecker', true);
tinyMCE.execCommand('mceSpellCheck', true);
}, 1);
}
};
/* 3 dummy functions to match WMD api */
TinyMCE.prototype.setEnabledButtons = function() {};
TinyMCE.prototype.start = function() {
//copy the options, because we need to modify them
var opts = $.extend({}, this._config);
var me = this;
var extraOpts = {
'mode': 'exact',
'elements': this._id,
};
opts = $.extend(opts, extraOpts);
tinyMCE.init(opts);
$('.mceStatusbar').remove();
};
TinyMCE.prototype.setPreviewerEnabled = function() {};
TinyMCE.prototype.setHighlight = function() {};
TinyMCE.prototype.putCursorAtEnd = function() {
var ed = tinyMCE.activeEditor;
//add an empty span with a unique id
var endId = tinymce.DOM.uniqueId();
ed.dom.add(ed.getBody(), 'span', {'id': endId}, '');
//select that span
var newNode = ed.dom.select('span#' + endId);
ed.selection.select(newNode[0]);
};
TinyMCE.prototype.focus = function(onFocus) {
var editorId = this._id;
var winH = $(window).height();
var winY = $(window).scrollTop();
var edY = this._element.offset().top;
var edH = this._element.height();
//@todo: the fallacy of this method is timeout - should instead use queue
//because at the time of calling focus() the editor may not be initialized yet
setTimeout(
function() {
tinyMCE.execCommand('mceFocus', false, editorId);
//@todo: make this general to all editors
//if editor bottom is below viewport
var isBelow = ((edY + edH) > (winY + winH));
var isAbove = (edY < winY);
if (isBelow || isAbove) {
//then center on screen
$(window).scrollTop(edY - edH/2 - winY/2);
}
if (onFocus) {
onFocus();
}
},
100
);
};
TinyMCE.prototype.setId = function(id) {
this._id = id;
};
TinyMCE.prototype.setText = function(text) {
this._text = text;
if (this.isLoaded()) {
tinymce.get(this._id).setContent(text);
}
};
TinyMCE.prototype.getText = function() {
return tinyMCE.activeEditor.getContent();
};
TinyMCE.prototype.getHtml = TinyMCE.prototype.getText;
TinyMCE.prototype.isLoaded = function() {
return (tinymce.get(this._id) !== undefined);
};
TinyMCE.prototype.createDom = function() {
var editorBox = this.makeElement('div');
editorBox.addClass('wmd-container');
this._element = editorBox;
var textarea = this.makeElement('textarea');
textarea.attr('id', this._id);
textarea.addClass('editor');
this._element.append(textarea);
};
TinyMCE.prototype.decorate = function(element) {
this._element = element;
this._id = element.attr('id');
};
/**
* @constructor
* @todo: change this to generic object description editor
*/
var TagWikiEditor = function(){
WrappedElement.call(this);
this._state = 'display';//'edit' or 'display'
this._content_backup = '';
this._is_editor_loaded = false;
this._enabled_editor_buttons = null;
this._is_previewer_enabled = false;
};
inherits(TagWikiEditor, WrappedElement);
TagWikiEditor.prototype.backupContent = function(){
this._content_backup = this._content_box.contents();
};
TagWikiEditor.prototype.setEnabledEditorButtons = function(buttons){
this._enabled_editor_buttons = buttons;
};
TagWikiEditor.prototype.setPreviewerEnabled = function(state){
this._is_previewer_enabled = state;
if (this.isEditorLoaded()){
this._editor.setPreviewerEnabled(this._is_previewer_enabled);
}
};
TagWikiEditor.prototype.setContent = function(content){
this._content_box.empty();
this._content_box.append(content);
};
TagWikiEditor.prototype.setState = function(state){
if (state === 'edit'){
this._state = state;
this._edit_btn.hide();
this._cancel_btn.show();
this._save_btn.show();
this._cancel_sep.show();
} else if (state === 'display'){
this._state = state;
this._edit_btn.show();
this._cancel_btn.hide();
this._cancel_sep.hide();
this._save_btn.hide();
}
};
TagWikiEditor.prototype.restoreContent = function(){
var content_box = this._content_box;
content_box.empty();
$.each(this._content_backup, function(idx, element){
content_box.append(element);
});
};
TagWikiEditor.prototype.getTagId = function(){
return this._tag_id;
};
TagWikiEditor.prototype.isEditorLoaded = function(){
return this._is_editor_loaded;
};
TagWikiEditor.prototype.setEditorLoaded = function(){
return this._is_editor_loaded = true;
};
/**
* loads initial data for the editor input and activates
* the editor
*/
TagWikiEditor.prototype.startActivatingEditor = function(){
var editor = this._editor;
var me = this;
var data = {
object_id: me.getTagId(),
model_name: 'Group'
};
$.ajax({
type: 'GET',
url: askbot['urls']['load_object_description'],
data: data,
cache: false,
success: function(data){
me.backupContent();
editor.setText(data);
me.setContent(editor.getElement());
me.setState('edit');
if (me.isEditorLoaded() === false){
editor.start();
me.setEditorLoaded();
}
}
});
};
TagWikiEditor.prototype.saveData = function(){
var me = this;
var text = this._editor.getText();
var data = {
object_id: me.getTagId(),
model_name: 'Group',//todo: fixme
text: text
};
$.ajax({
type: 'POST',
dataType: 'json',
url: askbot['urls']['save_object_description'],
data: data,
cache: false,
success: function(data){
if (data['success']){
me.setState('display');
me.setContent(data['html']);
} else {
showMessage(me.getElement(), data['message']);
}
}
});
};
TagWikiEditor.prototype.cancelEdit = function(){
this.restoreContent();
this.setState('display');
};
TagWikiEditor.prototype.decorate = function(element){
//expect <div id='group-wiki-{{id}}'><div class="content"/><a class="edit"/></div>
this._element = element;
var edit_btn = element.find('.edit-description');
this._edit_btn = edit_btn;
//adding two buttons...
var save_btn = this.makeElement('a');
save_btn.html(gettext('save'));
edit_btn.after(save_btn);
save_btn.hide();
this._save_btn = save_btn;
var cancel_btn = this.makeElement('a');
cancel_btn.html(gettext('cancel'));
save_btn.after(cancel_btn);
cancel_btn.hide();
this._cancel_btn = cancel_btn;
this._cancel_sep = $('<span> | </span>');
cancel_btn.before(this._cancel_sep);
this._cancel_sep.hide();
this._content_box = element.find('.content');
this._tag_id = element.attr('id').split('-').pop();
var me = this;
if (askbot['settings']['editorType'] === 'markdown') {
var editor = new WMD();
} else {
var editor = new TinyMCE({//override defaults
theme_advanced_buttons1: 'bold, italic, |, link, |, numlist, bullist',
theme_advanced_buttons2: '',
theme_advanced_path: false,
plugins: ''
});
}
if (this._enabled_editor_buttons){
editor.setEnabledButtons(this._enabled_editor_buttons);
}
editor.setPreviewerEnabled(this._is_previewer_enabled);
this._editor = editor;
setupButtonEventHandlers(edit_btn, function(){ me.startActivatingEditor() });
setupButtonEventHandlers(cancel_btn, function(){me.cancelEdit()});
setupButtonEventHandlers(save_btn, function(){me.saveData()});
};
var ImageChanger = function(){
WrappedElement.call(this);
this._image_element = undefined;
this._delete_button = undefined;
this._save_url = undefined;
this._delete_url = undefined;
this._messages = undefined;
};
inherits(ImageChanger, WrappedElement);
ImageChanger.prototype.setImageElement = function(image_element){
this._image_element = image_element;
};
ImageChanger.prototype.setMessages = function(messages){
this._messages = messages;
};
ImageChanger.prototype.setDeleteButton = function(delete_button){
this._delete_button = delete_button;
};
ImageChanger.prototype.setSaveUrl = function(url){
this._save_url = url;
};
ImageChanger.prototype.setDeleteUrl = function(url){
this._delete_url = url;
};
ImageChanger.prototype.setAjaxData = function(data){
this._ajax_data = data;
};
ImageChanger.prototype.showImage = function(image_url){
this._image_element.attr('src', image_url);
this._image_element.show();
};
ImageChanger.prototype.deleteImage = function(){
this._image_element.attr('src', '');
this._image_element.css('display', 'none');
var me = this;
var delete_url = this._delete_url;
var data = this._ajax_data;
$.ajax({
type: 'POST',
dataType: 'json',
url: delete_url,
data: data,
cache: false,
success: function(data){
if (data['success'] === true){
showMessage(me.getElement(), data['message'], 'after');
}
}
});
};
ImageChanger.prototype.saveImageUrl = function(image_url){
var me = this;
var data = this._ajax_data;
data['image_url'] = image_url;
var save_url = this._save_url;
$.ajax({
type: 'POST',
dataType: 'json',
url: save_url,
data: data,
cache: false,
success: function(data){
if (!data['success']){
showMessage(me.getElement(), data['message'], 'after');
}
}
});
};
ImageChanger.prototype.startDialog = function(){
//reusing the wmd's file uploader
var me = this;
var change_image_text = this._messages['change_image'];
var change_image_button = this._element;
Attacklab.Util.prompt(
"<h3>" + gettext('Enter the logo url or upload an image') + '</h3>',
'http://',
function(image_url){
if (image_url){
me.saveImageUrl(image_url);
me.showImage(image_url);
change_image_button.html(change_image_text);
me.showDeleteButton();
}
},
'image'
);
};
ImageChanger.prototype.showDeleteButton = function(){
this._delete_button.show();
this._delete_button.prev().show();
};
ImageChanger.prototype.hideDeleteButton = function(){
this._delete_button.hide();
this._delete_button.prev().hide();
};
ImageChanger.prototype.startDeleting = function(){
if (confirm(gettext('Do you really want to remove the image?'))){
this.deleteImage();
this._element.html(this._messages['add_image']);
this.hideDeleteButton();
this._delete_button.hide();
var sep = this._delete_button.prev();
sep.hide();
};
};
/**
* decorates an element that will serve as the image changer button
*/
ImageChanger.prototype.decorate = function(element){
this._element = element;
var me = this;
setupButtonEventHandlers(
element,
function(){
me.startDialog();
}
);
setupButtonEventHandlers(
this._delete_button,
function(){
me.startDeleting();
}
)
};
var UserGroupProfileEditor = function(){
TagWikiEditor.call(this);
};
inherits(UserGroupProfileEditor, TagWikiEditor);
UserGroupProfileEditor.prototype.toggleEmailModeration = function(){
var btn = this._moderate_email_btn;
var group_id = this.getTagId();
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
data: {group_id: group_id},
url: askbot['urls']['toggle_group_email_moderation'],
success: function(data){
if (data['success']){
btn.html(data['new_button_text']);
} else {
showMessage(btn, data['message']);
}
}
});
};
UserGroupProfileEditor.prototype.decorate = function(element){
this.setEnabledEditorButtons('bold italic link ol ul');
this.setPreviewerEnabled(false);
UserGroupProfileEditor.superClass_.decorate.call(this, element);
var change_logo_btn = element.find('.change-logo');
this._change_logo_btn = change_logo_btn;
var moderate_email_toggle = new TwoStateToggle();
moderate_email_toggle.setPostData({
group_id: this.getTagId(),
property_name: 'moderate_email'
});
var moderate_email_btn = element.find('#moderate-email');
this._moderate_email_btn = moderate_email_btn;
moderate_email_toggle.decorate(moderate_email_btn);
var moderate_publishing_replies_toggle = new TwoStateToggle();
moderate_publishing_replies_toggle.setPostData({
group_id: this.getTagId(),
property_name: 'moderate_answers_to_enquirers'
});
var btn = element.find('#moderate-answers-to-enquirers');
moderate_publishing_replies_toggle.decorate(btn);
var vip_toggle = new TwoStateToggle();
vip_toggle.setPostData({
group_id: this.getTagId(),
property_name: 'is_vip'
});
var btn = element.find('#vip-toggle');
vip_toggle.decorate(btn);
var opennessSelector = new DropdownSelect();
var selectorElement = element.find('#group-openness-selector');
opennessSelector.setPostData({
group_id: this.getTagId(),
property_name: 'openness'
});
opennessSelector.decorate(selectorElement);
var email_editor = new TextPropertyEditor();
email_editor.decorate(element.find('#preapproved-emails'));
var domain_editor = new TextPropertyEditor();
domain_editor.decorate(element.find('#preapproved-email-domains'));
var logo_changer = new ImageChanger();
logo_changer.setImageElement(element.find('.group-logo'));
logo_changer.setAjaxData({
group_id: this.getTagId()
});
logo_changer.setSaveUrl(askbot['urls']['save_group_logo_url']);
logo_changer.setDeleteUrl(askbot['urls']['delete_group_logo_url']);
logo_changer.setMessages({
change_image: gettext('change logo'),
add_image: gettext('add logo')
});
var delete_logo_btn = element.find('.delete-logo');
logo_changer.setDeleteButton(delete_logo_btn);
logo_changer.decorate(change_logo_btn);
};
var GroupJoinButton = function(){
TwoStateToggle.call(this);
};
inherits(GroupJoinButton, TwoStateToggle);
GroupJoinButton.prototype.getPostData = function(){
return { group_id: this._group_id };
};
GroupJoinButton.prototype.getHandler = function(){
var me = this;
return function(){
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
data: me.getPostData(),
url: askbot['urls']['join_or_leave_group'],
success: function(data){
if (data['success']){
var level = data['membership_level'];
var new_state = 'off-state';
if (level == 'full' || level == 'pending') {
new_state = 'on-state';
}
me.setState(new_state);
} else {
showMessage(me.getElement(), data['message']);
}
}
});
};
};
GroupJoinButton.prototype.decorate = function(elem) {
GroupJoinButton.superClass_.decorate.call(this, elem);
this._group_id = this._element.data('groupId');
};
var TagEditor = function() {
WrappedElement.call(this);
this._has_hot_backspace = false;
this._settings = JSON.parse(askbot['settings']['tag_editor']);
};
inherits(TagEditor, WrappedElement);
TagEditor.prototype.getSelectedTags = function() {
return $.trim(this._hidden_tags_input.val()).split(/\s+/);
};
TagEditor.prototype.setSelectedTags = function(tag_names) {
this._hidden_tags_input.val($.trim(tag_names.join(' ')));
};
TagEditor.prototype.addSelectedTag = function(tag_name) {
var tag_names = this._hidden_tags_input.val();
this._hidden_tags_input.val(tag_names + ' ' + tag_name);
$('.acResults').hide();//a hack to hide the autocompleter
};
TagEditor.prototype.isSelectedTagName = function(tag_name) {
var tag_names = this.getSelectedTags();
return $.inArray(tag_name, tag_names) != -1;
};
TagEditor.prototype.removeSelectedTag = function(tag_name) {
var tag_names = this.getSelectedTags();
var idx = $.inArray(tag_name, tag_names);
if (idx !== -1) {
tag_names.splice(idx, 1)
}
this.setSelectedTags(tag_names);
};
TagEditor.prototype.getTagDeleteHandler = function(tag){
var me = this;
return function(){
me.removeSelectedTag(tag.getName());
me.clearErrorMessage();
tag.dispose();
$('.acResults').hide();//a hack to hide the autocompleter
me.fixHeight();
};
};
TagEditor.prototype.cleanTag = function(tag_name, reject_dupe) {
tag_name = $.trim(tag_name);
tag_name = tag_name.replace(/\s+/, ' ');
var force_lowercase = this._settings['force_lowercase_tags'];
if (force_lowercase) {
tag_name = tag_name.toLowerCase();
}
if (reject_dupe && this.isSelectedTagName(tag_name)) {
throw interpolate(
gettext('tag "%s" was already added, no need to repeat (press "escape" to delete)'),
[tag_name]
);
}
var max_tags = this._settings['max_tags_per_post'];
if (this.getSelectedTags().length + 1 > max_tags) {//count current
throw interpolate(
ngettext(
'a maximum of %s tag is allowed',
'a maximum of %s tags are allowed',
max_tags
),
[max_tags]
);
}
//generic cleaning
return cleanTag(tag_name, this._settings);
};
TagEditor.prototype.addTag = function(tag_name) {
var tag = new Tag();
tag.setName(tag_name);
tag.setDeletable(true);
tag.setLinkable(true);
tag.setDeleteHandler(this.getTagDeleteHandler(tag));
this._tags_container.append(tag.getElement());
this.addSelectedTag(tag_name);
};
TagEditor.prototype.immediateClearErrorMessage = function() {
this._error_alert.html('');
this._error_alert.show();
//this._element.css('margin-top', '18px');//todo: the margin thing is a hack
}
TagEditor.prototype.clearErrorMessage = function(fade) {
if (fade) {
var me = this;
this._error_alert.fadeOut(function(){
me.immediateClearErrorMessage();
});
} else {
this.immediateClearErrorMessage();
}
};
TagEditor.prototype.setErrorMessage = function(text) {
var old_text = this._error_alert.html();
this._error_alert.html(text);
if (old_text == '') {
this._error_alert.hide();
this._error_alert.fadeIn(100);
}
//this._element.css('margin-top', '0');//todo: remove this hack
};
TagEditor.prototype.getAddTagHandler = function() {
var me = this;
return function(tag_name) {
if (me.isSelectedTagName(tag_name)) {
return;
}
try {
var clean_tag_name = me.cleanTag($.trim(tag_name));
me.addTag(clean_tag_name);
me.clearNewTagInput();
me.fixHeight();
} catch (error) {
me.setErrorMessage(error);
setTimeout(function(){
me.clearErrorMessage(true);
}, 1000);
}
};
};
TagEditor.prototype.getRawNewTagValue = function() {
return this._visible_tags_input.val();//without trimming
};
TagEditor.prototype.clearNewTagInput = function() {
return this._visible_tags_input.val('');
};
TagEditor.prototype.editLastTag = function() {
//delete rendered tag
var tc = this._tags_container;
tc.find('li:last').remove();
//remove from hidden tags input
var tags = this.getSelectedTags();
var last_tag = tags.pop();
this.setSelectedTags(tags);
//populate the tag editor
this._visible_tags_input.val(last_tag);
putCursorAtEnd(this._visible_tags_input);
};
TagEditor.prototype.setHotBackspace = function(is_hot) {
this._has_hot_backspace = is_hot;
};
TagEditor.prototype.hasHotBackspace = function() {
return this._has_hot_backspace;
};
TagEditor.prototype.completeTagInput = function(reject_dupe) {
var tag_name = $.trim(this._visible_tags_input.val());
try {
tag_name = this.cleanTag(tag_name, reject_dupe);
this.addTag(tag_name);
this.clearNewTagInput();
} catch (error) {
this.setErrorMessage(error);
}
};
TagEditor.prototype.saveHeight = function() {
return;
var elem = this._visible_tags_input;
this._height = elem.offset().top;
};
TagEditor.prototype.fixHeight = function() {
return;
var new_height = this._visible_tags_input.offset().top;
//@todo: replace this by real measurement
var element_height = parseInt(
this._element.css('height').replace('px', '')
);
if (new_height > this._height) {
this._element.css('height', element_height + 28);//magic number!!!
} else if (new_height < this._height) {
this._element.css('height', element_height - 28);//magic number!!!
}
this.saveHeight();
};
TagEditor.prototype.closeAutoCompleter = function() {
this._autocompleter.finish();
};
TagEditor.prototype.getTagInputKeyHandler = function() {
var new_tags = this._visible_tags_input;
var me = this;
return function(e) {
if (e.shiftKey) {
return;
}
me.saveHeight();
var key = e.which || e.keyCode;
var text = me.getRawNewTagValue();
//space 32, enter 13
if (key == 32 || key == 13) {
var tag_name = $.trim(text);
if (tag_name.length > 0) {
me.completeTagInput(true);//true for reject dupes
}
me.fixHeight();
return false;
}
if (text == '') {
me.clearErrorMessage();
me.closeAutoCompleter();
} else {
try {
/* do-nothing validation here
* just to report any errors while
* the user is typing */
me.cleanTag(text);
me.clearErrorMessage();
} catch (error) {
me.setErrorMessage(error);
}
}
//8 is backspace
if (key == 8 && text.length == 0) {
if (me.hasHotBackspace() === true) {
me.editLastTag();
me.setHotBackspace(false);
} else {
me.setHotBackspace(true);
}
}
//27 is escape
if (key == 27) {
me.clearNewTagInput();
me.clearErrorMessage();
}
if (key !== 8) {
me.setHotBackspace(false);
}
me.fixHeight();
return false;
};
}
TagEditor.prototype.decorate = function(element) {
this._element = element;
this._hidden_tags_input = element.find('input[name="tags"]');//this one is hidden
this._tags_container = element.find('ul.tags');
this._error_alert = $('.tag-editor-error-alert > span');
var me = this;
this._tags_container.children().each(function(idx, elem){
var tag = new Tag();
tag.setDeletable(true);
tag.setLinkable(false);
tag.decorate($(elem));
tag.setDeleteHandler(me.getTagDeleteHandler(tag));
});
var visible_tags_input = element.find('.new-tags-input');
this._visible_tags_input = visible_tags_input;
this.saveHeight();
var me = this;
var tagsAc = new AutoCompleter({
url: askbot['urls']['get_tag_list'],
onItemSelect: function(item){
if (me.isSelectedTagName(item['value']) === false) {
me.completeTagInput();
} else {
me.clearNewTagInput();
}
},
minChars: 1,
useCache: true,
matchInside: true,
maxCacheLength: 100,
delay: 10
});
tagsAc.decorate(visible_tags_input);
this._autocompleter = tagsAc;
visible_tags_input.keyup(this.getTagInputKeyHandler());
element.click(function(e) {
visible_tags_input.focus();
return false;
});
};
/**
* @constructor
* Category is a select box item
* that has CategoryEditControls
*/
var Category = function() {
SelectBoxItem.call(this);
this._state = 'display';
this._settings = JSON.parse(askbot['settings']['tag_editor']);
};
inherits(Category, SelectBoxItem);
Category.prototype.setCategoryTree = function(tree) {
this._tree = tree;
};
Category.prototype.getCategoryTree = function() {
return this._tree;
};
Category.prototype.getName = function() {
return this.getContent().getContent();
};
Category.prototype.getPath = function() {
return this._tree.getPathToItem(this);
};
Category.prototype.setState = function(state) {
this._state = state;
if ( !this._element ) {
return;
}
this._input_box.val('');
if (state === 'display') {
this.showContent();
this.hideEditor();
this.hideEditControls();
} else if (state === 'editable') {
this._tree._state = 'editable';//a hack
this.showContent();
this.hideEditor();
this.showEditControls();
} else if (state === 'editing') {
this._prev_tree_state = this._tree.getState();
this._tree._state = 'editing';//a hack
this._input_box.val(this.getName());
this.hideContent();
this.showEditor();
this.hideEditControls();
}
};
Category.prototype.hideEditControls = function() {
this._delete_button.hide();
this._edit_button.hide();
this._element.unbind('mouseenter mouseleave');
};
Category.prototype.showEditControls = function() {
var del = this._delete_button;
var edit = this._edit_button;
this._element.hover(
function(){
del.show();
edit.show();
},
function(){
del.hide();
edit.hide();
}
);
};
Category.prototype.showEditControlsNow = function() {
this._delete_button.show();
this._edit_button.show();
};
Category.prototype.hideContent = function() {
this.getContent().getElement().hide();
};
Category.prototype.showContent = function() {
this.getContent().getElement().show();
};
Category.prototype.showEditor = function() {
this._input_box.show();
this._input_box.focus();
this._save_button.show();
this._cancel_button.show();
};
Category.prototype.hideEditor = function() {
this._input_box.hide();
this._save_button.hide();
this._cancel_button.hide();
};
Category.prototype.getInput = function() {
return this._input_box.val();
};
Category.prototype.getDeleteHandler = function() {
var me = this;
return function() {
if (confirm(gettext('Delete category?'))) {
var tree = me.getCategoryTree();
$.ajax({
type: 'POST',
dataType: 'json',
data: JSON.stringify({
tag_name: me.getName(),
path: me.getPath()
}),
cache: false,
url: askbot['urls']['delete_tag'],
success: function(data) {
if (data['success']) {
//rebuild category tree based on data
tree.setData(data['tree_data']);
//re-open current branch
tree.selectPath(tree.getCurrentPath());
tree.setState('editable');
} else {
alert(data['message']);
}
}
});
}
return false;
};
};
Category.prototype.getSaveHandler = function() {
var me = this;
var settings = this._settings;
//here we need old value and new value
return function(){
var to_name = me.getInput();
try {
to_name = cleanTag(to_name, settings);
var data = {
from_name: me.getOriginalName(),
to_name: to_name,
path: me.getPath()
};
$.ajax({
type: 'POST',
dataType: 'json',
data: JSON.stringify(data),
cache: false,
url: askbot['urls']['rename_tag'],
success: function(data) {
if (data['success']) {
me.setName(to_name);
me.setState('editable');
me.showEditControlsNow();
} else {
alert(data['message']);
}
}
});
} catch (error) {
alert(error);
}
return false;
};
};
Category.prototype.addControls = function() {
var input_box = this.makeElement('input');
this._input_box = input_box;
this._element.append(input_box);
var save_button = this.makeButton(
gettext('save'),
this.getSaveHandler()
);
this._save_button = save_button;
this._element.append(save_button);
var me = this;
var cancel_button = this.makeButton(
'x',
function(){
me.setState('editable');
me.showEditControlsNow();
return false;
}
);
this._cancel_button = cancel_button;
this._element.append(cancel_button);
var edit_button = this.makeButton(
gettext('edit'),
function(){
//todo: I would like to make only one at a time editable
//var tree = me.getCategoryTree();
//tree.closeAllEditors();
//tree.setState('editable');
//calc path, then select it
var tree = me.getCategoryTree();
tree.selectPath(me.getPath());
me.setState('editing');
return false;
}
);
this._edit_button = edit_button;
this._element.append(edit_button);
var delete_button = this.makeButton(
'x', this.getDeleteHandler()
);
this._delete_button = delete_button;
this._element.append(delete_button);
};
Category.prototype.getOriginalName = function() {
return this._original_name;
};
Category.prototype.createDom = function() {
Category.superClass_.createDom.call(this);
this.addControls();
this.setState('display');
this._original_name = this.getName();
};
Category.prototype.decorate = function(element) {
Category.superClass_.decorate.call(this, element);
this.addControls();
this.setState('display');
this._original_name = this.getName();
};
var CategoryAdder = function() {
WrappedElement.call(this);
this._state = 'disabled';//waitedit
this._tree = undefined;//category tree
this._settings = JSON.parse(askbot['settings']['tag_editor']);
};
inherits(CategoryAdder, WrappedElement);
CategoryAdder.prototype.setCategoryTree = function(tree) {
this._tree = tree;
};
CategoryAdder.prototype.setLevel = function(level) {
this._level = level;
};
CategoryAdder.prototype.setState = function(state) {
this._state = state;
if (!this._element) {
return;
}
if (state === 'waiting') {
this._element.show();
this._input.val('');
this._input.hide();
this._save_button.hide();
this._cancel_button.hide();
this._trigger.show();
} else if (state === 'editable') {
this._element.show();
this._input.show();
this._input.val('');
this._input.focus();
this._save_button.show();
this._cancel_button.show();
this._trigger.hide();
} else if (state === 'disabled') {
this.setState('waiting');//a little hack
this._state = 'disabled';
this._element.hide();
}
};
CategoryAdder.prototype.cleanCategoryName = function(name) {
name = $.trim(name);
if (name === '') {
throw gettext('category name cannot be empty');
}
//if ( this._tree.hasCategory(name) ) {
//throw interpolate(
//throw gettext('this category already exists');
// [this._tree.getDisplayPathByName(name)]
//)
//}
return cleanTag(name, this._settings);
};
CategoryAdder.prototype.getPath = function() {
var path = this._tree.getCurrentPath();
if (path.length > this._level + 1) {
return path.slice(0, this._level + 1);
} else {
return path;
}
};
CategoryAdder.prototype.getSelectBox = function() {
return this._tree.getSelectBox(this._level);
};
CategoryAdder.prototype.startAdding = function() {
try {
var name = this._input.val();
name = this.cleanCategoryName(name);
} catch (error) {
alert(error);
return;
}
//don't add dupes to the same level
var existing_names = this.getSelectBox().getNames();
if ($.inArray(name, existing_names) != -1) {
alert(gettext('already exists at the current level!'));
return;
}
var me = this;
var tree = this._tree;
var adder_path = this.getPath();
$.ajax({
type: 'POST',
dataType: 'json',
data: JSON.stringify({
path: adder_path,
new_category_name: name
}),
url: askbot['urls']['add_tag_category'],
cache: false,
success: function(data) {
if (data['success']) {
//rebuild category tree based on data
tree.setData(data['tree_data']);
tree.selectPath(data['new_path']);
tree.setState('editable');
me.setState('waiting');
} else {
alert(data['message']);
}
}
});
};
CategoryAdder.prototype.createDom = function() {
this._element = this.makeElement('li');
//add open adder link
var trigger = this.makeElement('a');
this._trigger = trigger;
trigger.html(gettext('add category'));
this._element.append(trigger);
//add input box and the add button
var input = this.makeElement('input');
this._input = input;
input.addClass('add-category');
input.attr('name', 'add_category');
this._element.append(input);
//add save category button
var save_button = this.makeElement('button');
this._save_button = save_button;
save_button.html(gettext('save'));
this._element.append(save_button);
var cancel_button = this.makeElement('button');
this._cancel_button = cancel_button;
cancel_button.html('x');
this._element.append(cancel_button);
this.setState(this._state);
var me = this;
setupButtonEventHandlers(
trigger,
function(){ me.setState('editable'); }
)
setupButtonEventHandlers(
save_button,
function() {
me.startAdding();
return false;//prevent form submit
}
);
setupButtonEventHandlers(
cancel_button,
function() {
me.setState('waiting');
return false;//prevent submit
}
);
//create input box, button and the "activate" link
};
/**
* @constructor
* SelectBox subclass to create/edit/delete
* categories
*/
var CategorySelectBox = function() {
SelectBox.call(this);
this._item_class = Category;
this._category_adder = undefined;
this._tree = undefined;//cat tree
this._level = undefined;
};
inherits(CategorySelectBox, SelectBox);
CategorySelectBox.prototype.setState = function(state) {
this._state = state;
if (state === 'select') {
if (this._category_adder) {
this._category_adder.setState('disabled');
}
$.each(this._items, function(idx, item){
item.setState('display');
});
} else if (state === 'editable') {
this._category_adder.setState('waiting');
$.each(this._items, function(idx, item){
item.setState('editable');
});
}
};
CategorySelectBox.prototype.setCategoryTree = function(tree) {
this._tree = tree;
};
CategorySelectBox.prototype.getCategoryTree = function() {
};
CategorySelectBox.prototype.setLevel = function(level) {
this._level = level;
};
CategorySelectBox.prototype.getNames = function() {
var names = [];
$.each(this._items, function(idx, item) {
names.push(item.getName());
});
return names;
};
CategorySelectBox.prototype.appendCategoryAdder = function() {
var adder = new CategoryAdder();
adder.setLevel(this._level);
adder.setCategoryTree(this._tree);
this._category_adder = adder;
this._element.append(adder.getElement());
};
CategorySelectBox.prototype.createDom = function() {
CategorySelectBox.superClass_.createDom();
if (askbot['data']['userIsAdmin']) {
this.appendCategoryAdder();
}
};
CategorySelectBox.prototype.decorate = function(element) {
CategorySelectBox.superClass_.decorate.call(this, element);
this.setState(this._state);
if (askbot['data']['userIsAdmin']) {
this.appendCategoryAdder();
}
};
/**
* @constructor
* turns on/off the category editor
*/
var CategoryEditorToggle = function() {
TwoStateToggle.call(this);
};
inherits(CategoryEditorToggle, TwoStateToggle);
CategoryEditorToggle.prototype.setCategorySelector = function(sel) {
this._category_selector = sel;
};
CategoryEditorToggle.prototype.getCategorySelector = function() {
return this._category_selector;
};
CategoryEditorToggle.prototype.decorate = function(element) {
CategoryEditorToggle.superClass_.decorate.call(this, element);
};
CategoryEditorToggle.prototype.getDefaultHandler = function() {
var me = this;
return function() {
var editor = me.getCategorySelector();
if (me.isOn()) {
me.setState('off-state');
editor.setState('select');
} else {
me.setState('on-state');
editor.setState('editable');
}
};
};
var CategorySelector = function() {
Widget.call(this);
this._data = null;
this._select_handler = function(){};//dummy default
this._current_path = [0];//path points to selected item in tree
};
inherits(CategorySelector, Widget);
/**
* propagates state to the individual selectors
*/
CategorySelector.prototype.setState = function(state) {
this._state = state;
if (state === 'editing') {
return;//do not propagate this state
}
$.each(this._selectors, function(idx, selector){
selector.setState(state);
});
};
CategorySelector.prototype.getPathToItem = function(item) {
function findPathToItemInTree(tree, item) {
for (var i = 0; i < tree.length; i++) {
var node = tree[i];
if (node[2] === item) {
return [i];
}
var path = findPathToItemInTree(node[1], item);
if (path.length > 0) {
path.unshift(i);
return path;
}
}
return [];
};
return findPathToItemInTree(this._data, item);
};
CategorySelector.prototype.applyToDataItems = function(func) {
function applyToDataItems(tree) {
$.each(tree, function(idx, item) {
func(item);
applyToDataItems(item[1]);
});
};
if (this._data) {
applyToDataItems(this._data);
}
};
CategorySelector.prototype.setData = function(data) {
this._clearData
this._data = data;
var tree = this;
function attachCategory(item) {
var cat = new Category();
cat.setName(item[0]);
cat.setCategoryTree(tree);
item[2] = cat;
};
this.applyToDataItems(attachCategory);
};
/**
* clears contents of selector boxes starting from
* the given level, in range 0..2
*/
CategorySelector.prototype.clearCategoryLevels = function(level) {
for (var i = level; i < 3; i++) {
this._selectors[i].detachAllItems();
}
};
CategorySelector.prototype.getLeafItems = function(selection_path) {
//traverse the tree down to items pointed to by the path
var data = this._data[0];
for (var i = 1; i < selection_path.length; i++) {
data = data[1][selection_path[i]];
}
return data[1];
}
/**
* called when a sub-level needs to open
*/
CategorySelector.prototype.populateCategoryLevel = function(source_path) {
var level = source_path.length - 1;
if (level >= 3) {
return;
}
//clear all items downstream
this.clearCategoryLevels(level);
//populate current selector
var selector = this._selectors[level];
var items = this.getLeafItems(source_path);
$.each(items, function(idx, item) {
var category_name = item[0];
var category_subtree = item[1];
var category_object = item[2];
selector.addItemObject(category_object);
if (category_subtree.length > 0) {
category_object.addCssClass('tree');
}
});
this.setState(this._state);//update state
selector.clearSelection();
};
CategorySelector.prototype.selectPath = function(path) {
for (var i = 1; i <= path.length; i++) {
this.populateCategoryLevel(path.slice(0, i));
}
for (var i = 1; i < path.length; i++) {
var sel_box = this._selectors[i-1];
var category = sel_box.getItemByIndex(path[i]);
sel_box.selectItem(category);
}
};
CategorySelector.prototype.getSelectBox = function(level) {
return this._selectors[level];
};
CategorySelector.prototype.getSelectedPath = function(selected_level) {
var path = [0];//root, todo: better use names for path???
/*
* upper limit capped by current clicked level
* we ignore all selection above the current level
*/
for (var i = 0; i < selected_level + 1; i++) {
var selector = this._selectors[i];
var item = selector.getSelectedItem();
if (item) {
path.push(selector.getItemIndex(item));
} else {
return path;
}
}
return path;
};
/** getter and setter are not symmetric */
CategorySelector.prototype.setSelectHandler = function(handler) {
this._select_handler = handler;
};
CategorySelector.prototype.getSelectHandlerInternal = function() {
return this._select_handler;
};
CategorySelector.prototype.setCurrentPath = function(path) {
return this._current_path = path;
};
CategorySelector.prototype.getCurrentPath = function() {
return this._current_path;
};
CategorySelector.prototype.getEditorToggle = function() {
return this._editor_toggle;
};
/*CategorySelector.prototype.closeAllEditors = function() {
$.each(this._selectors, function(idx, sel) {
sel._category_adder.setState('wait');
$.each(sel._items, function(idx2, item) {
item.setState('editable');
});
});
};*/
CategorySelector.prototype.getSelectHandler = function(level) {
var me = this;
return function(item_data) {
if (me.getState() === 'editing') {
return;//don't navigate when editing
}
//1) run the assigned select handler
var tag_name = item_data['title']
if (me.getState() === 'select') {
/* this one will actually select the tag
* maybe a bit too implicit
*/
me.getSelectHandlerInternal()(tag_name);
}
//2) if appropriate, populate the higher level
if (level < 2) {
var current_path = me.getSelectedPath(level);
me.setCurrentPath(current_path);
me.populateCategoryLevel(current_path);
}
}
};
CategorySelector.prototype.decorate = function(element) {
this._element = element;
this._selectors = [];
var selector0 = new CategorySelectBox();
selector0.setLevel(0);
selector0.setCategoryTree(this);
selector0.decorate(element.find('.cat-col-0'));
selector0.setSelectHandler(this.getSelectHandler(0));
this._selectors.push(selector0);
var selector1 = new CategorySelectBox();
selector1.setLevel(1);
selector1.setCategoryTree(this);
selector1.decorate(element.find('.cat-col-1'));
selector1.setSelectHandler(this.getSelectHandler(1));
this._selectors.push(selector1)
var selector2 = new CategorySelectBox();
selector2.setLevel(2);
selector2.setCategoryTree(this);
selector2.decorate(element.find('.cat-col-2'));
selector2.setSelectHandler(this.getSelectHandler(2));
this._selectors.push(selector2);
if (askbot['data']['userIsAdminOrMod']) {
var editor_toggle = new CategoryEditorToggle();
editor_toggle.setCategorySelector(this);
var toggle_element = $('.category-editor-toggle');
toggle_element.show();
editor_toggle.decorate(toggle_element);
this._editor_toggle = editor_toggle;
}
this.populateCategoryLevel([0]);
};
/**
* @constructor
* loads html for the category selector from
* the server via ajax and activates the
* CategorySelector on the loaded HTML
*/
var CategorySelectorLoader = function() {
WrappedElement.call(this);
this._is_loaded = false;
};
inherits(CategorySelectorLoader, WrappedElement);
CategorySelectorLoader.prototype.setCategorySelector = function(sel) {
this._category_selector = sel;
};
CategorySelectorLoader.prototype.setLoaded = function(is_loaded) {
this._is_loaded = is_loaded;
};
CategorySelectorLoader.prototype.isLoaded = function() {
return this._is_loaded;
};
CategorySelectorLoader.prototype.setEditor = function(editor) {
this._editor = editor;
};
CategorySelectorLoader.prototype.closeEditor = function() {
this._editor.hide();
this._editor_buttons.hide();
this._display_tags_container.show();
this._question_body.show();
this._question_controls.show();
};
CategorySelectorLoader.prototype.openEditor = function() {
this._editor.show();
this._editor_buttons.show();
this._display_tags_container.hide();
this._question_body.hide();
this._question_controls.hide();
var sel = this._category_selector;
sel.setState('select');
sel.getEditorToggle().setState('off-state');
};
CategorySelectorLoader.prototype.addEditorButtons = function() {
this._editor.after(this._editor_buttons);
};
CategorySelectorLoader.prototype.getOnLoadHandler = function() {
var me = this;
return function(html){
me.setLoaded(true);
//append loaded html to dom
var editor = $('<div>' + html + '</div>');
me.setEditor(editor);
$('#question-tags').after(editor);
var selector = askbot['functions']['initCategoryTree']();
me.setCategorySelector(selector);
me.addEditorButtons();
me.openEditor();
//add the save button
};
};
CategorySelectorLoader.prototype.startLoadingHTML = function(on_load) {
var me = this;
$.ajax({
type: 'GET',
dataType: 'json',
data: { template_name: 'widgets/tag_category_selector.html' },
url: askbot['urls']['get_html_template'],
cache: true,
success: function(data) {
if (data['success']) {
on_load(data['html']);
} else {
showMessage(me.getElement(), data['message']);
}
}
});
};
CategorySelectorLoader.prototype.getRetagHandler = function() {
var me = this;
return function() {
if (me.isLoaded() === false) {
me.startLoadingHTML(me.getOnLoadHandler());
} else {
me.openEditor();
}
return false;
}
};
CategorySelectorLoader.prototype.drawNewTags = function(new_tags) {
if (new_tags === ''){
this._display_tags_container.html('');
return;
}
new_tags = new_tags.split(/\s+/);
var tags_html = ''
$.each(new_tags, function(index, name){
var tag = new Tag();
tag.setName(name);
tags_html += tag.getElement().outerHTML();
});
this._display_tags_container.html(tags_html);
};
CategorySelectorLoader.prototype.getSaveHandler = function() {
var me = this;
return function() {
var tagInput = $('input[name="tags"]');
$.ajax({
type: "POST",
url: retagUrl,//add to askbot['urls']
dataType: "json",
data: { tags: getUniqueWords(tagInput.val()).join(' ') },
success: function(json) {
if (json['success'] === true){
var new_tags = getUniqueWords(json['new_tags']);
oldTagsHtml = '';
me.closeEditor();
me.drawNewTags(new_tags.join(' '));
}
else {
me.closeEditor();
showMessage(me.getElement(), json['message']);
}
},
error: function(xhr, textStatus, errorThrown) {
showMessage(tagsDiv, 'sorry, something is not right here');
cancelRetag();
}
});
return false;
};
};
CategorySelectorLoader.prototype.getCancelHandler = function() {
var me = this;
return function() {
me.closeEditor();
};
};
CategorySelectorLoader.prototype.decorate = function(element) {
this._element = element;
this._display_tags_container = $('#question-tags');
this._question_body = $('.question .post-body');
this._question_controls = $('#question-controls');
this._editor_buttons = this.makeElement('div');
this._done_button = this.makeElement('button');
this._done_button.html(gettext('save tags'));
this._editor_buttons.append(this._done_button);
this._cancel_button = this.makeElement('button');
this._cancel_button.html(gettext('cancel'));
this._editor_buttons.append(this._cancel_button);
this._editor_buttons.find('button').addClass('submit');
this._editor_buttons.addClass('retagger-buttons');
//done button
setupButtonEventHandlers(
this._done_button,
this.getSaveHandler()
);
//cancel button
setupButtonEventHandlers(
this._cancel_button,
this.getCancelHandler()
);
//retag button
setupButtonEventHandlers(
element,
this.getRetagHandler()
);
};
$(document).ready(function() {
$('[id^="comments-for-"]').each(function(index, element){
var comments = new PostCommentsWidget();
comments.decorate(element);
});
$('[id^="swap-question-with-answer-"]').each(function(idx, element){
var swapper = new QASwapper();
swapper.decorate($(element));
});
$('[id^="post-id-"]').each(function(idx, element){
var deleter = new DeletePostLink();
//confusingly .question-delete matches the answers too need rename
var post_id = element.id.split('-').pop();
deleter.setPostId(post_id);
deleter.decorate($(element).find('.question-delete'));
});
//todo: convert to "control" class
var publishBtns = $('.answer-publish, .answer-unpublish');
publishBtns.each(function(idx, btn) {
setupButtonEventHandlers($(btn), function() {
var answerId = $(btn).data('answerId');
$.ajax({
type: 'POST',
dataType: 'json',
data: {'answer_id': answerId},
url: askbot['urls']['publishAnswer'],
success: function(data) {
if (data['success']) {
window.location.reload(true);
} else {
showMessage($(btn), data['message']);
}
}
});
});
});
if (askbot['settings']['tagSource'] == 'category-tree') {
var catSelectorLoader = new CategorySelectorLoader();
catSelectorLoader.decorate($('#retag'));
} else {
questionRetagger.init();
}
socialSharing.init();
var proxyUserNameInput = $('#id_post_author_username');
var proxyUserEmailInput = $('#id_post_author_email');
if (proxyUserNameInput.length === 1) {
var userSelectHandler = function(data) {
proxyUserEmailInput.val(data['data'][0]);
};
var fakeUserAc = new AutoCompleter({
url: '/get-users-info/',//askbot['urls']['get_users_info'],
promptText: gettext('User name:'),
minChars: 1,
useCache: true,
matchInside: true,
maxCacheLength: 100,
delay: 10,
onItemSelect: userSelectHandler
});
fakeUserAc.decorate(proxyUserNameInput);
if (proxyUserEmailInput.length === 1) {
var tip = new TippedInput();
tip.decorate(proxyUserEmailInput);
}
}
//if groups are enabled - activate share functions
var groupsInput = $('#share_group_name');
if (groupsInput.length === 1) {
var groupsAc = new AutoCompleter({
url: askbot['urls']['getGroupsList'],
promptText: gettext('Group name:'),
minChars: 1,
useCache: false,
matchInside: true,
maxCacheLength: 100,
delay: 10
});
groupsAc.decorate(groupsInput);
}
var usersInput = $('#share_user_name');
if (usersInput.length === 1) {
var usersAc = new AutoCompleter({
url: '/get-users-info/',
promptText: gettext('User name:'),
minChars: 1,
useCache: false,
matchInside: true,
maxCacheLength: 100,
delay: 10
});
usersAc.decorate(usersInput);
}
var showSharedUsers = $('.see-related-users');
if (showSharedUsers.length) {
var usersPopup = new ThreadUsersDialog();
usersPopup.setHeadingText(gettext('Shared with the following users:'));
usersPopup.decorate(showSharedUsers);
}
var showSharedGroups = $('.see-related-groups');
if (showSharedGroups.length) {
var groupsPopup = new ThreadUsersDialog();
groupsPopup.setHeadingText(gettext('Shared with the following groups:'));
groupsPopup.decorate(showSharedGroups);
}
});
/* google prettify.js from google code */
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c<i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2<i&&"-"===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d<65||j>122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c<b.length;++c)i=b[c],i[0]<=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=["["];o&&b.push("^");b.push.apply(b,a);for(c=0;c<
f.length;++c)i=f[c],b.push(e(i[0])),i[1]>i[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c<b;++c){var j=f[c];j==="("?++i:"\\"===j.charAt(0)&&(j=+j.substring(1))&&j<=i&&(d[j]=-1)}for(c=1;c<d.length;++c)-1===d[c]&&(d[c]=++t);for(i=c=0;c<b;++c)j=f[c],j==="("?(++i,d[i]===void 0&&(f[c]="(?:")):"\\"===j.charAt(0)&&
(j=+j.substring(1))&&j<=i&&(f[c]="\\"+d[i]);for(i=c=0;c<b;++c)"^"===f[c]&&"^"!==f[c+1]&&(f[c]="");if(a.ignoreCase&&s)for(c=0;c<b;++c)j=f[c],a=j.charAt(0),j.length>=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p<d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,""))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p<d;++p){g=a[p];if(g.global||g.multiline)throw Error(""+g);n.push("(?:"+y(g)+")")}return RegExp(n.join("|"),l?"gi":"g")}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if("BR"===g||"LI"===g)h[s]="\n",t[s<<1]=y++,t[s++<<1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&&(g=p?g.replace(/\r\n?/g,"\n"):g.replace(/[\t\n\r ]+/g," "),h[s]=g,t[s<<1]=y,y+=g.length,
t[s++<<1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=document.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);m(a);return{a:h.join("").replace(/\n$/,""),c:t}}function B(a,m,e,h){m&&(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,"pln"],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n<z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
"string")c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c<t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b="pln")}if((c=b.length>=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d<g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k>=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/,
q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g,
"");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a),
a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g<d.length;++g)e(d[g]);m===(m|0)&&d[0].setAttribute("value",
m);var r=s.createElement("OL");r.className="linenums";for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g<z;++g)l=d[g],l.className="L"+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode("\xa0")),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e>=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*</.test(m)?"default-markup":"default-code";return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n<g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n<g;){for(var z=d[n],f=d[n+1],b=n+2;b+2<=g&&d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h<p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&&(j=t.substring(e,b))){k&&(j=j.replace(m,"\r"));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement("SPAN");v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e<o&&(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e>=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"],
"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"],
H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"],
J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^<?]+/],["dec",/^<!\w[^>]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^<xmp\b[^>]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^<script\b[^>]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),
["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css",
/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes",
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p<h.length&&l.now()<e;p++){var n=h[p],k=n.className;if(k.indexOf("prettyprint")>=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p<h.length?setTimeout(m,
250):a&&a()}for(var e=[document.getElementsByTagName("pre"),document.getElementsByTagName("code"),document.getElementsByTagName("xmp")],h=[],k=0;k<e.length;++k)for(var t=0,s=e[k].length;t<s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit",
PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ"}})();
| simalytics/askbot-devel | static/default/media/js/post.js | JavaScript | gpl-3.0 | 160,054 |
/*
* This file is part of ADDIS (Aggregate Data Drug Information System).
* ADDIS is distributed from http://drugis.org/.
* Copyright © 2009 Gert van Valkenhoef, Tommi Tervonen.
* Copyright © 2010 Gert van Valkenhoef, Tommi Tervonen, Tijs Zwinkels,
* Maarten Jacobs, Hanno Koeslag, Florin Schimbinschi, Ahmad Kamal, Daniel
* Reid.
* Copyright © 2011 Gert van Valkenhoef, Ahmad Kamal, Daniel Reid, Florin
* Schimbinschi.
* Copyright © 2012 Gert van Valkenhoef, Daniel Reid, Joël Kuiper, Wouter
* Reckman.
* Copyright © 2013 Gert van Valkenhoef, Joël Kuiper.
*
* 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 org.drugis.addis.entities.relativeeffect;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.drugis.common.beans.AbstractObservable;
public abstract class GaussianBase extends AbstractObservable implements Distribution {
private double d_mu;
private double d_sigma;
private NormalDistribution d_dist;
public GaussianBase(double mu, double sigma) {
if (Double.isNaN(mu)) throw new IllegalArgumentException("mu may not be NaN");
if (Double.isNaN(sigma)) throw new IllegalArgumentException("sigma may not be NaN");
if (sigma < 0.0) throw new IllegalArgumentException("sigma must be >= 0.0");
d_mu = mu;
d_sigma = sigma;
if (getSigma() != 0.0) {
d_dist = new NormalDistribution(d_mu, d_sigma);
}
}
protected double calculateQuantile(double p) {
if (getSigma() == 0.0) {
return getMu();
}
return d_dist.inverseCumulativeProbability(p);
}
protected double calculateCumulativeProbability(double x) {
return d_dist.cumulativeProbability(x);
}
public double getSigma() {
return d_sigma;
}
public double getMu() {
return d_mu;
}
public GaussianBase plus(GaussianBase other) {
if (!canEqual(other)) throw new IllegalArgumentException(
"Cannot add together " + getClass().getSimpleName() +
" and " + other.getClass().getSimpleName());
return newInstance(getMu() + other.getMu(),
Math.sqrt(getSigma() * getSigma() + other.getSigma() * other.getSigma()));
}
protected abstract GaussianBase newInstance(double mu, double sigma);
abstract protected boolean canEqual(GaussianBase other);
@Override
public boolean equals(Object obj) {
if (obj instanceof GaussianBase) {
GaussianBase other = (GaussianBase) obj;
return canEqual(other) && d_mu == other.d_mu && d_sigma == other.d_sigma;
}
return false;
}
@Override
public int hashCode() {
return ((Double)d_mu).hashCode() + 31 * ((Double)d_sigma).hashCode();
}
@Override
public String toString() {
return getClass().getSimpleName() + "(mu=" + getMu() + ", sigma=" + getSigma() + ")";
}
}
| drugis/addis | application/src/main/java/org/drugis/addis/entities/relativeeffect/GaussianBase.java | Java | gpl-3.0 | 3,288 |
// http://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
},
extends: 'airbnb-base',
// required to lint *.vue files
plugins: [
'html'
],
// check if imports actually resolve
'settings': {
'import/resolver': {
'webpack': {
'config': 'scripts/webpack.conf.js'
}
}
},
// add your custom rules here
'rules': {
// don't require .vue extension when importing
'import/extensions': ['error', 'always', {
'js': 'never',
'vue': 'never'
}],
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
'no-console': ['warn', {
allow: ['error', 'warn', 'info'],
}],
'no-param-reassign': ['error', {
props: false,
}],
'consistent-return': 'off',
'no-use-before-define': ['error', 'nofunc'],
'object-shorthand': ['error', 'always'],
'no-mixed-operators': 'off',
'no-bitwise': ['error', { int32Hint: true }],
'no-underscore-dangle': 'off',
'arrow-parens': ['error', 'as-needed'],
'prefer-promise-reject-errors': 'off',
'prefer-destructuring': ['error', { array: false }],
indent: ['error', 2, {
MemberExpression: 0,
flatTernaryExpressions: true,
}],
},
globals: {
browser: true,
zip: true,
},
}
| gera2ld/Stylish-mx | .eslintrc.js | JavaScript | gpl-3.0 | 1,429 |
# -*- coding: UTF-8 -*-
"""
Lastship Add-on (C) 2019
Credits to Lastship, Placenta and Covenant; our thanks go to their creators
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/>.
"""
# Addon Name: Lastship
# Addon id: plugin.video.lastship
# Addon Provider: Lastship
import re
import urlparse
from resources.lib.modules import cache
from resources.lib.modules import cleantitle
from resources.lib.modules import client
from resources.lib.modules import source_utils
from resources.lib.modules import dom_parser
from resources.lib.modules import source_faultlog
from resources.lib.modules.handler.requestHandler import cRequestHandler
class source:
def __init__(self):
self.priority = 1
self.language = ['de']
self.domains = ['movie4k.sg', 'movie4k.lol', 'movie4k.pe', 'movie4k.tv', 'movie.to', 'movie4k.me', 'movie4k.org', 'movie2k.cm', 'movie2k.nu', 'movie4k.am', 'movie4k.io']
self._base_link = None
self.search_link = '/movies.php?list=search&search=%s'
@property
def base_link(self):
if not self._base_link:
self._base_link = cache.get(self.__get_base_url, 120, 'http://%s' % self.domains[0])
return self._base_link
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = self.__search(False, [localtitle] + source_utils.aliases_to_array(aliases), year)
if not url and title != localtitle: url = self.__search(False, [title] + source_utils.aliases_to_array(aliases), year)
return url
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
url = self.__search(True, [localtvshowtitle] + source_utils.aliases_to_array(aliases), year)
if not url and tvshowtitle != localtvshowtitle:
url = self.__search(True, [tvshowtitle] + source_utils.aliases_to_array(aliases), year)
if url:
return url
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
if url is None:
return
url = urlparse.urljoin(self.base_link, url)
oRequest = cRequestHandler(url)
oRequest.removeBreakLines(False)
oRequest.removeNewLines(False)
r = oRequest.request()
seasonMapping = dom_parser.parse_dom(r, 'select', attrs={'name': 'season'})
seasonMapping = dom_parser.parse_dom(seasonMapping, 'option', req='value')
seasonIndex = [i.attrs['value'] for i in seasonMapping if season in i.content]
seasonIndex = int(seasonIndex[0]) - 1
seasons = dom_parser.parse_dom(r, 'div', attrs={'id': re.compile('episodediv.+?')})
seasons = seasons[seasonIndex]
episodes = dom_parser.parse_dom(seasons, 'option', req='value')
url = [i.attrs['value'] for i in episodes if episode == re.findall('\d+', i.content)[0]]
if len(url) > 0:
return url[0]
except:
return
def sources(self, url, hostDict, hostprDict):
sources = []
try:
if not url:
return sources
url = urlparse.urljoin(self.base_link, url)
oRequest = cRequestHandler(url)
oRequest.removeBreakLines(False)
oRequest.removeNewLines(False)
r = oRequest.request()
r = r.replace('\\"', '"')
links = dom_parser.parse_dom(r, 'tr', attrs={'id': 'tablemoviesindex2'})
for i in links:
try:
host = dom_parser.parse_dom(i, 'img', req='alt')[0].attrs['alt']
host = host.split()[0].rsplit('.', 1)[0].strip().lower()
host = host.encode('utf-8')
valid, host = source_utils.is_host_valid(host, hostDict)
if not valid: continue
link = dom_parser.parse_dom(i, 'a', req='href')[0].attrs['href']
link = client.replaceHTMLCodes(link)
link = urlparse.urljoin(self.base_link, link)
link = link.encode('utf-8')
sources.append({'source': host, 'quality': 'SD', 'language': 'de', 'url': link, 'direct': False, 'debridonly': False})
except:
pass
if len(sources) == 0:
raise Exception()
return sources
except:
source_faultlog.logFault(__name__,source_faultlog.tagScrape, url)
return sources
def resolve(self, url):
try:
h = urlparse.urlparse(url.strip().lower()).netloc
oRequest = cRequestHandler(url)
oRequest.removeBreakLines(False)
oRequest.removeNewLines(False)
r = oRequest.request()
r = r.rsplit('"underplayer"')[0].rsplit("'underplayer'")[0]
u = re.findall('\'(.+?)\'', r) + re.findall('\"(.+?)\"', r)
u = [client.replaceHTMLCodes(i) for i in u]
u = [i for i in u if i.startswith('http') and not h in i]
url = u[-1].encode('utf-8')
if 'bit.ly' in url:
oRequest = cRequestHandler(url)
oRequest.removeBreakLines(False)
oRequest.removeNewLines(False)
oRequest.request()
url = oRequest.getHeaderLocationUrl()
elif 'nullrefer.com' in url:
url = url.replace('nullrefer.com/?', '')
return url
except:
source_faultlog.logFault(__name__,source_faultlog.tagResolve)
return
def __search(self, isSerieSearch, titles, year):
try:
q = self.search_link % titles[0]
q = urlparse.urljoin(self.base_link, q)
t = [cleantitle.get(i) for i in set(titles) if i]
oRequest = cRequestHandler(q)
oRequest.removeBreakLines(False)
oRequest.removeNewLines(False)
r = oRequest.request()
links = dom_parser.parse_dom(r, 'tr', attrs={'id': re.compile('coverPreview.+?')})
tds = [dom_parser.parse_dom(i, 'td') for i in links]
tuples = [(dom_parser.parse_dom(i[0], 'a')[0], re.findall('>(\d{4})', i[1].content)) for i in tds if 'ger' in i[4].content]
tuplesSortByYear = [(i[0].attrs['href'], i[0].content) for i in tuples if year in i[1]]
if len(tuplesSortByYear) > 0 and not isSerieSearch:
tuples = tuplesSortByYear
elif isSerieSearch:
tuples = [(i[0].attrs['href'], i[0].content) for i in tuples if "serie" in i[0].content.lower()]
else:
tuples = [(i[0].attrs['href'], i[0].content) for i in tuples]
urls = [i[0] for i in tuples if cleantitle.get(i[1]) in t]
if len(urls) == 0:
urls = [i[0] for i in tuples if 'untertitel' not in i[1]]
if len(urls) > 0:
return source_utils.strip_domain(urls[0])
except:
try:
source_faultlog.logFault(__name__, source_faultlog.tagSearch, titles[0])
except:
return
return
def __get_base_url(self, fallback):
try:
for domain in self.domains:
try:
url = 'http://%s' % domain
oRequest = cRequestHandler(url)
oRequest.removeBreakLines(False)
oRequest.removeNewLines(False)
r = oRequest.request()
r = dom_parser.parse_dom(r, 'meta', attrs={'name': 'author'}, req='content')
if r and 'movie4k.io' in r[0].attrs.get('content').lower():
return url
except:
pass
except:
pass
return fallback
| lastship/plugin.video.lastship | resources/lib/sources/de/movie4k.py | Python | gpl-3.0 | 8,599 |
var interval = setInterval(function () {
$("button[type=submit]").hide();
$("p.info").hide();
try {
var prompting = loadTXT("/data/status.json");
if (prompting.indexOf("started")>0 || prompting.indexOf("active")>0 ) {
$("button[type=submit]").show();
$("p.warning").hide();
$("p.info").show();
clearInterval(interval);
}
} catch (e) {
// Silently quit
}
}, 1000); | opendomo/OpenDomoOS | src/odbase/var/www/scripts/wizFirstConfigurationStep5.sh.js | JavaScript | gpl-3.0 | 389 |
class Cms::Controller::Admin::Base < Sys::Controller::Admin::Base
include Cms::Controller::Layout
helper Cms::FormHelper
layout 'admin/cms'
def default_url_options
Core.concept ? { :concept => Core.concept.id } : {}
end
def initialize_application
return false unless super
if params[:cms_navi] && params[:cms_navi][:site]
site_id = params[:cms_navi][:site]
expires = site_id.blank? ? Time.now - 60 : Time.now + 60*60*24*7
unless Core.user.root?
# システム管理者以外は所属サイトしか操作できない
site_id = Core.user.site_ids.first unless Core.user.site_ids.include?(site_id.to_i)
end
cookies[:cms_site] = {:value => site_id, :path => '/', :expires => expires}
Core.set_concept(session, 0)
return redirect_to "/#{ZomekiCMS::ADMIN_URL_PREFIX}"
end
if cookies[:cms_site] && !Core.site
cookies.delete(:cms_site)
Core.site = nil
end
if Core.user
if params[:concept]
concept = Cms::Concept.find_by(id: params[:concept])
if concept && Core.site.id != concept.site_id
Core.set_concept(session, 0)
else
Core.set_concept(session, params[:concept])
end
elsif Core.request_uri == "/#{ZomekiCMS::ADMIN_URL_PREFIX}"
Core.set_concept(session, 0)
else
Core.set_concept(session)
end
end
return true
end
end
| zomeki/zomeki2-development | lib/cms/controller/admin/base.rb | Ruby | gpl-3.0 | 1,475 |
<?php
/**
* Next/Previous Post Pagination Link
* -----------------------------------------------------------------------------
* @category PHP Script
* @package Sheepie
* @author Mark Grealish <mark@bhalash.com>
* @copyright Copyright (c) 2015 Mark Grealish
* @license https://www.gnu.org/copyleft/gpl.html The GNU GPL v3.0
* @version 1.0
* @link https://github.com/bhalash/sheepie
*/
?>
<nav class="pagination pagination--post noprint vcenter--full" id="pagination--post">
<p class="pagination__previous previous-post meta">
<?php next_post_link('%link', '%title', false); ?>
</p>
<p class="pagination__next next-post meta">
<?php previous_post_link('%link', '%title', false); ?>
</p>
</nav>
| bhalash/sheepie | partials/pagination-post.php | PHP | gpl-3.0 | 760 |
../../../../../share/pyshared/checkbox/reports/__init__.py | Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/checkbox/reports/__init__.py | Python | gpl-3.0 | 58 |
<?php
/**
* Copyright © OXID eSales AG. All rights reserved.
* See LICENSE file for license details.
*/
namespace OxidEsales\EshopCommunity\Application\Model;
use oxRegistry;
use oxDb;
/**
* Promotion List manager.
*/
class ActionList extends \OxidEsales\Eshop\Core\Model\ListModel
{
/**
* List Object class name
*
* @var string
*/
protected $_sObjectsInListName = 'oxactions';
/**
* Loads x last finished promotions
*
* @param int $iCount count to load
*/
public function loadFinishedByCount($iCount)
{
$sViewName = $this->getBaseObject()->getViewName();
$sDate = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime());
$oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
$sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and oxactiveto>0 and oxactiveto < " . $oDb->quote($sDate) . "
" . $this->_getUserGroupFilter() . "
order by oxactiveto desc, oxactivefrom desc limit " . (int) $iCount;
$this->selectString($sQ);
$this->_aArray = array_reverse($this->_aArray, true);
}
/**
* Loads last finished promotions after given timespan
*
* @param int $iTimespan timespan to load
*/
public function loadFinishedByTimespan($iTimespan)
{
$sViewName = $this->getBaseObject()->getViewName();
$sDateTo = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime());
$sDateFrom = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime() - $iTimespan);
$oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
$sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and oxactiveto < " . $oDb->quote($sDateTo) . " and oxactiveto > " . $oDb->quote($sDateFrom) . "
" . $this->_getUserGroupFilter() . "
order by oxactiveto, oxactivefrom";
$this->selectString($sQ);
}
/**
* Loads current promotions
*/
public function loadCurrent()
{
$sViewName = $this->getBaseObject()->getViewName();
$sDate = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime());
$oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
$sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and (oxactiveto > " . $oDb->quote($sDate) . " or oxactiveto=0) and oxactivefrom != 0 and oxactivefrom < " . $oDb->quote($sDate) . "
" . $this->_getUserGroupFilter() . "
order by oxactiveto, oxactivefrom";
$this->selectString($sQ);
}
/**
* Loads next not yet started promotions by cound
*
* @param int $iCount count to load
*/
public function loadFutureByCount($iCount)
{
$sViewName = $this->getBaseObject()->getViewName();
$sDate = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime());
$oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
$sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and (oxactiveto > " . $oDb->quote($sDate) . " or oxactiveto=0) and oxactivefrom > " . $oDb->quote($sDate) . "
" . $this->_getUserGroupFilter() . "
order by oxactiveto, oxactivefrom limit " . (int) $iCount;
$this->selectString($sQ);
}
/**
* Loads next not yet started promotions before the given timespan
*
* @param int $iTimespan timespan to load
*/
public function loadFutureByTimespan($iTimespan)
{
$sViewName = $this->getBaseObject()->getViewName();
$sDate = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime());
$sDateTo = date('Y-m-d H:i:s', \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime() + $iTimespan);
$oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
$sQ = "select * from {$sViewName} where oxtype=2 and oxactive=1 and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' and (oxactiveto > " . $oDb->quote($sDate) . " or oxactiveto=0) and oxactivefrom > " . $oDb->quote($sDate) . " and oxactivefrom < " . $oDb->quote($sDateTo) . "
" . $this->_getUserGroupFilter() . "
order by oxactiveto, oxactivefrom";
$this->selectString($sQ);
}
/**
* Returns part of user group filter query
*
* @param \OxidEsales\Eshop\Application\Model\User $oUser user object
*
* @return string
* @deprecated underscore prefix violates PSR12, will be renamed to "getUserGroupFilter" in next major
*/
protected function _getUserGroupFilter($oUser = null) // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
{
$oUser = ($oUser == null) ? $this->getUser() : $oUser;
$sTable = getViewName('oxactions');
$sGroupTable = getViewName('oxgroups');
$aIds = [];
// checking for current session user which gives additional restrictions for user itself, users group and country
if ($oUser && count($aGroupIds = $oUser->getUserGroups())) {
foreach ($aGroupIds as $oGroup) {
$aIds[] = $oGroup->getId();
}
}
$sGroupSql = count($aIds) ? "EXISTS(select oxobject2action.oxid from oxobject2action where oxobject2action.oxactionid=$sTable.OXID and oxobject2action.oxclass='oxgroups' and oxobject2action.OXOBJECTID in (" . implode(', ', \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->quoteArray($aIds)) . ") )" : '0';
return " and (
select
if(EXISTS(select 1 from oxobject2action, $sGroupTable where $sGroupTable.oxid=oxobject2action.oxobjectid and oxobject2action.oxactionid=$sTable.OXID and oxobject2action.oxclass='oxgroups' LIMIT 1),
$sGroupSql,
1)
) ";
}
/**
* return true if there are any active promotions
*
* @return boolean
*/
public function areAnyActivePromotions()
{
return (bool) $this->fetchExistsActivePromotion();
}
/**
* Fetch the information, if there is an active promotion.
*
* @return string One, if there is an active promotion.
*/
protected function fetchExistsActivePromotion()
{
$query = "select 1 from " . getViewName('oxactions') . "
where oxtypex = :oxtype and oxactive = :oxactive and oxshopid = :oxshopid
limit 1";
return \OxidEsales\Eshop\Core\DatabaseProvider::getDb()->getOne($query, [
':oxtype' => 2,
':oxactive' => 1,
':oxshopid' => \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId()
]);
}
/**
* load active shop banner list
*/
public function loadBanners()
{
$oBaseObject = $this->getBaseObject();
$oViewName = $oBaseObject->getViewName();
$sQ = "select * from {$oViewName} where oxtype=3 and " . $oBaseObject->getSqlActiveSnippet()
. " and oxshopid='" . \OxidEsales\Eshop\Core\Registry::getConfig()->getShopId() . "' " . $this->_getUserGroupFilter()
. " order by oxsort";
$this->selectString($sQ);
}
}
| michaelkeiluweit/oxideshop_ce | source/Application/Model/ActionList.php | PHP | gpl-3.0 | 7,605 |
/////////////////////////////////////////////////////////////////////////////
/// @file AbstractSection.cpp
///
/// @author Daniel Wilczak
/////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2000-2013 by the CAPD Group.
//
// This file constitutes a part of the CAPD library,
// distributed under the terms of the GNU General Public License.
// Consult http://capd.ii.uj.edu.pl/ for details.
#ifdef __HAVE_MPFR__
#include "capd/vectalg/mplib.h"
#include "capd/poincare/AbstractSection.h"
#include "capd/poincare/AbstractSection.hpp"
#include "capd/poincare/AffineSection.h"
#include "capd/poincare/CoordinateSection.h"
#include "capd/poincare/NonlinearSection.h"
using namespace capd;
template class poincare::AbstractSection<MpMatrix>;
template class poincare::AbstractSection<MpIMatrix>;
template class poincare::AffineSection<MpMatrix>;
template class poincare::AffineSection<MpIMatrix>;
template class poincare::CoordinateSection<MpMatrix>;
template class poincare::CoordinateSection<MpIMatrix>;
template class poincare::NonlinearSection<MpMatrix>;
template class poincare::NonlinearSection<MpIMatrix>;
#endif
| soonhokong/capd4 | capdDynSys4/src/mpcapd/poincare/AbstractSection.cpp | C++ | gpl-3.0 | 1,168 |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\App\Test\Unit\View\Deployment\Version\Storage;
use \Magento\Framework\App\View\Deployment\Version\Storage\File;
class FileTest extends \PHPUnit_Framework_TestCase
{
/**
* @var File
*/
private $object;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $directory;
protected function setUp()
{
$this->directory = $this->getMock('Magento\Framework\Filesystem\Directory\WriteInterface');
$filesystem = $this->getMock('Magento\Framework\Filesystem', [], [], '', false);
$filesystem
->expects($this->once())
->method('getDirectoryWrite')
->with('fixture_dir')
->will($this->returnValue($this->directory));
$this->object = new File($filesystem, 'fixture_dir', 'fixture_file.txt');
}
public function testLoad()
{
$this->directory
->expects($this->once())
->method('readFile')
->with('fixture_file.txt')
->will($this->returnValue('123'));
$this->assertEquals('123', $this->object->load());
}
/**
* @expectedException \Exception
* @expectedExceptionMessage Exception to be propagated
*/
public function testLoadExceptionPropagation()
{
$this->directory
->expects($this->once())
->method('readFile')
->with('fixture_file.txt')
->will($this->throwException(new \Exception('Exception to be propagated')));
$this->object->load();
}
/**
* @expectedException \UnexpectedValueException
* @expectedExceptionMessage Unable to retrieve deployment version of static files from the file system
*/
public function testLoadExceptionWrapping()
{
$filesystemException = new \Magento\Framework\Exception\FileSystemException(
new \Magento\Framework\Phrase('File does not exist')
);
$this->directory
->expects($this->once())
->method('readFile')
->with('fixture_file.txt')
->will($this->throwException($filesystemException));
try {
$this->object->load();
} catch (\Exception $e) {
$this->assertSame($filesystemException, $e->getPrevious(), 'Wrapping of original exception is expected');
throw $e;
}
}
public function testSave()
{
$this->directory
->expects($this->once())
->method('writeFile')
->with('fixture_file.txt', 'input_data', 'w');
$this->object->save('input_data');
}
}
| rajmahesh/magento2-master | vendor/magento/framework/App/Test/Unit/View/Deployment/Version/Storage/FileTest.php | PHP | gpl-3.0 | 2,744 |
/******************************************************************************/
/* */
/* X r d S e c g s i P r o x y . c c */
/* */
/* (c) 2005, G. Ganis / CERN */
/* */
/* This file is part of the XRootD software suite. */
/* */
/* XRootD is free software: you can redistribute it and/or modify it under */
/* the terms of the GNU Lesser General Public License as published by the */
/* Free Software Foundation, either version 3 of the License, or (at your */
/* option) any later version. */
/* */
/* XRootD is distributed in the hope that it will be useful, but WITHOUT */
/* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
/* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public */
/* License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License */
/* along with XRootD in a file called COPYING.LESSER (LGPL license) and file */
/* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */
/* */
/* The copyright holder's institutional names and contributor's names may not */
/* be used to endorse or promote products derived from this software without */
/* specific prior written permission of the institution or contributor. */
/* */
/******************************************************************************/
/* ************************************************************************** */
/* */
/* Manage GSI proxies */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <pwd.h>
#include <time.h>
#include "XrdOuc/XrdOucString.hh"
#include "XrdSys/XrdSysLogger.hh"
#include "XrdSys/XrdSysError.hh"
#include "XrdSys/XrdSysPwd.hh"
#include "XrdSut/XrdSutAux.hh"
#include "XrdCrypto/XrdCryptoAux.hh"
#include "XrdCrypto/XrdCryptoFactory.hh"
#include "XrdCrypto/XrdCryptoX509.hh"
#include "XrdCrypto/XrdCryptoX509Req.hh"
#include "XrdCrypto/XrdCryptoX509Chain.hh"
#include "XrdCrypto/XrdCryptoX509Crl.hh"
#include "XrdCrypto/XrdCryptosslgsiX509Chain.hh"
#include "XrdCrypto/XrdCryptosslgsiAux.hh"
#include "XrdSecgsi/XrdSecgsiTrace.hh"
#define PRT(x) {cerr <<x <<endl;}
//
// enum
enum kModes {
kM_undef = 0,
kM_init = 1,
kM_info,
kM_destroy,
kM_help
};
const char *gModesStr[] = {
"kM_undef",
"kM_init",
"kM_info",
"kM_destroy",
"kM_help"
};
//
// Prototypes
//
void Menu();
int ParseArguments(int argc, char **argv);
bool CheckOption(XrdOucString opt, const char *ref, int &ival);
void Display(XrdCryptoX509 *xp);
//
// Globals
//
int Mode = kM_undef;
bool Debug = 0;
bool Exists = 0;
XrdCryptoFactory *gCryptoFactory = 0;
XrdOucString CryptoMod = "ssl";
XrdOucString CAdir = "/etc/grid-security/certificates/";
XrdOucString CRLdir = "/etc/grid-security/certificates/";
XrdOucString DefEEcert = "/.globus/usercert.pem";
XrdOucString DefEEkey = "/.globus/userkey.pem";
XrdOucString DefPXcert = "/tmp/x509up_u";
XrdOucString EEcert = "";
XrdOucString EEkey = "";
XrdOucString PXcert = "";
XrdOucString Valid = "12:00";
int Bits = 512;
int PathLength = 0;
int ClockSkew = 30;
// For error logging and tracing
static XrdSysLogger Logger;
static XrdSysError eDest(0,"proxy_");
XrdOucTrace *gsiTrace = 0;
int main( int argc, char **argv )
{
// Test implemented functionality
int secValid = 0;
XrdProxyOpt_t pxopt;
XrdCryptosslgsiX509Chain *cPXp = 0;
XrdCryptoX509 *xPXp = 0, *xPXPp = 0;
XrdCryptoRSA *kPXp = 0;
XrdCryptoX509ParseFile_t ParseFile = 0;
int prc = 0;
int nci = 0;
int exitrc = 0;
// Parse arguments
if (ParseArguments(argc,argv)) {
exit(1);
}
//
// Initiate error logging and tracing
eDest.logger(&Logger);
if (!gsiTrace)
gsiTrace = new XrdOucTrace(&eDest);
if (gsiTrace) {
if (Debug)
// Medium level
gsiTrace->What |= (TRACE_Authen | TRACE_Debug);
}
//
// Set debug flags in other modules
if (Debug) {
XrdSutSetTrace(sutTRACE_Debug);
XrdCryptoSetTrace(cryptoTRACE_Debug);
}
//
// Load the crypto factory
if (!(gCryptoFactory = XrdCryptoFactory::GetCryptoFactory(CryptoMod.c_str()))) {
PRT(": cannot instantiate factory "<<CryptoMod);
exit(1);
}
if (Debug)
gCryptoFactory->SetTrace(cryptoTRACE_Debug);
//
// Depending on the mode
switch (Mode) {
case kM_help:
//
// We should not get here ... print the menu and go
Menu();
break;
case kM_init:
//
// Init proxies
secValid = XrdSutParseTime(Valid.c_str(), 1);
pxopt.bits = Bits;
pxopt.valid = secValid;
pxopt.depthlen = PathLength;
cPXp = new XrdCryptosslgsiX509Chain();
prc = XrdSslgsiX509CreateProxy(EEcert.c_str(), EEkey.c_str(), &pxopt,
cPXp, &kPXp, PXcert.c_str());
if (prc == 0) {
// The proxy is the first certificate
xPXp = cPXp->Begin();
if (xPXp) {
Display(xPXp);
} else {
PRT( ": proxy certificate not found");
}
} else {
PRT( ": problems creating proxy");
}
break;
case kM_destroy:
//
// Destroy existing proxies
if (unlink(PXcert.c_str()) == -1) {
perror("xrdgsiproxy");
}
break;
case kM_info:
//
// Display info about existing proxies
if (!(ParseFile = gCryptoFactory->X509ParseFile())) {
PRT("cannot attach to ParseFile function!");
break;
}
// Parse the proxy file
cPXp = new XrdCryptosslgsiX509Chain();
nci = (*ParseFile)(PXcert.c_str(), cPXp);
if (nci < 2) {
if (Exists) {
exitrc = 1;
} else {
PRT("proxy files must have at least two certificates"
" (found only: "<<nci<<")");
}
break;
}
// The proxy is the first certificate
xPXp = cPXp->Begin();
if (xPXp) {
if (!Exists) {
Display(xPXp);
if (strstr(xPXp->Subject(), "CN=limited proxy")) {
xPXPp = cPXp->SearchBySubject(xPXp->Issuer());
if (xPXPp) {
Display(xPXPp);
} else {
PRT("WARNING: found 'limited proxy' but not the associated proxy!");
}
}
} else {
// Check time validity
secValid = XrdSutParseTime(Valid.c_str(), 1);
int tl = xPXp->NotAfter() -(int)time(0);
if (Debug)
PRT("secValid: " << secValid<< ", tl: "<<tl<<", ClockSkew:"<<ClockSkew);
if (secValid > tl + ClockSkew) {
exitrc = 1;
break;
}
// Check bit strenght
if (Debug)
PRT("BitStrength: " << xPXp->BitStrength()<< ", Bits: "<<Bits);
if (xPXp->BitStrength() < Bits) {
exitrc = 1;
break;
}
}
} else {
if (Exists) {
exitrc = 1;
} else {
PRT( ": proxy certificate not found");
}
}
break;
default:
//
// Print menu
Menu();
}
exit(exitrc);
}
int ParseArguments(int argc, char **argv)
{
// Parse application arguments filling relevant global variables
// Number of arguments
if (argc < 0 || !argv[0]) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Insufficient number or arguments! +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
// Print main menu
Menu();
return 1;
}
--argc;
++argv;
//
// Loop over arguments
while ((argc >= 0) && (*argv)) {
XrdOucString opt = "";
int ival = -1;
if(*(argv)[0] == '-') {
opt = *argv;
opt.erase(0,1);
if (CheckOption(opt,"h",ival) || CheckOption(opt,"help",ival) ||
CheckOption(opt,"menu",ival)) {
Mode = kM_help;
} else if (CheckOption(opt,"debug",ival)) {
Debug = ival;
} else if (CheckOption(opt,"e",ival)) {
Exists = 1;
} else if (CheckOption(opt,"exists",ival)) {
Exists = 1;
} else if (CheckOption(opt,"f",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
PXcert = *argv;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-f' requires a proxy file name: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"file",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
PXcert = *argv;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-file' requires a proxy file name: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"out",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
PXcert = *argv;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-out' requires a proxy file name: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"cert",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
EEcert = *argv;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-cert' requires a cert file name: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"key",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
EEkey = *argv;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-key' requires a key file name: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"certdir",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
CAdir = *argv;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-certdir' requires a dir path: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"valid",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
Valid = *argv;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-valid' requires a time string: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"path-length",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
PathLength = strtol(*argv,0,10);
if (PathLength < -1 || errno == ERANGE) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-path-length' requires a number >= -1: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-path-length' requires a number >= -1: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"bits",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
Bits = strtol(*argv, 0, 10);
Bits = (Bits > 512) ? Bits : 512;
if (errno == ERANGE) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-bits' requires a number: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-bits' requires a number: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else if (CheckOption(opt,"clockskew",ival)) {
--argc;
++argv;
if (argc >= 0 && (*argv && *(argv)[0] != '-')) {
ClockSkew = strtol(*argv, 0, 10);
if (ClockSkew < -1 || errno == ERANGE) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-clockskew' requires a number >= -1: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Option '-clockskew' requires a number >= -1: ignoring +");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
argc++;
argv--;
}
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Ignoring unrecognized option: "<<*argv);
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
} else {
//
// Mode keyword
opt = *argv;
if (CheckOption(opt,"init",ival)) {
Mode = kM_init;
} else if (CheckOption(opt,"info",ival)) {
Mode = kM_info;
} else if (CheckOption(opt,"destroy",ival)) {
Mode = kM_destroy;
} else if (CheckOption(opt,"help",ival)) {
Mode = kM_help;
} else {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Ignoring unrecognized keyword mode: "<<opt.c_str());
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
}
--argc;
++argv;
}
//
// Default mode 'info'
Mode = (Mode == 0) ? kM_info : Mode;
//
// If help mode, print menu and exit
if (Mode == kM_help) {
// Print main menu
Menu();
return 1;
}
//
// we may need later
struct passwd *pw = 0;
XrdSysPwd thePwd;
//
// Check proxy file
if (PXcert.length() <= 0) {
// Use defaults
if (!pw && !(pw = thePwd.Get(getuid()))) {
// Cannot get info about current user
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot get info about current user - exit ");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
// Build proxy file name
PXcert = DefPXcert + (int)(pw->pw_uid);
}
//
// Expand Path
XrdSutExpand(PXcert);
// Get info
struct stat st;
if (stat(PXcert.c_str(),&st) != 0) {
if (errno != ENOENT) {
// Path exists but we cannot access it - exit
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot access requested proxy file: "<<PXcert.c_str());
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
} else {
if (Mode != kM_init) {
// Path exists but we cannot access it - exit
if (!Exists) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ proxy file: "<<PXcert.c_str()<<" not found");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
return 1;
}
}
}
//
// The following applies in 'init' mode only
if (Mode == kM_init) {
//
// Check certificate file
if (EEcert.length()) {
//
// Expand Path
XrdSutExpand(EEcert);
// Get info
if (stat(EEcert.c_str(),&st) != 0) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot access certificate file: "<<EEcert.c_str());
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
} else {
// Use defaults
if (!pw && !(pw = thePwd.Get(getuid()))) {
// Cannot get info about current user
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot get info about current user - exit ");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
EEcert = DefEEcert;
EEcert.insert(XrdSutHome(), 0);
if (stat(EEcert.c_str(),&st) != 0) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot access certificate file: "<<EEcert.c_str());
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
}
//
// Check key file
if (EEkey.length()) {
//
// Expand Path
XrdSutExpand(EEkey);
// Get info
if (stat(EEkey.c_str(),&st) != 0) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot access private key file: "<<EEkey.c_str());
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
} else {
// Use defaults
if (!pw && !(pw = thePwd.Get(getuid()))) {
// Cannot get info about current user
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot get info about current user - exit ");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
EEkey = DefEEkey;
EEkey.insert(XrdSutHome(), 0);
if (stat(EEkey.c_str(),&st) != 0) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Cannot access private key file: "<<EEkey.c_str());
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
}
// Check permissions
if (!S_ISREG(st.st_mode) || S_ISDIR(st.st_mode) ||
(st.st_mode & (S_IWGRP | S_IWOTH)) != 0 ||
(st.st_mode & (S_IRGRP | S_IROTH)) != 0) {
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
PRT("+ Wrong permissions for file: "<<EEkey.c_str()<< " (should be 0600)");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
return 1;
}
}
return 0;
}
void Menu()
{
// Print the menu
PRT(" ");
PRT(" xrdgsiproxy: application to manage GSI proxies ");
PRT(" ");
PRT(" Syntax:");
PRT(" ");
PRT(" xrdgsiproxy [-h] [<mode>] [options] ");
PRT(" ");
PRT(" ");
PRT(" -h display this menu");
PRT(" ");
PRT(" mode (info, init, destroy) [info]");
PRT(" ");
PRT(" info: display content of existing proxy file");
PRT(" ");
PRT(" init: create proxy certificate and related proxy file");
PRT(" ");
PRT(" destroy: delete existing proxy file");
PRT(" ");
PRT(" options:");
PRT(" ");
PRT(" -debug Print more information while running this"
" query (use if something goes wrong) ");
PRT(" ");
PRT(" -f,-file,-out <file> Non-standard location of proxy file");
PRT(" ");
PRT(" init mode only:");
PRT(" ");
PRT(" -certdir <dir> Non-standard location of directory"
" with information about known CAs");
PRT(" -cert <file> Non-standard location of certificate"
" for which proxies are wanted");
PRT(" -key <file> Non-standard location of the private"
" key to be used to sign the proxy");
PRT(" -bits <bits> strength in bits of the key [512]");
PRT(" -valid <hh:mm> Time validity of the proxy certificate [12:00]");
PRT(" -path-length <len> max number of descendent levels below"
" this proxy [0] ");
PRT(" -e,-exists [options] returns 0 if valid proxy exists, 1 otherwise;");
PRT(" valid options: '-valid <hh:mm>', -bits <bits>");
PRT(" -clockskew <secs> max clock-skewness allowed when checking time validity [30 secs]");
PRT(" ");
}
bool CheckOption(XrdOucString opt, const char *ref, int &ival)
{
// Check opt against ref
// Return 1 if ok, 0 if not
// Fills ival = 1 if match is exact
// ival = 0 if match is exact with no<ref>
// ival = -1 in the other cases
bool rc = 0;
int lref = (ref) ? strlen(ref) : 0;
if (!lref)
return rc;
XrdOucString noref = ref;
noref.insert("no",0);
ival = -1;
if (opt == ref) {
ival = 1;
rc = 1;
} else if (opt == noref) {
ival = 0;
rc = 1;
}
return rc;
}
void Display(XrdCryptoX509 *xp)
{
// display content of proxy certificate
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
if (!xp) {
PRT(" Empty certificate! ");
return;
}
// File
PRT("file : "<<PXcert);
// Issuer
PRT("issuer : "<<xp->Issuer());
// Subject
PRT("subject : "<<xp->Subject());
// Path length field
int pathlen = 0;
XrdSslgsiProxyCertInfo(xp->GetExtension(gsiProxyCertInfo_OID), pathlen);
PRT("path length : "<<pathlen);
// Key strength
PRT("bits : "<<xp->BitStrength());
// Time left
int now = int(time(0)) - XrdCryptoTZCorr();
int tl = xp->NotAfter() - now;
int hh = (tl >= 3600) ? (tl/3600) : 0; tl -= (hh*3600);
int mm = (tl >= 60) ? (tl/60) : 0; tl -= (mm*60);
int ss = (tl >= 0) ? tl : 0;
PRT("time left : "<<hh<<"h:"<<mm<<"m:"<<ss<<"s");
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
// Show VOMS attributes, if any
XrdOucString vatts, vat;
if (XrdSslgsiX509GetVOMSAttr(xp, vatts) == 0) {
int from = 0;
while ((from = vatts.tokenize(vat, from, ',')) != -1) {
if (vat.length() > 0) PRT("VOMS attributes: "<<vat);
}
PRT("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
}
| ffurano/xrootd-xrdhttp | src/XrdSecgsi/XrdSecgsiProxy.cc | C++ | gpl-3.0 | 25,410 |
/*
lcdui - A simple framework for embedded systems with an LCD/button interface
Copyright (C) 2012 by Al Williams (al.williams@awce.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 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/>.
*/
#include "lcdui.h"
using namespace std;
namespace liblcdui
{
// This kicks off a menu (or a submenu)
// if level is zero (default) you can't go back from here
void lcdui::go(unsigned int level)
{
// This mode is 0 for normal, 1 for changing a number, and
// 2 for changing an enumeration
int mode=0;
while (1)
{
// skip anything disabled
while (menu[current].mstring && !menu[current].enabled) current++;
// if at the end back up
if (menu[current].mstring==NULL)
do
{
current--;
} while (current && !menu[current].enabled);
// now current is correct
// get string
#ifndef NOSTRING
string work=menu[current].mstring;
ostringstream digits;
#else
char work[81];
#endif
// modify based on type
switch (menu[current].menutype)
{
case T_INT: // add number
#ifndef NOSTRING
work+="\t";
digits<<*menu[current].value;
work+=digits.str();
#else
// assume 8 bit char
work[0]='\t';
itoa(*menu[current].value,work+1,10);
#endif
break;
case T_ENUM: // add enumerated value
#ifndef NOSTRING
work+="\t";
work+=+menu[current].enumeration[*menu[current].value].name;
#else
work[0]='\t';
strcpy(work+1,menu[current].enumeration[*menu[current].value].name);
#endif
break;
}
// write it
output(work);
// get input
INTYPE in;
do
{
in=getInput();
if (in==IN_NONE) idle(); // call idle if nothing
} while (in==IN_NONE);
// See what to do
switch (in)
{
case IN_UP: // Up arrow
if (mode==1) // if modifying #
{
if (((*menu[current].value)-menu[current].step)<menu[current].min) break;
(*menu[current].value)-=menu[current].step;
callback(menu[current].id,menu[current].menutype,EV_CHANGE,menu[current].value);
break;
}
if (mode==2) // if modifying an enum
{
if (*menu[current].value==0) break;
(*menu[current].value)--;
callback(menu[current].id,menu[current].menutype,EV_CHANGE, menu[current].value);
break;
}
// none of the above, just navigating the menu
if (current) current--;
break;
case IN_DN: // down arrow
if (mode==1) // change number
{
if (((*menu[current].value)+menu[current].step)>menu[current].max) break;
(*menu[current].value)+=menu[current].step;
callback(menu[current].id,menu[current].menutype,EV_CHANGE,menu[current].value);
break;
}
if (mode==2) // change enum
{
(*menu[current].value)++;
if (menu[current].enumeration[*menu[current].value].name==NULL)
(*menu[current].value)--;
callback(menu[current].id,menu[current].menutype,EV_CHANGE,menu[current].value);
break;
}
// none of the above, navigate the menu
current++;
break;
// Select key either executes menu,
// modifies int or enum
// or finishes modification
case IN_OK:
if (mode) // changing a value so exit change
{
mode=0;
// note we have no way to roll back with the current
// scheme; changes are "hot" unless you override callback
callback(menu[current].id,menu[current].menutype,EV_SAVE,menu[current].value);
break;
}
// Do a submenu
if (menu[current].menutype==T_MENU)
{
// remember where we are
MENU *parent=menu;
unsigned parentcur=current;
// go to new menu
menu=menu[current].submenu;
current=0;
callback(menu[current].id,menu[current].menutype,EV_ACTION,menu[current].value);
go(level+1);
// back, so restore
current=parentcur;
menu=parent;
break;
}
// integer and not read only
if (menu[current].menutype==T_INT && !menu[current].readonly)
{
callback(menu[current].id,menu[current].menutype,EV_EDIT,menu[current].value);
mode=1; // start edit
break;
}
// enum and not read only
if (menu[current].menutype==T_ENUM && !menu[current].readonly)
{
callback(menu[current].id,menu[current].menutype,EV_EDIT,menu[current].value);
mode=2; // start edit
break;
}
// none of the above, so must be T_ACTION
callback(menu[current].id,menu[current].menutype,EV_ACTION,menu[current].value);
break;
// back button gets out of a menu;
case IN_BACK:
if (mode)
{
mode=0; // stop editing
callback(menu[current].id,menu[current].menutype,EV_CANCEL,menu[current].value);
break; // don't leave submenu if editing
}
// note could save edited value and restore here
// or edit a local copy and only save on ok
if (level) return; // only return if nested
break;
}
}
}
void lcdui::callback(int id, MENUTYPE mtype, EVTYPE event, int *value)
{
switch (mtype)
{
case T_ACTION:
dispatch(id);
break;
// A custom override could get notified when anything changes here
case T_INT:
case T_ENUM:
case T_MENU:
break;
}
}
}
| thespeeder/lcdui | lcdui.cpp | C++ | gpl-3.0 | 5,873 |
######################################################################
# Copyright (C) 2014 Jaakko Luttinen
#
# This file is licensed under Version 3.0 of the GNU General Public
# License. See LICENSE for a text of the license.
######################################################################
######################################################################
# This file is part of BayesPy.
#
# BayesPy is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# BayesPy 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 BayesPy. If not, see <http://www.gnu.org/licenses/>.
######################################################################
"""
Module for the Gaussian-Wishart and similar distributions.
"""
import numpy as np
from scipy import special
from .expfamily import (ExponentialFamily,
ExponentialFamilyDistribution,
useconstructor)
from .gaussian import GaussianMoments
from .gamma import GammaMoments
from .wishart import (WishartMoments,
WishartPriorMoments)
from .node import (Moments,
ensureparents)
from bayespy.utils import random
from bayespy.utils import utils
class GaussianGammaISOMoments(Moments):
"""
Class for the moments of Gaussian-gamma-ISO variables.
"""
def compute_fixed_moments(self, x, alpha):
"""
Compute the moments for a fixed value
`x` is a mean vector.
`alpha` is a precision scale
"""
x = np.asanyarray(x)
alpha = np.asanyarray(alpha)
u0 = np.einsum('...,...i->...i', alpha, x)
u1 = np.einsum('...,...i,...j->...ij', alpha, x, x)
u2 = np.copy(alpha)
u3 = np.log(alpha)
u = [u0, u1, u2, u3]
return u
def compute_dims_from_values(self, x, alpha):
"""
Return the shape of the moments for a fixed value.
"""
if np.ndim(x) < 1:
raise ValueError("Mean must be a vector")
D = np.shape(x)[-1]
return ( (D,), (D,D), (), () )
class GaussianGammaARDMoments(Moments):
"""
Class for the moments of Gaussian-gamma-ARD variables.
"""
def compute_fixed_moments(self, x, alpha):
"""
Compute the moments for a fixed value
`x` is a mean vector.
`alpha` is a precision scale
"""
x = np.asanyarray(x)
alpha = np.asanyarray(alpha)
if np.ndim(x) < 1:
raise ValueError("Mean must be a vector")
if np.ndim(alpha) < 1:
raise ValueError("ARD scales must be a vector")
if np.shape(x)[-1] != np.shape(alpha)[-1]:
raise ValueError("Mean and ARD scales have inconsistent shapes")
u0 = np.einsum('...i,...i->...i', alpha, x)
u1 = np.einsum('...k,...k,...k->...k', alpha, x, x)
u2 = np.copy(alpha)
u3 = np.log(alpha)
u = [u0, u1, u2, u3]
return u
def compute_dims_from_values(self, x, alpha):
"""
Return the shape of the moments for a fixed value.
"""
if np.ndim(x) < 1:
raise ValueError("Mean must be a vector")
if np.ndim(alpha) < 1:
raise ValueError("ARD scales must be a vector")
D = np.shape(x)[-1]
if np.shape(alpha)[-1] != D:
raise ValueError("Mean and ARD scales have inconsistent shapes")
return ( (D,), (D,), (D,), (D,) )
class GaussianWishartMoments(Moments):
"""
Class for the moments of Gaussian-Wishart variables.
"""
def compute_fixed_moments(self, x, Lambda):
"""
Compute the moments for a fixed value
`x` is a vector.
`Lambda` is a precision matrix
"""
x = np.asanyarray(x)
Lambda = np.asanyarray(Lambda)
u0 = np.einsum('...ik,...k->...i', Lambda, x)
u1 = np.einsum('...i,...ij,...j->...', x, Lambda, x)
u2 = np.copy(Lambda)
u3 = linalg.logdet_cov(Lambda)
return [u0, u1, u2, u3]
def compute_dims_from_values(self, x, Lambda):
"""
Return the shape of the moments for a fixed value.
"""
if np.ndim(x) < 1:
raise ValueError("Mean must be a vector")
if np.ndim(Lambda) < 2:
raise ValueError("Precision must be a matrix")
D = np.shape(x)[-1]
if np.shape(Lambda)[-2:] != (D,D):
raise ValueError("Mean vector and precision matrix have "
"inconsistent shapes")
return ( (D,), (), (D,D), () )
class GaussianGammaISODistribution(ExponentialFamilyDistribution):
"""
Class for the VMP formulas of Gaussian-Gamma-ISO variables.
"""
def compute_message_to_parent(self, parent, index, u, u_mu_Lambda, u_a, u_b):
"""
Compute the message to a parent node.
"""
if index == 0:
raise NotImplementedError()
elif index == 1:
raise NotImplementedError()
elif index == 2:
raise NotImplementedError()
else:
raise ValueError("Index out of bounds")
def compute_phi_from_parents(self, u_mu_Lambda, u_a, u_b, mask=True):
"""
Compute the natural parameter vector given parent moments.
"""
raise NotImplementedError()
def compute_moments_and_cgf(self, phi, mask=True):
"""
Compute the moments and :math:`g(\phi)`.
"""
raise NotImplementedError()
return (u, g)
def compute_cgf_from_parents(self, u_mu_Lambda, u_a, u_b):
"""
Compute :math:`\mathrm{E}_{q(p)}[g(p)]`
"""
raise NotImplementedError()
return g
def compute_fixed_moments_and_f(self, x, alpha, mask=True):
"""
Compute the moments and :math:`f(x)` for a fixed value.
"""
raise NotImplementedError()
return (u, f)
class GaussianWishartDistribution(ExponentialFamilyDistribution):
"""
Class for the VMP formulas of Gaussian-Wishart variables.
"""
def compute_message_to_parent(self, parent, index, u, u_mu, u_alpha, u_V, u_n):
"""
Compute the message to a parent node.
"""
if index == 0:
raise NotImplementedError()
elif index == 1:
raise NotImplementedError()
elif index == 2:
raise NotImplementedError()
elif index == 3:
raise NotImplementedError()
else:
raise ValueError("Index out of bounds")
def compute_phi_from_parents(self, u_mu, u_alpha, u_V, u_n, mask=True):
"""
Compute the natural parameter vector given parent moments.
"""
raise NotImplementedError()
def compute_moments_and_cgf(self, phi, mask=True):
"""
Compute the moments and :math:`g(\phi)`.
"""
raise NotImplementedError()
return (u, g)
def compute_cgf_from_parents(self, u_mu, u_alpha, u_V, u_n):
"""
Compute :math:`\mathrm{E}_{q(p)}[g(p)]`
"""
raise NotImplementedError()
return g
def compute_fixed_moments_and_f(self, x, Lambda, mask=True):
"""
Compute the moments and :math:`f(x)` for a fixed value.
"""
raise NotImplementedError()
return (u, f)
class GaussianWishart(ExponentialFamily):
"""
Node for Gaussian-Wishart random variables.
The prior:
.. math::
p(x, \Lambda| \mu, \alpha, V, n)
p(x|\Lambda, \mu, \alpha) = \mathcal(N)(x | \mu, \alpha^{-1} Lambda^{-1})
p(\Lambda|V, n) = \mathcal(W)(\Lambda | n, V)
The posterior approximation :math:`q(x, \Lambda)` has the same Gaussian-Wishart form.
"""
_moments = GaussianWishartMoments()
_parent_moments = (GaussianGammaMoments(),
GammaMoments(),
WishartMoments(),
WishartPriorMoments())
_distribution = GaussianWishartDistribution()
@classmethod
@ensureparents
def _constructor(cls, mu, alpha, V, n, plates_lambda=None, plates_x=None, **kwargs):
"""
Constructs distribution and moments objects.
This method is called if useconstructor decorator is used for __init__.
`mu` is the mean/location vector
`alpha` is the scale
`V` is the scale matrix
`n` is the degrees of freedom
"""
D = mu.dims[0][0]
# Check shapes
if mu.dims != ( (D,), (D,D), (), () ):
raise ValueError("Mean vector has wrong shape")
if alpha.dims != ( (), () ):
raise ValueError("Scale has wrong shape")
if V.dims != ( (D,D), () ):
raise ValueError("Precision matrix has wrong shape")
if n.dims != ( (), () ):
raise ValueError("Degrees of freedom has wrong shape")
dims = ( (D,), (), (D,D), () )
return (dims,
kwargs,
cls._total_plates(kwargs.get('plates'),
cls._distribution.plates_from_parent(0, mu.plates),
cls._distribution.plates_from_parent(1, alpha.plates),
cls._distribution.plates_from_parent(2, V.plates),
cls._distribution.plates_from_parent(3, n.plates)),
cls._distribution,
cls._moments,
cls._parent_moments)
def random(self):
"""
Draw a random sample from the distribution.
"""
raise NotImplementedError()
def show(self):
"""
Print the distribution using standard parameterization.
"""
raise NotImplementedError()
| nipunreddevil/bayespy | bayespy/inference/vmp/nodes/gaussian_wishart.py | Python | gpl-3.0 | 10,240 |
using System;
using Server.Items;
namespace Server.Items
{
public class DecorativePlateKabuto : BaseArmor
{
public override int BasePhysicalResistance { get { return 6; } }
public override int BaseFireResistance { get { return 2; } }
public override int BaseColdResistance { get { return 2; } }
public override int BasePoisonResistance { get { return 2; } }
public override int BaseEnergyResistance { get { return 3; } }
public override int InitMinHits { get { return 55; } }
public override int InitMaxHits { get { return 75; } }
public override int StrengthReq { get { return 70; } }
public override ArmorMaterialType MaterialType { get { return ArmorMaterialType.Plate; } }
[Constructable]
public DecorativePlateKabuto()
: base( 0x2778 )
{
Weight = 6.0;
}
public DecorativePlateKabuto( Serial serial )
: base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
/*int version = */
reader.ReadInt();
}
}
} | greeduomacro/xrunuo | Scripts/Distro/Items/Armor/Plate/DecorativePlateKabuto.cs | C# | gpl-3.0 | 1,204 |
<?php
/* Copyright (C) 2012 Regis Houssin <regis.houssin@capnetworks.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 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/>.
*/
$contracts = array(
'CHARSET' => 'UTF-8',
'ContractsArea' => 'Kontrakter område',
'ListOfContracts' => 'Liste over kontrakter',
'LastContracts' => 'Seneste %s modificerede kontrakter',
'AllContracts' => 'Alle kontrakter',
'ContractCard' => 'Kontrakt-kortet',
'ContractStatus' => 'Kontrakt status',
'ContractStatusNotRunning' => 'Ikke kører',
'ContractStatusRunning' => 'Kørsel',
'ContractStatusDraft' => 'Udkast',
'ContractStatusValidated' => 'Valideret',
'ContractStatusClosed' => 'Lukket',
'ServiceStatusInitial' => 'Ikke kører',
'ServiceStatusRunning' => 'Kørsel',
'ServiceStatusNotLate' => 'Kører, ikke er udløbet',
'ServiceStatusNotLateShort' => 'Ikke er udløbet',
'ServiceStatusLate' => 'Kører, er udløbet',
'ServiceStatusLateShort' => 'Udløbet',
'ServiceStatusClosed' => 'Lukket',
'ServicesLegend' => 'Services legend',
'Contracts' => 'Kontrakter',
'Contract' => 'Kontrakt',
'NoContracts' => 'Nr. kontrakter',
'MenuServices' => 'Services',
'MenuInactiveServices' => 'Tjenester, der ikke er aktive',
'MenuRunningServices' => 'Kørsel tjenester',
'MenuExpiredServices' => 'Udløbet tjenester',
'MenuClosedServices' => 'Lukket tjenester',
'NewContract' => 'Ny kontrakt',
'AddContract' => 'Tilføj kontrakt',
'SearchAContract' => 'Søg en kontrakt',
'DeleteAContract' => 'Slet en kontrakt',
'CloseAContract' => 'Luk en kontrakt',
'ConfirmDeleteAContract' => 'Er du sikker på du vil slette denne kontrakt og alle dets tjenester?',
'ConfirmValidateContract' => 'Er du sikker på at du ønsker at validere denne kontrakt?',
'ConfirmCloseContract' => 'Dette vil lukke alle tjenester (aktiv eller ej). Er du sikker på du ønsker at lukke denne kontrakt?',
'ConfirmCloseService' => 'Er du sikker på du ønsker at lukke denne service med <b>dato %s?</b>',
'ValidateAContract' => 'Validere en kontrakt',
'ActivateService' => 'Aktivér service',
'ConfirmActivateService' => 'Er du sikker på du vil aktivere denne tjeneste med datoen <b>for %s?</b>',
'RefContract' => 'Contract reference',
'DateContract' => 'Kontrakt dato',
'DateServiceActivate' => 'Forkyndelsesdato aktivering',
'DateServiceUnactivate' => 'Forkyndelsesdato unactivation',
'DateServiceStart' => 'Dato for starten af service',
'DateServiceEnd' => 'Datoen for afslutningen af tjenesten',
'ShowContract' => 'Vis kontrakt',
'ListOfServices' => 'Liste over tjenesteydelser',
'ListOfInactiveServices' => 'Liste over ikke aktive tjenester',
'ListOfExpiredServices' => 'Liste over udløb aktive tjenester',
'ListOfClosedServices' => 'Liste over lukkede tjenester',
'ListOfRunningContractsLines' => 'Liste over kører kontrakt linjer',
'ListOfRunningServices' => 'Liste over kører tjenester',
'NotActivatedServices' => 'Ikke aktiverede tjenester (blandt valideret kontrakter)',
'BoardNotActivatedServices' => 'Tjenester for at aktivere blandt valideret kontrakter',
'LastContracts' => 'Seneste %s modificerede kontrakter',
'LastActivatedServices' => 'Seneste %s aktiveret tjenester',
'LastModifiedServices' => 'Seneste %s modificerede tjenester',
'EditServiceLine' => 'Rediger service line',
'ContractStartDate' => 'Startdato',
'ContractEndDate' => 'Slutdato',
'DateStartPlanned' => 'Planlagt startdato',
'DateStartPlannedShort' => 'Planlagt startdato',
'DateEndPlanned' => 'Planlagte slutdato',
'DateEndPlannedShort' => 'Planlagte slutdato',
'DateStartReal' => 'Real startdato',
'DateStartRealShort' => 'Real startdato',
'DateEndReal' => 'Real slutdato',
'DateEndRealShort' => 'Real slutdato',
'NbOfServices' => 'Nb af tjenesteydelser',
'CloseService' => 'Luk service',
'ServicesNomberShort' => '%s tjeneste (r)',
'RunningServices' => 'Kørsel tjenester',
'BoardRunningServices' => 'Udløbet kører tjenester',
'ServiceStatus' => 'Status for service',
'DraftContracts' => 'Drafts kontrakter',
'CloseRefusedBecauseOneServiceActive' => 'Kontrakten ikke kan lukkes, da der er mindst en åben tjeneste på det',
'CloseAllContracts' => 'Luk alle kontrakter',
'DeleteContractLine' => 'Slet en kontrakt linje',
'ConfirmDeleteContractLine' => 'Er du sikker på du vil slette denne kontrakt linje?',
'MoveToAnotherContract' => 'Flyt tjeneste i en anden kontrakt.',
'ConfirmMoveToAnotherContract' => 'Jeg choosed nyt mål kontrakt og bekræfte, jeg ønsker at flytte denne tjeneste i denne kontrakt.',
'ConfirmMoveToAnotherContractQuestion' => 'Vælg, hvor eksisterende kontrakt (af samme tredjemand), du ønsker at flytte denne service?',
'PaymentRenewContractId' => 'Forny kontrakten linje (antal %s)',
'ExpiredSince' => 'Udløbsdatoen',
'RelatedContracts' => 'Relaterede kontrakter',
'NoExpiredServices' => 'Ingen udløbne aktive tjenester',
////////// Types de contacts //////////
'TypeContact_contrat_internal_SALESREPSIGN' => 'Salg repræsentant, der underskriver kontrakt',
'TypeContact_contrat_internal_SALESREPFOLL' => 'Salg repræsentant opfølgning kontrakt',
'TypeContact_contrat_external_BILLING' => 'Faktureringsindstillinger kunde kontakt',
'TypeContact_contrat_external_CUSTOMER' => 'Opfølgning kunde kontakt',
'TypeContact_contrat_external_SALESREPSIGN' => 'Undertegnelse kontrakt kunde kontakt',
'Error_CONTRACT_ADDON_NotDefined' => 'Konstant CONTRACT_ADDON ikke defineret'
);
?> | woakes070048/crm-php | htdocs/langs/da_DK/contracts.lang.php | PHP | gpl-3.0 | 6,072 |
package bb
import "github.com/Syfaro/telegram-bot-api"
type message struct {
Err error
bot *tgbotapi.BotAPI
config tgbotapi.MessageConfig
Ret tgbotapi.Message
}
func (b *Base) NewMessage(chatID int, text string) *message {
return &message{
bot: b.Bot,
config: tgbotapi.NewMessage(chatID, text),
}
}
func (m *message) DisableWebPagePreview() *message {
m.config.DisableWebPagePreview = true
return m
}
func (m *message) MarkdownMode() *message {
m.config.ParseMode = tgbotapi.ModeMarkdown
return m
}
func (m *message) ReplyToMessageID(ID int) *message {
m.config.ReplyToMessageID = ID
return m
}
func (m *message) ReplyMarkup(markup interface{}) *message {
m.config.ReplyMarkup = markup
return m
}
func (m *message) Send() *message {
msg, err := m.bot.SendMessage(m.config)
m.Ret = msg
m.Err = err
return m
}
type forward struct {
Err error
bot *tgbotapi.BotAPI
config tgbotapi.ForwardConfig
Ret tgbotapi.Message
}
func (b *Base) NewForward(chatID, fromChatID, messageID int) *forward {
return &forward{
bot: b.Bot,
config: tgbotapi.NewForward(chatID, fromChatID, messageID),
}
}
func (f *forward) Send() *forward {
msg, err := f.bot.ForwardMessage(f.config)
f.Ret = msg
f.Err = err
return f
}
| jqs7/telegram-chinese-groups | vendor/github.com/jqs7/bb/message.go | GO | gpl-3.0 | 1,264 |
#
# This file is part of Checkbox.
#
# Copyright 2008 Canonical Ltd.
#
# Checkbox 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.
#
# Checkbox 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 Checkbox. If not, see <http://www.gnu.org/licenses/>.
#
import os
import hashlib
import shutil
from stat import ST_MODE, S_IMODE, S_ISFIFO
def safe_change_mode(path, mode):
if not os.path.exists(path):
raise Exception("Path does not exist: %s" % path)
old_mode = os.stat(path)[ST_MODE]
if mode != S_IMODE(old_mode):
os.chmod(path, mode)
def safe_make_directory(path, mode=0o755):
if os.path.exists(path):
if not os.path.isdir(path):
raise Exception("Path is not a directory: %s" % path)
else:
os.makedirs(path, mode)
def safe_make_fifo(path, mode=0o666):
if os.path.exists(path):
mode = os.stat(path)[ST_MODE]
if not S_ISFIFO(mode):
raise Exception("Path is not a FIFO: %s" % path)
else:
os.mkfifo(path, mode)
def safe_remove_directory(path):
if os.path.exists(path):
if not os.path.isdir(path):
raise Exception("Path is not a directory: %s" % path)
shutil.rmtree(path)
def safe_remove_file(path):
if os.path.exists(path):
if not os.path.isfile(path):
raise Exception("Path is not a file: %s" % path)
os.remove(path)
def safe_rename(old, new):
if old != new:
if not os.path.exists(old):
raise Exception("Old path does not exist: %s" % old)
if os.path.exists(new):
raise Exception("New path exists already: %s" % new)
os.rename(old, new)
class safe_md5sum:
def __init__(self):
self.digest = hashlib.md5()
self.hexdigest = self.digest.hexdigest
def update(self, string):
self.digest.update(string.encode("utf-8"))
def safe_md5sum_file(name):
md5sum = None
if os.path.exists(name):
file = open(name)
digest = safe_md5sum()
while 1:
buf = file.read(4096)
if buf == "":
break
digest.update(buf)
file.close()
md5sum = digest.hexdigest()
return md5sum
def safe_close(file, safe=True):
if safe:
file.flush()
os.fsync(file.fileno())
file.close()
| jds2001/ocp-checkbox | checkbox/lib/safe.py | Python | gpl-3.0 | 2,778 |
require 'working_class/version'
require 'working_class/parser'
require 'working_class/task'
require 'working_class/tasklist'
# WorkingClass Module
#
module WorkingClass
# Loads the file from the path and returns a Tasklist
#
# @param path [String] the filepath
# @return [WorkingClass::Tasklist] the parsed Tasklist
#
def self.load_file(path)
string = File.open(path, 'r').read()
self.load(string)
end
# Parses the given string and returns a Tasklist
#
# @param string [String] the WorkingClass tasklist syntax string
# @return [WorkingClass::Tasklist] the parsed Tasklist
#
def self.load(string)
Parser.new(string).to_tasklist
end
end
| TimKaechele/Working-Class | lib/working_class.rb | Ruby | gpl-3.0 | 680 |
/*
* Copyright 2012 OSBI Ltd
*
* 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.
*/
var account = 'UA-16172251-17';
if (window.location.hostname && window.location.hostname == "dev.analytical-labs.com" ) {
account = 'UA-16172251-12';
} else if (window.location.hostname && window.location.hostname == "demo.analytical-labs.com" ) {
account = 'UA-16172251-5';
}
var _gaq = _gaq || [];
_gaq.push(['_setAccount', account]);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
| clevernet/CleverNIM | saiku-ui/js/ga.js | JavaScript | gpl-3.0 | 1,366 |
#ifndef STAN_MATH_PRIM_SCAL_PROB_STUDENT_T_RNG_HPP
#define STAN_MATH_PRIM_SCAL_PROB_STUDENT_T_RNG_HPP
#include <boost/random/student_t_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/err/check_finite.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/err/check_positive_finite.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/scal/fun/square.hpp>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <stan/math/prim/scal/fun/lbeta.hpp>
#include <stan/math/prim/scal/fun/lgamma.hpp>
#include <stan/math/prim/scal/fun/digamma.hpp>
#include <stan/math/prim/scal/meta/length.hpp>
#include <stan/math/prim/scal/fun/grad_reg_inc_beta.hpp>
#include <stan/math/prim/scal/fun/inc_beta.hpp>
#include <stan/math/prim/scal/meta/include_summand.hpp>
#include <stan/math/prim/scal/meta/VectorBuilder.hpp>
namespace stan {
namespace math {
template <class RNG>
inline double
student_t_rng(double nu,
double mu,
double sigma,
RNG& rng) {
using boost::variate_generator;
using boost::random::student_t_distribution;
static const char* function("student_t_rng");
check_positive_finite(function, "Degrees of freedom parameter", nu);
check_finite(function, "Location parameter", mu);
check_positive_finite(function, "Scale parameter", sigma);
variate_generator<RNG&, student_t_distribution<> >
rng_unit_student_t(rng, student_t_distribution<>(nu));
return mu + sigma * rng_unit_student_t();
}
}
}
#endif
| TomasVaskevicius/bouncy-particle-sampler | third_party/stan_math/stan/math/prim/scal/prob/student_t_rng.hpp | C++ | gpl-3.0 | 1,700 |
from py2neo import Graph
from py2neo.ext.gremlin import Gremlin
import os
DEFAULT_GRAPHDB_URL = "http://localhost:7474/db/data/"
DEFAULT_STEP_DIR = os.path.dirname(__file__) + '/bjoernsteps/'
class BjoernSteps:
def __init__(self):
self._initJoernSteps()
self.initCommandSent = False
def setGraphDbURL(self, url):
""" Sets the graph database URL. By default,
http://localhost:7474/db/data/ is used."""
self.graphDbURL = url
def addStepsDir(self, stepsDir):
"""Add an additional directory containing steps to be injected
into the server"""
self.stepsDirs.append(stepsDir)
def connectToDatabase(self):
""" Connects to the database server."""
self.graphDb = Graph(self.graphDbURL)
self.gremlin = Gremlin(self.graphDb)
def runGremlinQuery(self, query):
""" Runs the specified gremlin query on the database. It is
assumed that a connection to the database has been
established. To allow the user-defined steps located in the
joernsteps directory to be used in the query, these step
definitions are prepended to the query."""
if not self.initCommandSent:
self.gremlin.execute(self._createInitCommand())
self.initCommandSent = True
return self.gremlin.execute(query)
def runCypherQuery(self, cmd):
""" Runs the specified cypher query on the graph database."""
return cypher.execute(self.graphDb, cmd)
def getGraphDbURL(self):
return self.graphDbURL
"""
Create chunks from a list of ids.
This method is useful when you want to execute many independent
traversals on a large set of start nodes. In that case, you
can retrieve the set of start node ids first, then use 'chunks'
to obtain disjoint subsets that can be passed to idListToNodes.
"""
def chunks(self, idList, chunkSize):
for i in xrange(0, len(idList), chunkSize):
yield idList[i:i+chunkSize]
def _initJoernSteps(self):
self.graphDbURL = DEFAULT_GRAPHDB_URL
self.stepsDirs = [DEFAULT_STEP_DIR]
def _createInitCommand(self):
initCommand = ""
for stepsDir in self.stepsDirs:
for (root, dirs, files) in os.walk(stepsDir, followlinks=True):
files.sort()
for f in files:
filename = os.path.join(root, f)
if not filename.endswith('.groovy'): continue
initCommand += file(filename).read() + "\n"
return initCommand
| mrphrazer/bjoern | python-bjoern/bjoern/all.py | Python | gpl-3.0 | 2,645 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2011-2018 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "slipPointPatchFields.H"
#include "pointPatchFields.H"
#include "addToRunTimeSelectionTable.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
makePointPatchFields(slip);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// ************************************************************************* //
| will-bainbridge/OpenFOAM-dev | src/OpenFOAM/fields/pointPatchFields/derived/slip/slipPointPatchFields.C | C++ | gpl-3.0 | 1,689 |
/*
* gvNIX is an open source tool for rapid application development (RAD).
* Copyright (C) 2010 Generalitat Valenciana
*
* 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 org.gvnix.addon.geo.addon;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.gvnix.addon.geo.annotations.GvNIXMapViewer;
import org.gvnix.support.WebProjectUtils;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.springframework.roo.addon.propfiles.PropFileOperations;
import org.springframework.roo.classpath.PhysicalTypeIdentifier;
import org.springframework.roo.classpath.PhysicalTypeMetadata;
import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails;
import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadata;
import org.springframework.roo.classpath.details.annotations.ArrayAttributeValue;
import org.springframework.roo.classpath.details.annotations.ClassAttributeValue;
import org.springframework.roo.classpath.itd.AbstractItdMetadataProvider;
import org.springframework.roo.classpath.itd.ItdTypeDetailsProvidingMetadataItem;
import org.springframework.roo.model.JavaSymbolName;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.model.SpringJavaType;
import org.springframework.roo.project.LogicalPath;
import org.springframework.roo.project.ProjectOperations;
import org.springframework.roo.support.logging.HandlerUtils;
/**
* Provides {@link GvNIXMapViewerMetadata}.
*
* @author <a href="http://www.disid.com">DISID Corporation S.L.</a> made for <a
* href="http://www.dgti.gva.es">General Directorate for Information
* Technologies (DGTI)</a>
* @since 1.4
*/
@Component
@Service
public final class GvNIXMapViewerMetadataProvider extends
AbstractItdMetadataProvider {
private static final Logger LOGGER = HandlerUtils
.getLogger(GvNIXMapViewerMetadataProvider.class);
private ProjectOperations projectOperations;
private PropFileOperations propFileOperations;
private WebProjectUtils webProjectUtils;
/**
* Register itself into metadataDependencyRegister and add metadata trigger
*
* @param context the component context
*/
protected void activate(ComponentContext cContext) {
context = cContext.getBundleContext();
getMetadataDependencyRegistry().registerDependency(
PhysicalTypeIdentifier.getMetadataIdentiferType(),
getProvidesType());
addMetadataTrigger(new JavaType(GvNIXMapViewer.class.getName()));
}
/**
* Unregister this provider
*
* @param context the component context
*/
protected void deactivate(ComponentContext context) {
getMetadataDependencyRegistry().deregisterDependency(
PhysicalTypeIdentifier.getMetadataIdentiferType(),
getProvidesType());
removeMetadataTrigger(new JavaType(GvNIXMapViewer.class.getName()));
}
/**
* Return an instance of the Metadata offered by this add-on
*/
protected ItdTypeDetailsProvidingMetadataItem getMetadata(
String metadataIdentificationString, JavaType aspectName,
PhysicalTypeMetadata governorPhysicalTypeMetadata,
String itdFilename) {
JavaType javaType = GvNIXMapViewerMetadata
.getJavaType(metadataIdentificationString);
ClassOrInterfaceTypeDetails controller = getTypeLocationService()
.getTypeDetails(javaType);
// Getting @RequestMapping annotation
AnnotationMetadata requestMappingAnnotation = controller
.getAnnotation(SpringJavaType.REQUEST_MAPPING);
// Getting @GvNIXMapViewer annotation
AnnotationMetadata mapViewerAnnotation = controller
.getAnnotation(new JavaType(GvNIXMapViewer.class.getName()));
// Getting path value
AnnotationAttributeValue<Object> value = requestMappingAnnotation
.getAttribute("value");
String path = value.getValue().toString();
// Getting mapId
String mapId = String.format("ps_%s_%s", javaType.getPackage()
.getFullyQualifiedPackageName().replaceAll("[.]", "_"),
new JavaSymbolName(path.replaceAll("/", ""))
.getSymbolNameCapitalisedFirstLetter());
// Getting entityLayers
List<JavaType> entitiesToVisualize = new ArrayList<JavaType>();
@SuppressWarnings({ "unchecked", "rawtypes" })
ArrayAttributeValue<ClassAttributeValue> mapViewerAttributes = (ArrayAttributeValue) mapViewerAnnotation
.getAttribute("entityLayers");
if (mapViewerAttributes != null) {
List<ClassAttributeValue> entityLayers = mapViewerAttributes
.getValue();
for (ClassAttributeValue entity : entityLayers) {
entitiesToVisualize.add(entity.getValue());
}
}
// Getting projection
String projection = "";
AnnotationAttributeValue<Object> projectionAttr = mapViewerAnnotation
.getAttribute("projection");
if (projectionAttr != null) {
projection = projectionAttr.getValue().toString();
}
return new GvNIXMapViewerMetadata(metadataIdentificationString,
aspectName, governorPhysicalTypeMetadata,
getProjectOperations(), getPropFileOperations(),
getTypeLocationService(), getFileManager(),
entitiesToVisualize, path, mapId, projection,
getWebProjectUtils());
}
/**
* Define the unique ITD file name extension, here the resulting file name
* will be **_ROO_GvNIXMapViewer.aj
*/
public String getItdUniquenessFilenameSuffix() {
return "GvNIXMapViewer";
}
protected String getGovernorPhysicalTypeIdentifier(
String metadataIdentificationString) {
JavaType javaType = GvNIXMapViewerMetadata
.getJavaType(metadataIdentificationString);
LogicalPath path = GvNIXMapViewerMetadata
.getPath(metadataIdentificationString);
return PhysicalTypeIdentifier.createIdentifier(javaType, path);
}
protected String createLocalIdentifier(JavaType javaType, LogicalPath path) {
return GvNIXMapViewerMetadata.createIdentifier(javaType, path);
}
public String getProvidesType() {
return GvNIXMapViewerMetadata.getMetadataIdentiferType();
}
public ProjectOperations getProjectOperations() {
if (projectOperations == null) {
// Get all Services implement ProjectOperations interface
try {
ServiceReference<?>[] references = this.context
.getAllServiceReferences(
ProjectOperations.class.getName(), null);
for (ServiceReference<?> ref : references) {
return (ProjectOperations) this.context.getService(ref);
}
return null;
}
catch (InvalidSyntaxException e) {
LOGGER.warning("Cannot load ProjectOperations on GvNIXWebEntityMapLayerMetadataProvider.");
return null;
}
}
else {
return projectOperations;
}
}
public PropFileOperations getPropFileOperations() {
if (propFileOperations == null) {
// Get all Services implement PropFileOperations interface
try {
ServiceReference<?>[] references = this.context
.getAllServiceReferences(
PropFileOperations.class.getName(), null);
for (ServiceReference<?> ref : references) {
return (PropFileOperations) this.context.getService(ref);
}
return null;
}
catch (InvalidSyntaxException e) {
LOGGER.warning("Cannot load PropFileOperations on GvNIXWebEntityMapLayerMetadataProvider.");
return null;
}
}
else {
return propFileOperations;
}
}
public WebProjectUtils getWebProjectUtils() {
if (webProjectUtils == null) {
// Get all Services implement WebProjectUtils interface
try {
ServiceReference<?>[] references = this.context
.getAllServiceReferences(
WebProjectUtils.class.getName(), null);
for (ServiceReference<?> ref : references) {
webProjectUtils = (WebProjectUtils) this.context
.getService(ref);
return webProjectUtils;
}
return null;
}
catch (InvalidSyntaxException e) {
LOGGER.warning("Cannot load WebProjectUtils on GvNIXWebEntityMapLayerMetadataProvider.");
return null;
}
}
else {
return webProjectUtils;
}
}
} | osroca/gvnix | addon-web-mvc-geo/addon/src/main/java/org/gvnix/addon/geo/addon/GvNIXMapViewerMetadataProvider.java | Java | gpl-3.0 | 10,078 |
// Copyright � 2010 - May 2014 Rise Vision Incorporated.
// Use of this software is governed by the GPLv3 license
// (reproduced in the LICENSE file).
function rvPlayerDCPage() {
var pageHTML = "";
this.get = function (port, ports, dcStatus, onStr, offStr) {
var res = pageHTML.replace("[PORT]", port);
res = res.replace("[PORTS]", ports);
res = res.replace("[Status]", dcStatus);
res = res.replace("[onStr]", onStr);
res = res.replace("[offStr]", offStr);
return res;
}
this.init = function () {
download(chrome.runtime.getURL("display_page.html"));
}
var download = function (fileUrl) {
var xhr = new XMLHttpRequest();
xhr.responseType = "text";
//xhr.onerror = ???;
xhr.onload = function (xhrProgressEvent) {
pageHTML = xhrProgressEvent.target.responseText;
}
xhr.open('GET', fileUrl, true); //async=true
xhr.send();
};
} | xlsuite/reach.network | player-socialweedia/app/js/player/dc_page.js | JavaScript | gpl-3.0 | 985 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Ansible module to manage A10 Networks slb service-group objects
(c) 2014, Mischa Peters <mpeters@a10networks.com>,
Eric Chou <ericc@a10networks.com>
This file is part of Ansible
Ansible 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.
Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
"""
DOCUMENTATION = '''
---
module: a10_service_group
version_added: 1.8
short_description: Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' service groups.
description:
- Manage SLB (Server Load Balancing) service-group objects on A10 Networks devices via aXAPIv2.
author: "Eric Chou (@ericchou) 2016, Mischa Peters (@mischapeters) 2014"
notes:
- Requires A10 Networks aXAPI 2.1.
- When a server doesn't exist and is added to the service-group the server will be created.
extends_documentation_fragment: a10
options:
partition:
version_added: "2.3"
description:
- set active-partition
required: false
default: null
service_group:
description:
- The SLB (Server Load Balancing) service-group name
required: true
default: null
aliases: ['service', 'pool', 'group']
service_group_protocol:
description:
- The SLB service-group protocol of TCP or UDP.
required: false
default: tcp
aliases: ['proto', 'protocol']
choices: ['tcp', 'udp']
service_group_method:
description:
- The SLB service-group load balancing method, such as round-robin or weighted-rr.
required: false
default: round-robin
aliases: ['method']
choices: ['round-robin', 'weighted-rr', 'least-connection', 'weighted-least-connection', 'service-least-connection', 'service-weighted-least-connection', 'fastest-response', 'least-request', 'round-robin-strict', 'src-ip-only-hash', 'src-ip-hash']
servers:
description:
- A list of servers to add to the service group. Each list item should be a
dictionary which specifies the C(server:) and C(port:), but can also optionally
specify the C(status:). See the examples below for details.
required: false
default: null
validate_certs:
description:
- If C(no), SSL certificates will not be validated. This should only be used
on personally controlled devices using self-signed certificates.
required: false
default: 'yes'
choices: ['yes', 'no']
'''
RETURN = '''
#
'''
EXAMPLES = '''
# Create a new service-group
- a10_service_group:
host: a10.mydomain.com
username: myadmin
password: mypassword
partition: mypartition
service_group: sg-80-tcp
servers:
- server: foo1.mydomain.com
port: 8080
- server: foo2.mydomain.com
port: 8080
- server: foo3.mydomain.com
port: 8080
- server: foo4.mydomain.com
port: 8080
status: disabled
'''
RETURN = '''
content:
description: the full info regarding the slb_service_group
returned: success
type: string
sample: "mynewservicegroup"
'''
VALID_SERVICE_GROUP_FIELDS = ['name', 'protocol', 'lb_method']
VALID_SERVER_FIELDS = ['server', 'port', 'status']
def validate_servers(module, servers):
for item in servers:
for key in item:
if key not in VALID_SERVER_FIELDS:
module.fail_json(msg="invalid server field (%s), must be one of: %s" % (key, ','.join(VALID_SERVER_FIELDS)))
# validate the server name is present
if 'server' not in item:
module.fail_json(msg="server definitions must define the server field")
# validate the port number is present and an integer
if 'port' in item:
try:
item['port'] = int(item['port'])
except:
module.fail_json(msg="server port definitions must be integers")
else:
module.fail_json(msg="server definitions must define the port field")
# convert the status to the internal API integer value
if 'status' in item:
item['status'] = axapi_enabled_disabled(item['status'])
else:
item['status'] = 1
def main():
argument_spec = a10_argument_spec()
argument_spec.update(url_argument_spec())
argument_spec.update(
dict(
state=dict(type='str', default='present', choices=['present', 'absent']),
service_group=dict(type='str', aliases=['service', 'pool', 'group'], required=True),
service_group_protocol=dict(type='str', default='tcp', aliases=['proto', 'protocol'], choices=['tcp', 'udp']),
service_group_method=dict(type='str', default='round-robin',
aliases=['method'],
choices=['round-robin',
'weighted-rr',
'least-connection',
'weighted-least-connection',
'service-least-connection',
'service-weighted-least-connection',
'fastest-response',
'least-request',
'round-robin-strict',
'src-ip-only-hash',
'src-ip-hash']),
servers=dict(type='list', aliases=['server', 'member'], default=[]),
partition=dict(type='str', default=[]),
)
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=False
)
host = module.params['host']
username = module.params['username']
password = module.params['password']
partition = module.params['partition']
state = module.params['state']
write_config = module.params['write_config']
slb_service_group = module.params['service_group']
slb_service_group_proto = module.params['service_group_protocol']
slb_service_group_method = module.params['service_group_method']
slb_servers = module.params['servers']
if slb_service_group is None:
module.fail_json(msg='service_group is required')
axapi_base_url = 'https://' + host + '/services/rest/V2.1/?format=json'
load_balancing_methods = {'round-robin': 0,
'weighted-rr': 1,
'least-connection': 2,
'weighted-least-connection': 3,
'service-least-connection': 4,
'service-weighted-least-connection': 5,
'fastest-response': 6,
'least-request': 7,
'round-robin-strict': 8,
'src-ip-only-hash': 14,
'src-ip-hash': 15}
if not slb_service_group_proto or slb_service_group_proto.lower() == 'tcp':
protocol = 2
else:
protocol = 3
# validate the server data list structure
validate_servers(module, slb_servers)
json_post = {
'service_group': {
'name': slb_service_group,
'protocol': protocol,
'lb_method': load_balancing_methods[slb_service_group_method],
}
}
# first we authenticate to get a session id
session_url = axapi_authenticate(module, axapi_base_url, username, password)
# then we select the active-partition
slb_server_partition = axapi_call(module, session_url + '&method=system.partition.active', json.dumps({'name': partition}))
# then we check to see if the specified group exists
slb_result = axapi_call(module, session_url + '&method=slb.service_group.search', json.dumps({'name': slb_service_group}))
slb_service_group_exist = not axapi_failure(slb_result)
changed = False
if state == 'present':
# before creating/updating we need to validate that servers
# defined in the servers list exist to prevent errors
checked_servers = []
for server in slb_servers:
result = axapi_call(module, session_url + '&method=slb.server.search', json.dumps({'name': server['server']}))
if axapi_failure(result):
module.fail_json(msg="the server %s specified in the servers list does not exist" % server['server'])
checked_servers.append(server['server'])
if not slb_service_group_exist:
result = axapi_call(module, session_url + '&method=slb.service_group.create', json.dumps(json_post))
if axapi_failure(result):
module.fail_json(msg=result['response']['err']['msg'])
changed = True
else:
# check to see if the service group definition without the
# server members is different, and update that individually
# if it needs it
do_update = False
for field in VALID_SERVICE_GROUP_FIELDS:
if json_post['service_group'][field] != slb_result['service_group'][field]:
do_update = True
break
if do_update:
result = axapi_call(module, session_url + '&method=slb.service_group.update', json.dumps(json_post))
if axapi_failure(result):
module.fail_json(msg=result['response']['err']['msg'])
changed = True
# next we pull the defined list of servers out of the returned
# results to make it a bit easier to iterate over
defined_servers = slb_result.get('service_group', {}).get('member_list', [])
# next we add/update new member servers from the user-specified
# list if they're different or not on the target device
for server in slb_servers:
found = False
different = False
for def_server in defined_servers:
if server['server'] == def_server['server']:
found = True
for valid_field in VALID_SERVER_FIELDS:
if server[valid_field] != def_server[valid_field]:
different = True
break
if found or different:
break
# add or update as required
server_data = {
"name": slb_service_group,
"member": server,
}
if not found:
result = axapi_call(module, session_url + '&method=slb.service_group.member.create', json.dumps(server_data))
changed = True
elif different:
result = axapi_call(module, session_url + '&method=slb.service_group.member.update', json.dumps(server_data))
changed = True
# finally, remove any servers that are on the target
# device but were not specified in the list given
for server in defined_servers:
found = False
for slb_server in slb_servers:
if server['server'] == slb_server['server']:
found = True
break
# remove if not found
server_data = {
"name": slb_service_group,
"member": server,
}
if not found:
result = axapi_call(module, session_url + '&method=slb.service_group.member.delete', json.dumps(server_data))
changed = True
# if we changed things, get the full info regarding
# the service group for the return data below
if changed:
result = axapi_call(module, session_url + '&method=slb.service_group.search', json.dumps({'name': slb_service_group}))
else:
result = slb_result
elif state == 'absent':
if slb_service_group_exist:
result = axapi_call(module, session_url + '&method=slb.service_group.delete', json.dumps({'name': slb_service_group}))
changed = True
else:
result = dict(msg="the service group was not present")
# if the config has changed, save the config unless otherwise requested
if changed and write_config:
write_result = axapi_call(module, session_url + '&method=system.action.write_memory')
if axapi_failure(write_result):
module.fail_json(msg="failed to save the configuration: %s" % write_result['response']['err']['msg'])
# log out of the session nicely and exit
axapi_call(module, session_url + '&method=session.close')
module.exit_json(changed=changed, content=result)
# standard ansible module imports
import json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import url_argument_spec
from ansible.module_utils.a10 import axapi_call, a10_argument_spec, axapi_authenticate, axapi_failure, axapi_enabled_disabled
if __name__ == '__main__':
main()
| kbrebanov/ansible-modules-extras | network/a10/a10_service_group.py | Python | gpl-3.0 | 13,531 |
# The majority of The Supplejack Manager code is Crown copyright (C) 2014, New Zealand Government,
# and is licensed under the GNU General Public License, version 3. Some components are
# third party components that are licensed under the MIT license or otherwise publicly available.
# See https://github.com/DigitalNZ/supplejack_manager for details.
#
# Supplejack was created by DigitalNZ at the National Library of NZ and the Department of Internal Affairs.
# http://digitalnz.org/supplejack
require "spec_helper"
describe CollectionStatisticsHelper do
end | motizuki/supplejack_manager | spec/helpers/collection_statistics_helper_spec.rb | Ruby | gpl-3.0 | 566 |
package com.oryx.remote.webservice.element._enum;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Classe Java pour XmlEnumContact.
* <p>
* <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe.
* <p>
* <pre>
* <simpleType name="XmlEnumContact">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Phone"/>
* <enumeration value="Mobile"/>
* <enumeration value="Fax"/>
* <enumeration value="Web"/>
* <enumeration value="Email"/>
* </restriction>
* </simpleType>
* </pre>
*/
@XmlType(name = "XmlEnumContact", namespace = "http://enum.element.webservice.remote.oryx.com")
@XmlEnum
public enum XmlEnumContact {
@XmlEnumValue("Phone")
PHONE("Phone"),
@XmlEnumValue("Mobile")
MOBILE("Mobile"),
@XmlEnumValue("Fax")
FAX("Fax"),
@XmlEnumValue("Web")
WEB("Web"),
@XmlEnumValue("Email")
EMAIL("Email");
private final String value;
XmlEnumContact(String v) {
value = v;
}
public static XmlEnumContact fromValue(String v) {
for (XmlEnumContact c : XmlEnumContact.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
public String value() {
return value;
}
}
| 241180/Oryx | oryx-server-ws-gen/src/main/java/copied/com/oryx/remote/webservice/element/_enum/XmlEnumContact.java | Java | gpl-3.0 | 1,467 |
# -*- coding: utf-8 -*-
"""
tiponpython Simulacion de ensayos de acuiferos
Copyright 2012 Andres Pias
This file is part of tiponpython.
tiponpython is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
tiponpython 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 tiponpython. If not, see http://www.gnu.org/licenses/gpl.txt.
"""
# Form implementation generated from reading ui file 'ingresarCaudal.ui'
#
# Created: Wed Dec 14 21:03:09 2011
# by: PyQt4 UI code generator 4.8.5
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
import observacion
import observacionesensayo
import sys
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Dialog(QtGui.QDialog):
def setupUi(self, Dialog, cont):
global ContEnsayo
ContEnsayo=cont
self.observaciones=[]
Dialog.setObjectName(_fromUtf8("ingresarobservacionesensayo"))
Dialog.resize(375, 214)
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Ingresar Observaciones Ensayo", None, QtGui.QApplication.UnicodeUTF8))
self.txttiempo = QtGui.QTextEdit(Dialog)
self.txttiempo.setGeometry(QtCore.QRect(170, 40, 101, 31))
self.txttiempo.setObjectName(_fromUtf8("txttiempo"))
self.label = QtGui.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(100, 50, 46, 21))
self.label.setText(QtGui.QApplication.translate("Dialog", "Tiempo", None, QtGui.QApplication.UnicodeUTF8))
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(100, 100, 46, 13))
self.label_2.setText(QtGui.QApplication.translate("Dialog", "Nivel", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.txtcaudal = QtGui.QTextEdit(Dialog)
self.txtcaudal.setGeometry(QtCore.QRect(170, 90, 101, 31))
self.txtcaudal.setObjectName(_fromUtf8("txtcaudal"))
self.btnagregar = QtGui.QPushButton(Dialog)
self.btnagregar.setGeometry(QtCore.QRect(100, 150, 71, 23))
self.btnagregar.setText(QtGui.QApplication.translate("Dialog", "Agregar", None, QtGui.QApplication.UnicodeUTF8))
self.btnagregar.setObjectName(_fromUtf8("btnagregar"))
self.btnfinalizar = QtGui.QPushButton(Dialog)
self.btnfinalizar.setGeometry(QtCore.QRect(200, 150, 71, 23))
self.btnfinalizar.setText(QtGui.QApplication.translate("Dialog", "Finalizar", None, QtGui.QApplication.UnicodeUTF8))
self.btnfinalizar.setObjectName(_fromUtf8("btnfinalizar"))
self.dialogo=Dialog
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.btnagregar, QtCore.SIGNAL(_fromUtf8("clicked()")), self.agregar)
QtCore.QObject.connect(self.btnfinalizar, QtCore.SIGNAL(_fromUtf8("clicked()")), self.finalizar)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
pass
def agregar(self):
global ContEnsayo
control=True
t=float(self.txttiempo.toPlainText())
print "tiempo: "+str(t)
## Se verifica que vengas los datos con sus tiempos ordenados de manera creciente sino salta
control=ContEnsayo.verificarFormato(self.observaciones, t)
if (control==False):
reply = QtGui.QMessageBox.critical(self,
"Error",
"Los datos de bombeo no fueron agregaos. Debe ingresar un valor para el tiempo mayor a los ingresados anteriormente.")
else:
n=float(self.txtcaudal.toPlainText())
print "caudal: "+str(n)
o=observacion.observacion(t,n)
self.observaciones.append(o)
reply = QtGui.QMessageBox.information(None,
"Información",
"Se agrego la nueva observacion del ensayo. Presione finalizar para guardar las observaciones")
self.txttiempo.setText('')
self.txtcaudal.setText('')
def finalizar(self):
global ContEnsayo
####Pedir un nombre para el ensayo
nombre, ok=QtGui.QInputDialog.getText(self,"Finalzar registro ",
"Nombre: ", QtGui.QLineEdit.Normal)
## Se manda al controlador las observaciones y se retorna el id de las observaciones
obse=ContEnsayo.agregarObservacion(self.observaciones, nombre)
reply = QtGui.QMessageBox.information(self,
"Información",
"Se ha creado un nuevo conjunto de observaciones en el sistema. El id es: "+ str(obse.id))
if reply == QtGui.QMessageBox.Ok:
print "OK"
self.dialogo.close()
else:
print "Escape"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
frmImpProyecto = QtGui.QWidget()
ui = Ui_Dialog()
ui.setupUi(frmImpProyecto)
frmImpProyecto.show()
sys.exit(app.exec_())
| fenixon/tiponpython | views/ingresarObservaciones.py | Python | gpl-3.0 | 5,555 |
import WordCombination from "../../src/values/WordCombination";
import relevantWords from "../../src/stringProcessing/relevantWords";
import polishFunctionWordsFactory from "../../src/researches/polish/functionWords.js";
const getRelevantWords = relevantWords.getRelevantWords;
const polishFunctionWords = polishFunctionWordsFactory().all;
describe( "gets Polish word combinations", function() {
it( "returns word combinations", function() {
const input = "W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce piersiowej, to należy natychmiast" +
" dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce piersiowej, to należy " +
"natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce piersiowej, " +
"to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce " +
"piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w" +
" klatce piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś " +
"odczuwa ból w klatce piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że " +
"gdy ktoś odczuwa ból w klatce piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas" +
" wie, że gdy ktoś odczuwa ból w klatce piersiowej, to należy natychmiast dzwonić po karetkę.";
const expected = [
new WordCombination( [ "odczuwa", "ból", "w", "klatce", "piersiowej" ], 8, polishFunctionWords ),
new WordCombination( [ "natychmiast", "dzwonić", "po", "karetkę" ], 8, polishFunctionWords ),
new WordCombination( [ "ból", "w", "klatce", "piersiowej" ], 8, polishFunctionWords ),
new WordCombination( [ "odczuwa", "ból", "w", "klatce" ], 8, polishFunctionWords ),
new WordCombination( [ "dzwonić", "po", "karetkę" ], 8, polishFunctionWords ),
new WordCombination( [ "ból", "w", "klatce" ], 8, polishFunctionWords ),
new WordCombination( [ "odczuwa", "ból" ], 8, polishFunctionWords ),
new WordCombination( [ "natychmiast", "dzwonić" ], 8, polishFunctionWords ),
new WordCombination( [ "klatce", "piersiowej" ], 8, polishFunctionWords ),
new WordCombination( [ "wie" ], 8, polishFunctionWords ),
new WordCombination( [ "karetkę" ], 8, polishFunctionWords ),
new WordCombination( [ "dzwonić" ], 8, polishFunctionWords ),
new WordCombination( [ "natychmiast" ], 8, polishFunctionWords ),
new WordCombination( [ "piersiowej" ], 8, polishFunctionWords ),
new WordCombination( [ "klatce" ], 8, polishFunctionWords ),
new WordCombination( [ "ból" ], 8, polishFunctionWords ),
new WordCombination( [ "odczuwa" ], 8, polishFunctionWords ),
new WordCombination( [ "zasadzie" ], 8, polishFunctionWords ),
];
// Make sure our words aren't filtered by density.
spyOn( WordCombination.prototype, "getDensity" ).and.returnValue( 0.01 );
const words = getRelevantWords( input, "pl_PL" );
words.forEach( function( word ) {
delete( word._relevantWords );
} );
expect( words ).toEqual( expected );
} );
} );
| Yoast/js-text-analysis | spec/stringProcessing/relevantWordsPolishSpec.js | JavaScript | gpl-3.0 | 3,204 |