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
//: generics/FactoryConstraint.java interface FactoryI<T> { T create(); } class Foo2<T> { private T x; public <F extends FactoryI<T>> Foo2(F factory) { x = factory.create(); } // ... } class IntegerFactory implements FactoryI<Integer> { public Integer create() { return new Integer(0); } } class Widget { public static class Factory implements FactoryI<Widget> { public Widget create() { return new Widget(); } } } public class FactoryConstraint { public static void main(String[] args) { new Foo2<Integer>(new IntegerFactory()); new Foo2<Widget>(new Widget.Factory()); } } ///:~
NorthFacing/step-by-Java
java-base/sourceCodeBak/Thinking in Java/generics/FactoryConstraint.java
Java
gpl-2.0
638
<?php /* * Copyright 2005-2015 Centreon * Centreon is developped by : Julien Mathis and Romain Le Merlus under * GPL Licence 2.0. * * 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. * * 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>. * * Linking this program statically or dynamically with other modules is making a * combined work based on this program. Thus, the terms and conditions of the GNU * General Public License cover the whole combination. * * As a special exception, the copyright holders of this program give Centreon * permission to link this program with independent modules to produce an executable, * regardless of the license terms of these independent modules, and to copy and * distribute the resulting executable under terms of Centreon choice, provided that * Centreon also meet, for each linked independent module, the terms and conditions * of the license of that module. An independent module is a module which is not * derived from this program. If you modify this program, you may extend this * exception to your version of the program, but you are not obliged to do so. If you * do not wish to do so, delete this exception statement from your version. * * For more information : contact@centreon.com * */ if (!isset($centreon)) { exit(); } /* * Path to the configuration dir */ $path = "./include/views/graphs/"; /* * Smarty template Init */ $tpl = new Smarty(); $tpl = initSmartyTpl($path, $tpl); function getGetPostValue($str) { $value = null; if (isset($_GET[$str]) && $_GET[$str]) { $value = $_GET[$str]; } if (isset($_POST[$str]) && $_POST[$str]) { $value = $_POST[$str]; } return urldecode($value); } $svc_id = getGetPostValue('chartId'); $metrics = array(); if (isset($svc_id) && $svc_id) { list($hostId, $svcId) = explode('_', $svc_id); /* Get list metrics */ $query = 'SELECT m.metric_id, m.metric_name, i.host_name, i.service_description FROM metrics m, index_data i WHERE i.id = m.index_id AND i.service_id = ' . CentreonDB::escape($svcId) . ' AND i.host_id = ' . CentreonDB::escape($hostId); $res = $pearDBO->query($query); while ($row = $res->fetchRow()) { $metrics[] = array( 'id' => $svc_id . '_' .$row['metric_id'], 'title' => $row['host_name'] . ' - ' . $row['service_description'] . ' : ' . $row['metric_name'] ); } } /* Get Period if is in url */ $period_start = 'undefined'; $period_end = 'undefined'; if (isset($_REQUEST['start']) && is_numeric($_REQUEST['start'])) { $period_start = $_REQUEST['start']; } if (isset($_REQUEST['end']) && is_numeric($_REQUEST['end'])) { $period_end = $_REQUEST['end']; } /* * Form begin */ $form = new HTML_QuickFormCustom('FormPeriod', 'get', "?p=".$p); $periods = array( "" => "", "3h" => _("Last 3 Hours"), "6h" => _("Last 6 Hours"), "12h" => _("Last 12 Hours"), "1d" => _("Last 24 Hours"), "2d" => _("Last 2 Days"), "3d" => _("Last 3 Days"), "4d" => _("Last 4 Days"), "5d" => _("Last 5 Days"), "7d" => _("Last 7 Days"), "14d" => _("Last 14 Days"), "28d" => _("Last 28 Days"), "30d" => _("Last 30 Days"), "31d" => _("Last 31 Days"), "2M" => _("Last 2 Months"), "4M" => _("Last 4 Months"), "6M" => _("Last 6 Months"), "1y" => _("Last Year") ); $sel = $form->addElement('select', 'period', _("Graph Period"), $periods, array("onchange"=>"changeInterval()")); $form->addElement( 'text', 'StartDate', '', array( "id" => "StartDate", "class" => "datepicker-iso", "size" => 10, "onchange" => "changePeriod()" ) ); $form->addElement( 'text', 'StartTime', '', array( "id" => "StartTime", "class" => "timepicker", "size" => 5, "onchange" => "changePeriod()" ) ); $form->addElement( 'text', 'EndDate', '', array( "id" => "EndDate", "class" => "datepicker-iso", "size" => 10, "onchange" => "changePeriod()" ) ); $form->addElement( 'text', 'EndTime', '', array( "id" => "EndTime", "class" => "timepicker", "size" => 5, "onchange" => "changePeriod()" ) ); if ($period_start != 'undefined' && $period_end != 'undefined') { $startDay = date('Y-m-d', $period_start); $startTime = date('H:i', $period_start); $endDay = date('Y-m-d', $period_end); $endTime = date('H:i', $period_end); $form->setDefaults(array( 'StartDate' => $startDay, 'StartTime' => $startTime, 'EndDate' => $endDay, 'EndTime' => $endTime )); } else { $form->setDefaults(array( 'period' => '3h' )); } $renderer = new HTML_QuickForm_Renderer_ArraySmarty($tpl); $form->accept($renderer); $tpl->assign('form', $renderer->toArray()); $tpl->assign('metrics', $metrics); $tpl->display("graph-split.html");
jben94/centreon
www/include/views/graphs/graph-split.php
PHP
gpl-2.0
5,434
<?php // URI: design/admin/templates/navigator/google.tpl // Filename: design/admin/templates/navigator/google.tpl // Timestamp: 1416144920 (Sun Nov 16 14:35:20 CET 2014) $oldSetArray_99a3cecd353295a13123c0e522f2c6fe = isset( $setArray ) ? $setArray : array(); $setArray = array(); $tpl->Level++; if ( $tpl->Level > 40 ) { $text = $tpl->MaxLevelWarning;$tpl->Level--; return; } $eZTemplateCompilerCodeDate = 1074699607; if ( !defined( 'EZ_TEMPLATE_COMPILER_COMMON_CODE' ) ) include_once( 'var/ezdemo_site/cache/template/compiled/common.php' ); if ( !isset( $vars[$currentNamespace]['page_uri_suffix'] ) ) { $vars[$currentNamespace]['page_uri_suffix'] = false; $setArray[$currentNamespace]['page_uri_suffix'] = true; } if ( !isset( $vars[$currentNamespace]['left_max'] ) ) { $vars[$currentNamespace]['left_max'] = 7; $setArray[$currentNamespace]['left_max'] = true; } if ( !isset( $vars[$currentNamespace]['right_max'] ) ) { $vars[$currentNamespace]['right_max'] = 6; $setArray[$currentNamespace]['right_max'] = true; } $namespace = $currentNamespace; if ( $namespace == '' ) $namespace = "ViewParameter"; else $namespace .= ':ViewParameter'; if ( !isset( $vars[$namespace]['page_uri_suffix'] ) ) { $vars[$namespace]['page_uri_suffix'] = false; $setArray[$namespace]['page_uri_suffix'] = true; } unset( $var ); unset( $var ); $var = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'left_max', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['left_max'] : null; if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $namespace = $currentNamespace; if ( $namespace == '' ) $namespace = "ViewParameter"; else $namespace .= ':ViewParameter'; if ( !isset( $vars[$namespace]['left_max'] ) ) { $vars[$namespace]['left_max'] = $var; unset( $var ); $setArray[$namespace]['left_max'] = true; } unset( $var ); unset( $var ); $var = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'right_max', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['right_max'] : null; if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $namespace = $currentNamespace; if ( $namespace == '' ) $namespace = "ViewParameter"; else $namespace .= ':ViewParameter'; if ( !isset( $vars[$namespace]['right_max'] ) ) { $vars[$namespace]['right_max'] = $var; unset( $var ); $setArray[$namespace]['right_max'] = true; } $namespaceStack[] = $currentNamespace; $currentNamespace .= ( $currentNamespace ? ":" : "" ) . 'ViewParameter'; unset( $var ); unset( $var1 ); unset( $var2 ); unset( $var3 ); unset( $var3 ); $var3 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_count', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_count'] : null; if (! isset( $var3 ) ) $var3 = NULL; while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); unset( $var4 ); unset( $var4 ); $var4 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_limit', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_limit'] : null; if (! isset( $var4 ) ) $var4 = NULL; while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); @$var2 = $var3 / $var4; unset( $var3, $var4 ); if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); $var1 = ceil( $var2 ); unset( $var2 ); if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); $var = (int)$var1; unset( $var1 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $vars[$currentNamespace]['page_count'] = $var; unset( $var ); unset( $var ); unset( $var1 ); unset( $var1 ); $var1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'page_count', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['page_count'] : null; if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); unset( $var2 ); unset( $var3 ); unset( $var4 ); unset( $var5 ); unset( $var6 ); unset( $var6 ); $var6 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( "view_parameters", $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]["view_parameters"] : null; $var7 = compiledFetchAttribute( $var6, "offset" ); unset( $var6 ); $var6 = $var7; if (! isset( $var6 ) ) $var6 = NULL; while ( is_object( $var6 ) and method_exists( $var6, 'templateValue' ) ) $var6 = $var6->templateValue(); while ( is_object( $var6 ) and method_exists( $var6, 'templateValue' ) ) $var6 = $var6->templateValue(); if ( isset( $var6 ) ) { $var5 = $var6; } else { $var5 = 0; } unset( $var6 ); if (! isset( $var5 ) ) $var5 = NULL; while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); unset( $var6 ); unset( $var6 ); $var6 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_limit', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_limit'] : null; if (! isset( $var6 ) ) $var6 = NULL; while ( is_object( $var6 ) and method_exists( $var6, 'templateValue' ) ) $var6 = $var6->templateValue(); while ( is_object( $var6 ) and method_exists( $var6, 'templateValue' ) ) $var6 = $var6->templateValue(); @$var4 = $var5 / $var6; unset( $var5, $var6 ); if (! isset( $var4 ) ) $var4 = NULL; while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); $var3 = ceil( $var4 ); unset( $var4 ); if (! isset( $var3 ) ) $var3 = NULL; while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); $var2 = (int)$var3; unset( $var3 ); if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); $var = min( $var1, $var2); unset( $var1, $var2 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $vars[$currentNamespace]['current_page'] = $var; unset( $var ); unset( $var ); unset( $var1 ); unset( $var2 ); unset( $var2 ); $var2 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'current_page', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['current_page'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); unset( $var3 ); unset( $var3 ); $var3 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_limit', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_limit'] : null; if (! isset( $var3 ) ) $var3 = NULL; while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); $var1 = $var2 * $var3; unset( $var2, $var3 ); if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); unset( $var2 ); unset( $var2 ); $var2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_limit', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_limit'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); $var = $var1 - $var2; unset( $var1, $var2 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $vars[$currentNamespace]['item_previous'] = $var; unset( $var ); unset( $var ); unset( $var1 ); unset( $var2 ); unset( $var2 ); $var2 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'current_page', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['current_page'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); unset( $var3 ); unset( $var3 ); $var3 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_limit', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_limit'] : null; if (! isset( $var3 ) ) $var3 = NULL; while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); $var1 = $var2 * $var3; unset( $var2, $var3 ); if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); unset( $var2 ); unset( $var2 ); $var2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_limit', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_limit'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); $var = $var1 + $var2; unset( $var1, $var2 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $vars[$currentNamespace]['item_next'] = $var; unset( $var ); unset( $var ); unset( $var1 ); $namespace = $rootNamespace; if ( $namespace == '' ) $namespace = "ViewParameter"; else $namespace .= ':ViewParameter'; unset( $var1 ); $var1 = ( array_key_exists( $namespace, $vars ) and array_key_exists( 'current_page', $vars[$namespace] ) ) ? $vars[$namespace]['current_page'] : null; if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); unset( $var2 ); unset( $var2 ); $var2 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'left_max', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['left_max'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); $var = min( $var1, $var2); unset( $var1, $var2 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $vars[$currentNamespace]['left_length'] = $var; unset( $var ); unset( $var ); unset( $var1 ); unset( $var2 ); unset( $var3 ); $namespace = $rootNamespace; if ( $namespace == '' ) $namespace = "ViewParameter"; else $namespace .= ':ViewParameter'; unset( $var3 ); $var3 = ( array_key_exists( $namespace, $vars ) and array_key_exists( 'page_count', $vars[$namespace] ) ) ? $vars[$namespace]['page_count'] : null; if (! isset( $var3 ) ) $var3 = NULL; while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); unset( $var4 ); $namespace = $rootNamespace; if ( $namespace == '' ) $namespace = "ViewParameter"; else $namespace .= ':ViewParameter'; unset( $var4 ); $var4 = ( array_key_exists( $namespace, $vars ) and array_key_exists( 'current_page', $vars[$namespace] ) ) ? $vars[$namespace]['current_page'] : null; if (! isset( $var4 ) ) $var4 = NULL; while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); $var2 = $var3 - $var4 - 1.000000; unset( $var3, $var4 ); if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); unset( $var3 ); unset( $var3 ); $var3 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'right_max', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['right_max'] : null; if (! isset( $var3 ) ) $var3 = NULL; while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); $var1 = min( $var2, $var3); unset( $var2, $var3 ); if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); $var = max( $var1, 0); unset( $var1 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $vars[$currentNamespace]['right_length'] = $var; unset( $var ); $vars[$currentNamespace]['view_parameter_text'] = ''; $vars[$currentNamespace]['offset_text'] = '/(offset)/'; unset( $loopItem ); unset( $loopItem ); $loopItem = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'view_parameters', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['view_parameters'] : null; if (! isset( $loopItem ) ) $loopItem = NULL; while ( is_object( $loopItem ) and method_exists( $loopItem, 'templateValue' ) ) $loopItem = $loopItem->templateValue(); if ( !isset( $sectionStack ) ) $sectionStack = array(); $index = 0; $currentIndex = 1; if ( is_array( $loopItem ) ) { $loopKeys = array_keys( $loopItem ); $loopCount = count( $loopKeys ); } else if ( is_numeric( $loopItem ) ) { $loopKeys = false; if ( $loopItem < 0 ) $loopCountValue = -$loopItem; else $loopCountValue = $loopItem; $loopCount = $loopCountValue - 0; } else if ( is_string( $loopItem ) ) { $loopKeys = false; $loopCount = strlen( $loopItem ) - 0; } else { $loopKeys = false; $loopCount = 0; } while ( $index < $loopCount ) { if ( is_array( $loopItem ) ) { $loopKey = $loopKeys[$index]; unset( $item ); $item = $loopItem[$loopKey]; } else if ( is_numeric( $loopItem ) ) { unset( $item ); $item = $index + 0 + 1; if ( $loopItem < 0 ) $item = -$item; $loopKey = $index + 0; } else if ( is_string( $loopItem ) ) { unset( $item ); $loopKey = $index + 0; $item = $loopItem[$loopKey]; } unset( $last ); $last = false; $vars[$currentNamespace]['key'] = $loopKey; $vars[$currentNamespace]['item'] = $item; $currentIndexInc = $currentIndex - 1; $vars[$currentNamespace]['index'] = $currentIndexInc; $vars[$currentNamespace]['number'] = $currentIndex; $matchValue = true; unset( $tmpMatchValue ); unset( $tmpMatchValue1 ); unset( $tmpMatchValue1 ); $tmpMatchValue1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'key', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['key'] : null; if (! isset( $tmpMatchValue1 ) ) $tmpMatchValue1 = NULL; while ( is_object( $tmpMatchValue1 ) and method_exists( $tmpMatchValue1, 'templateValue' ) ) $tmpMatchValue1 = $tmpMatchValue1->templateValue(); while ( is_object( $tmpMatchValue1 ) and method_exists( $tmpMatchValue1, 'templateValue' ) ) $tmpMatchValue1 = $tmpMatchValue1->templateValue(); $tmpMatchValue = ( ( $tmpMatchValue1 ) == ( 'offset' ) ); unset( $tmpMatchValue1 ); if (! isset( $tmpMatchValue ) ) $tmpMatchValue = NULL; while ( is_object( $tmpMatchValue ) and method_exists( $tmpMatchValue, 'templateValue' ) ) $tmpMatchValue = $tmpMatchValue->templateValue(); if ( $tmpMatchValue ) $matchValue = false; unset( $tmpMatchValue ); unset( $tmpMatchValue1 ); unset( $tmpMatchValue1 ); $tmpMatchValue1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'item', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['item'] : null; if (! isset( $tmpMatchValue1 ) ) $tmpMatchValue1 = NULL; while ( is_object( $tmpMatchValue1 ) and method_exists( $tmpMatchValue1, 'templateValue' ) ) $tmpMatchValue1 = $tmpMatchValue1->templateValue(); while ( is_object( $tmpMatchValue1 ) and method_exists( $tmpMatchValue1, 'templateValue' ) ) $tmpMatchValue1 = $tmpMatchValue1->templateValue(); $tmpMatchValue = ( ( $tmpMatchValue1 ) == ( '' ) ); unset( $tmpMatchValue1 ); if (! isset( $tmpMatchValue ) ) $tmpMatchValue = NULL; while ( is_object( $tmpMatchValue ) and method_exists( $tmpMatchValue, 'templateValue' ) ) $tmpMatchValue = $tmpMatchValue->templateValue(); if ( $tmpMatchValue ) $matchValue = false; if ( $matchValue ) { $sectionStack[] = array( &$loopItem, $loopKeys, $loopCount, $currentIndex, $index ); unset( $loopItem, $loopKeys ); $text .= ' '; unset( $var ); unset( $var1 ); unset( $var1 ); $var1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'view_parameter_text', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['view_parameter_text'] : null; if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); unset( $var3 ); unset( $var3 ); $var3 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'key', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['key'] : null; if (! isset( $var3 ) ) $var3 = NULL; while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); unset( $var5 ); unset( $var5 ); $var5 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'item', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['item'] : null; if (! isset( $var5 ) ) $var5 = NULL; while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); $var = ( $var1 . '/(' . $var3 . ')/' . $var5 ); unset( $var1, $var3, $var5 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); if ( array_key_exists( $currentNamespace, $vars ) && array_key_exists( 'view_parameter_text', $vars[$currentNamespace] ) ) { $vars[$currentNamespace]['view_parameter_text'] = $var; unset( $var ); } list( $loopItem, $loopKeys, $loopCount, $currentIndex, $index ) = array_pop( $sectionStack ); ++$currentIndex; } ++$index; } unset( $loopKeys, $loopCount, $index, $last, $loopIndex, $loopItem ); $text .= ' '; unset( $show ); unset( $show1 ); unset( $show1 ); $show1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'page_count', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['page_count'] : null; if (! isset( $show1 ) ) $show1 = NULL; while ( is_object( $show1 ) and method_exists( $show1, 'templateValue' ) ) $show1 = $show1->templateValue(); while ( is_object( $show1 ) and method_exists( $show1, 'templateValue' ) ) $show1 = $show1->templateValue(); $show = ( ( $show1 ) > ( 1 ) ); unset( $show1 ); if (! isset( $show ) ) $show = NULL; while ( is_object( $show ) and method_exists( $show, 'templateValue' ) ) $show = $show->templateValue(); if ( $show ) { unset( $show ); $text .= ' <div class="pagenavigator"> <p> '; unset( $var ); unset( $var1 ); unset( $var1 ); $var1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'item_previous', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['item_previous'] : null; if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); $var = ( ( $var1 ) < ( 0 ) ); unset( $var1 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $vars[$currentNamespace]['match'] = $var; unset( $var ); unset( $match ); unset( $match1 ); unset( $match1 ); $match1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'item_previous', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['item_previous'] : null; if (! isset( $match1 ) ) $match1 = NULL; while ( is_object( $match1 ) and method_exists( $match1, 'templateValue' ) ) $match1 = $match1->templateValue(); while ( is_object( $match1 ) and method_exists( $match1, 'templateValue' ) ) $match1 = $match1->templateValue(); $match = ( ( $match1 ) < ( 0 ) ); unset( $match1 ); if (! isset( $match ) ) $match = NULL; while ( is_object( $match ) and method_exists( $match, 'templateValue' ) ) $match = $match->templateValue(); switch ( $match ) { case 0: { $text .= ' <span class="previous"><a href='; unset( $var ); unset( $var1 ); unset( $var2 ); unset( $var2 ); $var2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); unset( $var3 ); unset( $var4 ); unset( $var5 ); unset( $var5 ); $var5 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'item_previous', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['item_previous'] : null; if (! isset( $var5 ) ) $var5 = NULL; while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); $var4 = ( ( $var5 ) > ( 0 ) ); unset( $var5 ); if (! isset( $var4 ) ) $var4 = NULL; while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); unset( $var6 ); unset( $var7 ); unset( $var7 ); $var7 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'offset_text', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['offset_text'] : null; if (! isset( $var7 ) ) $var7 = NULL; while ( is_object( $var7 ) and method_exists( $var7, 'templateValue' ) ) $var7 = $var7->templateValue(); while ( is_object( $var7 ) and method_exists( $var7, 'templateValue' ) ) $var7 = $var7->templateValue(); unset( $var8 ); unset( $var8 ); $var8 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'item_previous', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['item_previous'] : null; if (! isset( $var8 ) ) $var8 = NULL; while ( is_object( $var8 ) and method_exists( $var8, 'templateValue' ) ) $var8 = $var8->templateValue(); while ( is_object( $var8 ) and method_exists( $var8, 'templateValue' ) ) $var8 = $var8->templateValue(); $var6 = ( $var7 . $var8 ); unset( $var7, $var8 ); if (! isset( $var6 ) ) $var6 = NULL; while ( is_object( $var6 ) and method_exists( $var6, 'templateValue' ) ) $var6 = $var6->templateValue(); $var3 = $var4 ? $var6 : ''; unset( $var4, $var6 ); if (! isset( $var3 ) ) $var3 = NULL; while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); unset( $var4 ); unset( $var4 ); $var4 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'view_parameter_text', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['view_parameter_text'] : null; if (! isset( $var4 ) ) $var4 = NULL; while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); unset( $var5 ); unset( $var5 ); $var5 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri_suffix', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri_suffix'] : null; if (! isset( $var5 ) ) $var5 = NULL; while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); $var1 = ( $var2 . $var3 . $var4 . $var5 ); unset( $var2, $var3, $var4, $var5 ); if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); eZURI::transformURI( $var1, false, eZURI::getTransformURIMode() ); $var1 = '"' . $var1 . '"'; $var = $var1; unset( $var1 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $text .= $var; unset( $var ); $text .= '><span class="text">&laquo;&nbsp;Previous</span></a></span> '; } break; default: { $text .= ' <span class="previous"><span class="text disabled">&laquo;&nbsp;Previous</span></span> '; } break; } unset( $match ); unset( $vars[$currentNamespace]['match'] ); $text .= ' '; unset( $var ); unset( $var1 ); unset( $var1 ); $var1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'item_next', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['item_next'] : null; if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); unset( $var2 ); unset( $var2 ); $var2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_count', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_count'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); $var = ( ( $var1 ) < ( $var2 ) ); unset( $var1, $var2 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $vars[$currentNamespace]['match'] = $var; unset( $var ); unset( $match ); unset( $match1 ); unset( $match1 ); $match1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'item_next', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['item_next'] : null; if (! isset( $match1 ) ) $match1 = NULL; while ( is_object( $match1 ) and method_exists( $match1, 'templateValue' ) ) $match1 = $match1->templateValue(); while ( is_object( $match1 ) and method_exists( $match1, 'templateValue' ) ) $match1 = $match1->templateValue(); unset( $match2 ); unset( $match2 ); $match2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_count', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_count'] : null; if (! isset( $match2 ) ) $match2 = NULL; while ( is_object( $match2 ) and method_exists( $match2, 'templateValue' ) ) $match2 = $match2->templateValue(); while ( is_object( $match2 ) and method_exists( $match2, 'templateValue' ) ) $match2 = $match2->templateValue(); $match = ( ( $match1 ) < ( $match2 ) ); unset( $match1, $match2 ); if (! isset( $match ) ) $match = NULL; while ( is_object( $match ) and method_exists( $match, 'templateValue' ) ) $match = $match->templateValue(); switch ( $match ) { case 1: { $text .= ' <span class="next"><a href='; unset( $var ); unset( $var1 ); unset( $var2 ); unset( $var2 ); $var2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); unset( $var3 ); unset( $var3 ); $var3 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'offset_text', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['offset_text'] : null; if (! isset( $var3 ) ) $var3 = NULL; while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); unset( $var4 ); unset( $var4 ); $var4 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'item_next', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['item_next'] : null; if (! isset( $var4 ) ) $var4 = NULL; while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); unset( $var5 ); unset( $var5 ); $var5 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'view_parameter_text', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['view_parameter_text'] : null; if (! isset( $var5 ) ) $var5 = NULL; while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); unset( $var6 ); unset( $var6 ); $var6 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri_suffix', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri_suffix'] : null; if (! isset( $var6 ) ) $var6 = NULL; while ( is_object( $var6 ) and method_exists( $var6, 'templateValue' ) ) $var6 = $var6->templateValue(); while ( is_object( $var6 ) and method_exists( $var6, 'templateValue' ) ) $var6 = $var6->templateValue(); $var1 = ( $var2 . $var3 . $var4 . $var5 . $var6 ); unset( $var2, $var3, $var4, $var5, $var6 ); if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); eZURI::transformURI( $var1, false, eZURI::getTransformURIMode() ); $var1 = '"' . $var1 . '"'; $var = $var1; unset( $var1 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $text .= $var; unset( $var ); $text .= '><span class="text">Next&nbsp;&raquo;</span></a></span> '; } break; default: { $text .= ' <span class="next"><span class="text disabled">Next&nbsp;&raquo;</span></span> '; } break; } unset( $match ); unset( $vars[$currentNamespace]['match'] ); $text .= ' <span class="pages">'; // if begins unset( $if_cond ); unset( $if_cond1 ); unset( $if_cond1 ); $if_cond1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'current_page', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['current_page'] : null; if (! isset( $if_cond1 ) ) $if_cond1 = NULL; while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) ) $if_cond1 = $if_cond1->templateValue(); unset( $if_cond2 ); unset( $if_cond2 ); $if_cond2 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'left_max', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['left_max'] : null; if (! isset( $if_cond2 ) ) $if_cond2 = NULL; while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) ) $if_cond2 = $if_cond2->templateValue(); $if_cond = ( ( $if_cond1 ) > ( $if_cond2 ) ); unset( $if_cond1, $if_cond2 ); if (! isset( $if_cond ) ) $if_cond = NULL; while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) ) $if_cond = $if_cond->templateValue(); if ( $if_cond ) { $text .= '<a href='; unset( $var ); unset( $var1 ); unset( $var2 ); unset( $var2 ); $var2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); unset( $var3 ); unset( $var3 ); $var3 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'view_parameter_text', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['view_parameter_text'] : null; if (! isset( $var3 ) ) $var3 = NULL; while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); unset( $var4 ); unset( $var4 ); $var4 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri_suffix', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri_suffix'] : null; if (! isset( $var4 ) ) $var4 = NULL; while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); $var1 = ( $var2 . $var3 . $var4 ); unset( $var2, $var3, $var4 ); if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); eZURI::transformURI( $var1, false, eZURI::getTransformURIMode() ); $var1 = '"' . $var1 . '"'; $var = $var1; unset( $var1 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $text .= $var; unset( $var ); $text .= '>1</a>'; // if begins unset( $if_cond ); unset( $if_cond1 ); unset( $if_cond2 ); unset( $if_cond2 ); $if_cond2 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'current_page', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['current_page'] : null; if (! isset( $if_cond2 ) ) $if_cond2 = NULL; while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) ) $if_cond2 = $if_cond2->templateValue(); unset( $if_cond3 ); unset( $if_cond3 ); $if_cond3 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'left_length', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['left_length'] : null; if (! isset( $if_cond3 ) ) $if_cond3 = NULL; while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) ) $if_cond3 = $if_cond3->templateValue(); $if_cond1 = $if_cond2 - $if_cond3; unset( $if_cond2, $if_cond3 ); if (! isset( $if_cond1 ) ) $if_cond1 = NULL; while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) ) $if_cond1 = $if_cond1->templateValue(); $if_cond = ( ( $if_cond1 ) > ( 1 ) ); unset( $if_cond1 ); if (! isset( $if_cond ) ) $if_cond = NULL; while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) ) $if_cond = $if_cond->templateValue(); if ( $if_cond ) { $text .= '...'; } unset( $if_cond ); // if ends } unset( $if_cond ); // if ends $text .= ' '; unset( $loopItem ); unset( $loopItem ); $loopItem = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'left_length', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['left_length'] : null; if (! isset( $loopItem ) ) $loopItem = NULL; while ( is_object( $loopItem ) and method_exists( $loopItem, 'templateValue' ) ) $loopItem = $loopItem->templateValue(); if ( !isset( $sectionStack ) ) $sectionStack = array(); $index = 0; $currentIndex = 1; if ( is_array( $loopItem ) ) { $loopKeys = array_keys( $loopItem ); $loopCount = count( $loopKeys ); } else if ( is_numeric( $loopItem ) ) { $loopKeys = false; if ( $loopItem < 0 ) $loopCountValue = -$loopItem; else $loopCountValue = $loopItem; $loopCount = $loopCountValue - 0; } else if ( is_string( $loopItem ) ) { $loopKeys = false; $loopCount = strlen( $loopItem ) - 0; } else { $loopKeys = false; $loopCount = 0; } while ( $index < $loopCount ) { if ( is_array( $loopItem ) ) { $loopKey = $loopKeys[$index]; unset( $item ); $item = $loopItem[$loopKey]; } else if ( is_numeric( $loopItem ) ) { unset( $item ); $item = $index + 0 + 1; if ( $loopItem < 0 ) $item = -$item; $loopKey = $index + 0; } else if ( is_string( $loopItem ) ) { unset( $item ); $loopKey = $index + 0; $item = $loopItem[$loopKey]; } unset( $last ); $last = false; $vars[$currentNamespace]['key'] = $loopKey; $vars[$currentNamespace]['item'] = $item; $currentIndexInc = $currentIndex - 1; $vars[$currentNamespace]['index'] = $currentIndexInc; $vars[$currentNamespace]['number'] = $currentIndex; $sectionStack[] = array( &$loopItem, $loopKeys, $loopCount, $currentIndex, $index ); unset( $loopItem, $loopKeys ); $text .= ' '; unset( $var ); unset( $var1 ); unset( $var2 ); $namespace = $rootNamespace; if ( $namespace == '' ) $namespace = "ViewParameter"; else $namespace .= ':ViewParameter'; unset( $var2 ); $var2 = ( array_key_exists( $namespace, $vars ) and array_key_exists( 'current_page', $vars[$namespace] ) ) ? $vars[$namespace]['current_page'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); unset( $var3 ); $namespace = $rootNamespace; if ( $namespace == '' ) $namespace = "ViewParameter"; else $namespace .= ':ViewParameter'; unset( $var3 ); $var3 = ( array_key_exists( $namespace, $vars ) and array_key_exists( 'left_length', $vars[$namespace] ) ) ? $vars[$namespace]['left_length'] : null; if (! isset( $var3 ) ) $var3 = NULL; while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); $var1 = $var2 - $var3; unset( $var2, $var3 ); if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); unset( $var2 ); unset( $var2 ); $var2 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'index', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['index'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); $var = $var1 + $var2; unset( $var1, $var2 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $vars[$currentNamespace]['page_offset'] = $var; unset( $var ); $text .= ' <span class="other"><a href='; unset( $var ); unset( $var1 ); unset( $var2 ); unset( $var2 ); $var2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); unset( $var3 ); unset( $var4 ); unset( $var5 ); unset( $var5 ); $var5 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'page_offset', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['page_offset'] : null; if (! isset( $var5 ) ) $var5 = NULL; while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); $var4 = ( ( $var5 ) > ( 0 ) ); unset( $var5 ); if (! isset( $var4 ) ) $var4 = NULL; while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); unset( $var6 ); unset( $var7 ); unset( $var7 ); $var7 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'offset_text', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['offset_text'] : null; if (! isset( $var7 ) ) $var7 = NULL; while ( is_object( $var7 ) and method_exists( $var7, 'templateValue' ) ) $var7 = $var7->templateValue(); while ( is_object( $var7 ) and method_exists( $var7, 'templateValue' ) ) $var7 = $var7->templateValue(); unset( $var8 ); unset( $var9 ); unset( $var9 ); $var9 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'page_offset', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['page_offset'] : null; if (! isset( $var9 ) ) $var9 = NULL; while ( is_object( $var9 ) and method_exists( $var9, 'templateValue' ) ) $var9 = $var9->templateValue(); while ( is_object( $var9 ) and method_exists( $var9, 'templateValue' ) ) $var9 = $var9->templateValue(); unset( $var10 ); unset( $var10 ); $var10 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_limit', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_limit'] : null; if (! isset( $var10 ) ) $var10 = NULL; while ( is_object( $var10 ) and method_exists( $var10, 'templateValue' ) ) $var10 = $var10->templateValue(); while ( is_object( $var10 ) and method_exists( $var10, 'templateValue' ) ) $var10 = $var10->templateValue(); $var8 = $var9 * $var10; unset( $var9, $var10 ); if (! isset( $var8 ) ) $var8 = NULL; while ( is_object( $var8 ) and method_exists( $var8, 'templateValue' ) ) $var8 = $var8->templateValue(); $var6 = ( $var7 . $var8 ); unset( $var7, $var8 ); if (! isset( $var6 ) ) $var6 = NULL; while ( is_object( $var6 ) and method_exists( $var6, 'templateValue' ) ) $var6 = $var6->templateValue(); $var3 = $var4 ? $var6 : ''; unset( $var4, $var6 ); if (! isset( $var3 ) ) $var3 = NULL; while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); unset( $var4 ); $namespace = $rootNamespace; if ( $namespace == '' ) $namespace = "ViewParameter"; else $namespace .= ':ViewParameter'; unset( $var4 ); $var4 = ( array_key_exists( $namespace, $vars ) and array_key_exists( 'view_parameter_text', $vars[$namespace] ) ) ? $vars[$namespace]['view_parameter_text'] : null; if (! isset( $var4 ) ) $var4 = NULL; while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); unset( $var5 ); unset( $var5 ); $var5 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri_suffix', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri_suffix'] : null; if (! isset( $var5 ) ) $var5 = NULL; while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); $var1 = ( $var2 . $var3 . $var4 . $var5 ); unset( $var2, $var3, $var4, $var5 ); if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); eZURI::transformURI( $var1, false, eZURI::getTransformURIMode() ); $var1 = '"' . $var1 . '"'; $var = $var1; unset( $var1 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $text .= $var; unset( $var ); $text .= '>'; unset( $var ); unset( $var1 ); unset( $var1 ); $var1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'page_offset', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['page_offset'] : null; if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); $var = $var1 + 1; unset( $var1 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $text .= $var; unset( $var ); $text .= '</a></span> '; unset( $vars[$currentNamespace]['page_offset'] ); $text .= ' '; list( $loopItem, $loopKeys, $loopCount, $currentIndex, $index ) = array_pop( $sectionStack ); ++$currentIndex; ++$index; } unset( $loopKeys, $loopCount, $index, $last, $loopIndex, $loopItem ); $text .= ' <span class="current">'; unset( $var ); unset( $var1 ); unset( $var1 ); $var1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'current_page', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['current_page'] : null; if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); $var = $var1 + 1; unset( $var1 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $text .= $var; unset( $var ); $text .= '</span> '; unset( $loopItem ); unset( $loopItem ); $loopItem = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'right_length', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['right_length'] : null; if (! isset( $loopItem ) ) $loopItem = NULL; while ( is_object( $loopItem ) and method_exists( $loopItem, 'templateValue' ) ) $loopItem = $loopItem->templateValue(); if ( !isset( $sectionStack ) ) $sectionStack = array(); $index = 0; $currentIndex = 1; if ( is_array( $loopItem ) ) { $loopKeys = array_keys( $loopItem ); $loopCount = count( $loopKeys ); } else if ( is_numeric( $loopItem ) ) { $loopKeys = false; if ( $loopItem < 0 ) $loopCountValue = -$loopItem; else $loopCountValue = $loopItem; $loopCount = $loopCountValue - 0; } else if ( is_string( $loopItem ) ) { $loopKeys = false; $loopCount = strlen( $loopItem ) - 0; } else { $loopKeys = false; $loopCount = 0; } while ( $index < $loopCount ) { if ( is_array( $loopItem ) ) { $loopKey = $loopKeys[$index]; unset( $item ); $item = $loopItem[$loopKey]; } else if ( is_numeric( $loopItem ) ) { unset( $item ); $item = $index + 0 + 1; if ( $loopItem < 0 ) $item = -$item; $loopKey = $index + 0; } else if ( is_string( $loopItem ) ) { unset( $item ); $loopKey = $index + 0; $item = $loopItem[$loopKey]; } unset( $last ); $last = false; $vars[$currentNamespace]['key'] = $loopKey; $vars[$currentNamespace]['item'] = $item; $currentIndexInc = $currentIndex - 1; $vars[$currentNamespace]['index'] = $currentIndexInc; $vars[$currentNamespace]['number'] = $currentIndex; $sectionStack[] = array( &$loopItem, $loopKeys, $loopCount, $currentIndex, $index ); unset( $loopItem, $loopKeys ); $text .= ' '; unset( $var ); unset( $var1 ); $namespace = $rootNamespace; if ( $namespace == '' ) $namespace = "ViewParameter"; else $namespace .= ':ViewParameter'; unset( $var1 ); $var1 = ( array_key_exists( $namespace, $vars ) and array_key_exists( 'current_page', $vars[$namespace] ) ) ? $vars[$namespace]['current_page'] : null; if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); unset( $var2 ); unset( $var2 ); $var2 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'index', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['index'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); $var = $var1 + $var2 + 1.000000; unset( $var1, $var2 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $vars[$currentNamespace]['page_offset'] = $var; unset( $var ); $text .= ' <span class="other"><a href='; unset( $var ); unset( $var1 ); unset( $var2 ); unset( $var2 ); $var2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); unset( $var3 ); unset( $var4 ); unset( $var5 ); unset( $var5 ); $var5 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'page_offset', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['page_offset'] : null; if (! isset( $var5 ) ) $var5 = NULL; while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); $var4 = ( ( $var5 ) > ( 0 ) ); unset( $var5 ); if (! isset( $var4 ) ) $var4 = NULL; while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); unset( $var6 ); unset( $var7 ); unset( $var7 ); $var7 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'offset_text', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['offset_text'] : null; if (! isset( $var7 ) ) $var7 = NULL; while ( is_object( $var7 ) and method_exists( $var7, 'templateValue' ) ) $var7 = $var7->templateValue(); while ( is_object( $var7 ) and method_exists( $var7, 'templateValue' ) ) $var7 = $var7->templateValue(); unset( $var8 ); unset( $var9 ); unset( $var9 ); $var9 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'page_offset', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['page_offset'] : null; if (! isset( $var9 ) ) $var9 = NULL; while ( is_object( $var9 ) and method_exists( $var9, 'templateValue' ) ) $var9 = $var9->templateValue(); while ( is_object( $var9 ) and method_exists( $var9, 'templateValue' ) ) $var9 = $var9->templateValue(); unset( $var10 ); unset( $var10 ); $var10 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_limit', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_limit'] : null; if (! isset( $var10 ) ) $var10 = NULL; while ( is_object( $var10 ) and method_exists( $var10, 'templateValue' ) ) $var10 = $var10->templateValue(); while ( is_object( $var10 ) and method_exists( $var10, 'templateValue' ) ) $var10 = $var10->templateValue(); $var8 = $var9 * $var10; unset( $var9, $var10 ); if (! isset( $var8 ) ) $var8 = NULL; while ( is_object( $var8 ) and method_exists( $var8, 'templateValue' ) ) $var8 = $var8->templateValue(); $var6 = ( $var7 . $var8 ); unset( $var7, $var8 ); if (! isset( $var6 ) ) $var6 = NULL; while ( is_object( $var6 ) and method_exists( $var6, 'templateValue' ) ) $var6 = $var6->templateValue(); $var3 = $var4 ? $var6 : ''; unset( $var4, $var6 ); if (! isset( $var3 ) ) $var3 = NULL; while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); unset( $var4 ); $namespace = $rootNamespace; if ( $namespace == '' ) $namespace = "ViewParameter"; else $namespace .= ':ViewParameter'; unset( $var4 ); $var4 = ( array_key_exists( $namespace, $vars ) and array_key_exists( 'view_parameter_text', $vars[$namespace] ) ) ? $vars[$namespace]['view_parameter_text'] : null; if (! isset( $var4 ) ) $var4 = NULL; while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); unset( $var5 ); unset( $var5 ); $var5 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri_suffix', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri_suffix'] : null; if (! isset( $var5 ) ) $var5 = NULL; while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); $var1 = ( $var2 . $var3 . $var4 . $var5 ); unset( $var2, $var3, $var4, $var5 ); if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); eZURI::transformURI( $var1, false, eZURI::getTransformURIMode() ); $var1 = '"' . $var1 . '"'; $var = $var1; unset( $var1 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $text .= $var; unset( $var ); $text .= '>'; unset( $var ); unset( $var1 ); unset( $var1 ); $var1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'page_offset', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['page_offset'] : null; if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); $var = $var1 + 1; unset( $var1 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $text .= $var; unset( $var ); $text .= '</a></span> '; unset( $vars[$currentNamespace]['page_offset'] ); $text .= ' '; list( $loopItem, $loopKeys, $loopCount, $currentIndex, $index ) = array_pop( $sectionStack ); ++$currentIndex; ++$index; } unset( $loopKeys, $loopCount, $index, $last, $loopIndex, $loopItem ); // if begins unset( $if_cond ); unset( $if_cond1 ); unset( $if_cond1 ); $if_cond1 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'page_count', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['page_count'] : null; if (! isset( $if_cond1 ) ) $if_cond1 = NULL; while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) ) $if_cond1 = $if_cond1->templateValue(); unset( $if_cond2 ); unset( $if_cond3 ); unset( $if_cond3 ); $if_cond3 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'current_page', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['current_page'] : null; if (! isset( $if_cond3 ) ) $if_cond3 = NULL; while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) ) $if_cond3 = $if_cond3->templateValue(); unset( $if_cond4 ); unset( $if_cond4 ); $if_cond4 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'right_max', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['right_max'] : null; if (! isset( $if_cond4 ) ) $if_cond4 = NULL; while ( is_object( $if_cond4 ) and method_exists( $if_cond4, 'templateValue' ) ) $if_cond4 = $if_cond4->templateValue(); $if_cond2 = $if_cond3 + $if_cond4 + 1.000000; unset( $if_cond3, $if_cond4 ); if (! isset( $if_cond2 ) ) $if_cond2 = NULL; while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) ) $if_cond2 = $if_cond2->templateValue(); $if_cond = ( ( $if_cond1 ) > ( $if_cond2 ) ); unset( $if_cond1, $if_cond2 ); if (! isset( $if_cond ) ) $if_cond = NULL; while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) ) $if_cond = $if_cond->templateValue(); if ( $if_cond ) { // if begins unset( $if_cond ); unset( $if_cond1 ); unset( $if_cond2 ); unset( $if_cond2 ); $if_cond2 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'current_page', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['current_page'] : null; if (! isset( $if_cond2 ) ) $if_cond2 = NULL; while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) ) $if_cond2 = $if_cond2->templateValue(); unset( $if_cond3 ); unset( $if_cond3 ); $if_cond3 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'right_max', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['right_max'] : null; if (! isset( $if_cond3 ) ) $if_cond3 = NULL; while ( is_object( $if_cond3 ) and method_exists( $if_cond3, 'templateValue' ) ) $if_cond3 = $if_cond3->templateValue(); $if_cond1 = $if_cond2 + $if_cond3 + 2.000000; unset( $if_cond2, $if_cond3 ); if (! isset( $if_cond1 ) ) $if_cond1 = NULL; while ( is_object( $if_cond1 ) and method_exists( $if_cond1, 'templateValue' ) ) $if_cond1 = $if_cond1->templateValue(); unset( $if_cond2 ); unset( $if_cond2 ); $if_cond2 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'page_count', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['page_count'] : null; if (! isset( $if_cond2 ) ) $if_cond2 = NULL; while ( is_object( $if_cond2 ) and method_exists( $if_cond2, 'templateValue' ) ) $if_cond2 = $if_cond2->templateValue(); $if_cond = ( ( $if_cond1 ) < ( $if_cond2 ) ); unset( $if_cond1, $if_cond2 ); if (! isset( $if_cond ) ) $if_cond = NULL; while ( is_object( $if_cond ) and method_exists( $if_cond, 'templateValue' ) ) $if_cond = $if_cond->templateValue(); if ( $if_cond ) { $text .= '<span class="other">...</span>'; } unset( $if_cond ); // if ends $text .= '<span class="other"><a href='; unset( $var ); unset( $var1 ); unset( $var2 ); unset( $var2 ); $var2 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri'] : null; if (! isset( $var2 ) ) $var2 = NULL; while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); while ( is_object( $var2 ) and method_exists( $var2, 'templateValue' ) ) $var2 = $var2->templateValue(); unset( $var3 ); unset( $var4 ); unset( $var5 ); unset( $var6 ); unset( $var6 ); $var6 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'page_count', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['page_count'] : null; if (! isset( $var6 ) ) $var6 = NULL; while ( is_object( $var6 ) and method_exists( $var6, 'templateValue' ) ) $var6 = $var6->templateValue(); while ( is_object( $var6 ) and method_exists( $var6, 'templateValue' ) ) $var6 = $var6->templateValue(); $var5 = $var6 + -1; unset( $var6 ); if (! isset( $var5 ) ) $var5 = NULL; while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); $var4 = ( ( $var5 ) > ( 0 ) ); unset( $var5 ); if (! isset( $var4 ) ) $var4 = NULL; while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); unset( $var6 ); unset( $var7 ); unset( $var7 ); $var7 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'offset_text', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['offset_text'] : null; if (! isset( $var7 ) ) $var7 = NULL; while ( is_object( $var7 ) and method_exists( $var7, 'templateValue' ) ) $var7 = $var7->templateValue(); while ( is_object( $var7 ) and method_exists( $var7, 'templateValue' ) ) $var7 = $var7->templateValue(); unset( $var8 ); unset( $var9 ); unset( $var10 ); unset( $var10 ); $var10 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'page_count', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['page_count'] : null; if (! isset( $var10 ) ) $var10 = NULL; while ( is_object( $var10 ) and method_exists( $var10, 'templateValue' ) ) $var10 = $var10->templateValue(); while ( is_object( $var10 ) and method_exists( $var10, 'templateValue' ) ) $var10 = $var10->templateValue(); $var9 = $var10 + -1; unset( $var10 ); if (! isset( $var9 ) ) $var9 = NULL; while ( is_object( $var9 ) and method_exists( $var9, 'templateValue' ) ) $var9 = $var9->templateValue(); unset( $var10 ); unset( $var10 ); $var10 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'item_limit', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['item_limit'] : null; if (! isset( $var10 ) ) $var10 = NULL; while ( is_object( $var10 ) and method_exists( $var10, 'templateValue' ) ) $var10 = $var10->templateValue(); while ( is_object( $var10 ) and method_exists( $var10, 'templateValue' ) ) $var10 = $var10->templateValue(); $var8 = $var9 * $var10; unset( $var9, $var10 ); if (! isset( $var8 ) ) $var8 = NULL; while ( is_object( $var8 ) and method_exists( $var8, 'templateValue' ) ) $var8 = $var8->templateValue(); $var6 = ( $var7 . $var8 ); unset( $var7, $var8 ); if (! isset( $var6 ) ) $var6 = NULL; while ( is_object( $var6 ) and method_exists( $var6, 'templateValue' ) ) $var6 = $var6->templateValue(); $var3 = $var4 ? $var6 : ''; unset( $var4, $var6 ); if (! isset( $var3 ) ) $var3 = NULL; while ( is_object( $var3 ) and method_exists( $var3, 'templateValue' ) ) $var3 = $var3->templateValue(); unset( $var4 ); unset( $var4 ); $var4 = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'view_parameter_text', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['view_parameter_text'] : null; if (! isset( $var4 ) ) $var4 = NULL; while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); while ( is_object( $var4 ) and method_exists( $var4, 'templateValue' ) ) $var4 = $var4->templateValue(); unset( $var5 ); unset( $var5 ); $var5 = ( array_key_exists( $rootNamespace, $vars ) and array_key_exists( 'page_uri_suffix', $vars[$rootNamespace] ) ) ? $vars[$rootNamespace]['page_uri_suffix'] : null; if (! isset( $var5 ) ) $var5 = NULL; while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); while ( is_object( $var5 ) and method_exists( $var5, 'templateValue' ) ) $var5 = $var5->templateValue(); $var1 = ( $var2 . $var3 . $var4 . $var5 ); unset( $var2, $var3, $var4, $var5 ); if (! isset( $var1 ) ) $var1 = NULL; while ( is_object( $var1 ) and method_exists( $var1, 'templateValue' ) ) $var1 = $var1->templateValue(); eZURI::transformURI( $var1, false, eZURI::getTransformURIMode() ); $var1 = '"' . $var1 . '"'; $var = $var1; unset( $var1 ); if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $text .= $var; unset( $var ); $text .= '>'; unset( $var ); unset( $var ); $var = ( array_key_exists( $currentNamespace, $vars ) and array_key_exists( 'page_count', $vars[$currentNamespace] ) ) ? $vars[$currentNamespace]['page_count'] : null; if (! isset( $var ) ) $var = NULL; while ( is_object( $var ) and method_exists( $var, 'templateValue' ) ) $var = $var->templateValue(); $text .= ( is_object( $var ) ? compiledFetchText( $tpl, $rootNamespace, $currentNamespace, false, $var ) : $var ); unset( $var ); $text .= '</a></span>'; } unset( $if_cond ); // if ends $text .= ' </span> </p> <div class="break"></div> </div> '; } $text .= ' '; unset( $vars[$currentNamespace]['page_count'] ); unset( $vars[$currentNamespace]['current_page'] ); unset( $vars[$currentNamespace]['item_previous'] ); unset( $vars[$currentNamespace]['item_next'] ); unset( $vars[$currentNamespace]['left_length'] ); unset( $vars[$currentNamespace]['right_length'] ); unset( $vars[$currentNamespace]['view_parameter_text'] ); unset( $vars[$currentNamespace]['offset_text'] ); $currentNamespace = array_pop( $namespaceStack ); $namespace = $currentNamespace; if ( $namespace == '' ) $namespace = "ViewParameter"; else $namespace .= ':ViewParameter'; if ( isset( $setArray[$namespace]['page_uri_suffix'] ) ) { unset( $vars[$namespace]['page_uri_suffix'] ); } $namespace = $currentNamespace; if ( $namespace == '' ) $namespace = "ViewParameter"; else $namespace .= ':ViewParameter'; if ( isset( $setArray[$namespace]['left_max'] ) ) { unset( $vars[$namespace]['left_max'] ); } $namespace = $currentNamespace; if ( $namespace == '' ) $namespace = "ViewParameter"; else $namespace .= ':ViewParameter'; if ( isset( $setArray[$namespace]['right_max'] ) ) { unset( $vars[$namespace]['right_max'] ); } if ( isset( $setArray[$currentNamespace]['page_uri_suffix'] ) ) { unset( $vars[$currentNamespace]['page_uri_suffix'] ); } if ( isset( $setArray[$currentNamespace]['left_max'] ) ) { unset( $vars[$currentNamespace]['left_max'] ); } if ( isset( $setArray[$currentNamespace]['right_max'] ) ) { unset( $vars[$currentNamespace]['right_max'] ); } $text .= ' '; $setArray = $oldSetArray_99a3cecd353295a13123c0e522f2c6fe; $tpl->Level--; ?>
imadkaf/aYaville
ezpublish_legacy/var/ezdemo_site/cache/template/compiled/google-1c07b127ceff2e661bfb8ff17cd42902.php
PHP
gpl-2.0
66,608
'use strict'; const { expect } = require('chai'); const { getParsedSql } = require('./util'); describe('common table expressions', () => { it('should support single CTE', () => { const sql = ` WITH cte AS (SELECT 1) SELECT * FROM cte `.trim(); expect(getParsedSql(sql)).to.equal('WITH "cte" AS (SELECT 1) SELECT * FROM "cte"'); }); it('should support multiple CTE', () => { const expected = 'WITH "cte1" AS (SELECT 1), "cte2" AS (SELECT 2) ' + 'SELECT * FROM "cte1" UNION SELECT * FROM "cte2"'; const sql = ` WITH cte1 AS (SELECT 1), cte2 AS (SELECT 2) SELECT * FROM cte1 UNION SELECT * FROM cte2 `.trim(); expect(getParsedSql(sql)).to.equal(expected) }); it('should support CTE with column', () => { const sql = ` WITH cte (col1) AS (SELECT 1) SELECT * FROM cte `.trim(); expect(getParsedSql(sql)).to.contain('(col1)'); }); it('should support CTE with multiple columns', () => { const sql = ` WITH cte (col1, col2) AS (SELECT 1, 2) SELECT * FROM cte `.trim(); expect(getParsedSql(sql)).to.contain('(col1, col2)'); }); it('should support recursive CTE', () => { const sql = ` WITH RECURSIVE cte(n) AS ( SELECT 1 UNION SELECT n + 1 FROM cte WHERE n < 5 ) SELECT * FROM cte `.trim(); expect(getParsedSql(sql)).to.match(/^WITH RECURSIVE/); }); });
godmodelabs/flora-sql-parser
test/ast2sql/cte.js
JavaScript
gpl-2.0
1,628
"use strict"; /*** * critical element webgl demo by Silke Rohn and Benedikt Klotz * Source is the Basis applikation. * Added and changed functionalities: * @Benedikt: Objects, Lighting, particle systems, shader, blending and face culling * @Silke: particle system, changes to particle systems (Elements) */ var webgl = { gl: null, objects: [], time: 0.0, life: 250, objectAngle: 0, debug: true, maxAge: 5.0, /** * @author: Silke Rohn **/ elements: { HYDRO: -15, KALIUM: -15, TITAN: 35, FERRUM: 10, URAN: -15, CARBON: 10, MAGNESIUM: -20, OXID: -5, select: function() { var select = document.getElementById("select"); var value = select.selectedIndex; var objects = webgl.objects[2] switch(value) { case 0: webgl.life += this.FERRUM; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; if (objects.colors[0] <= 0.9) { for (var i = 0; i < objects.colors.length;i+=4) { objects.colors[i] += 0.01; objects.colors[i+1] += 0.01; } changed = true; } if(changed) { webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER,objects.colorObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.colors)); } break; case 1: webgl.life += this.OXID; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; if (objects.colors[0] <= 0.9) { for (var i = 0; i < objects.colors.length;i+=4) { objects.colors[i+1] += 0.1; } changed = true; } webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER, objects.colorObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.colors)); break; case 2: webgl.life += this.HYDRO; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; for (var i = 0; i < objects.velocities.length;i+=3) { objects.velocities[i] += 0.01; objects.velocities[i+1] += 0.01; } changed = true; webgl.maxAge += 0.5; webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER, objects.velocityObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.velocities)); break; case 3: webgl.life += this.URAN; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; for (var i = 0; i < objects.colors.length;i+=3) { objects.velocities[i] -= 0.01; objects.velocities[i+2] -= 0.01; } changed = true; if (webgl.maxAge <0.5){ window.alert("Die kritische Masse ist verschwunden!!!"); } webgl.maxAge -= 0.5; webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER, objects.velocityObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.velocities)); break; case 4: webgl.life += this.CARBON; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; for (var i = 0; i < objects.velocities.length;i+=3) { objects.velocities[i] -= 0.01; objects.velocities[i+1] -= 0.01; } changed = true; if (webgl.maxAge <0.5){ window.alert("Die kritische Masse ist verschwunden!!!"); } webgl.maxAge -= 0.5; webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER, objects.velocityObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.velocities)); break; case 5: webgl.life += this.TITAN; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; if (objects.colors[2] >= 0.1) { for (var i = 0; i < objects.colors.length;i+=4) { objects.colors[i+2] -= 0.1; } changed = true; } webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER, objects.colorObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.colors)); break; case 6: webgl.life += this.MAGNESIUM; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; if ((objects.colors[0] >= 0.1) && (objects.colors[1] >= 0.1)) { for (var i = 0; i < objects.colors.length;i+=4) { objects.colors[i] -= 0.1; objects.colors[i+1] -= 0.1; } changed = true; } webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER, objects.colorObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.colors)); break; case 7: webgl.life += this.KALIUM; if (webgl.life <0){ window.alert("Die kritische Masse ist explodiert!!!"); } var changed = false; for (var i = 0; i < webgl.objects[2].velocities.length;i+=3) { objects.velocities[i] += 0.01;//Math.random()*.1; objects.velocities[i+1] += 0.01;//Math.random()*.1; objects.velocities[i+2] += 0.01;//Math.random()*.1; } changed = true; if (webgl.maxAge <0.5){ window.alert("Die kritische Masse ist verschwunden!!!"); } webgl.maxAge -= 0.5; webgl.gl.bindBuffer(webgl.gl.ARRAY_BUFFER, objects.velocityObject); webgl.gl.bufferSubData(webgl.gl.ARRAY_BUFFER,0,new Float32Array(objects.velocities)); break; default: console.log("Error: unknown element"); } }, }, /** * Encapsulates Projection and Viewing matrix and some helper functions. **/ matrices: { projection: new J3DIMatrix4(), viewing: new J3DIMatrix4(), viewingTranslate: { x: 0, y: 0, z: 0 }, viewingRotations: { x: 0, y: 0, z: 0 }, /** * Initializes the Projection and the Viewing matrix. * Projection uses perspective projection with fove of 30.0, aspect of 1.0, near 1 and far 10000. * Viewing is set up as a translate of (0, 10, -50) and a rotate of 20 degrees around x and y axis. **/ init: function () { this.projection.perspective(30, 1.0, 1, 10000); this.viewingTranslate = { x: 0, y: 0, z: -5 }; this.viewingRotations = { x: 50, y: 0, z: 0 }; this.updateViewing.call(this); }, updateViewing: function() { var t = this.viewingTranslate; this.viewing = new J3DIMatrix4(); this.viewing.translate(t.x, t.y, t.z); var r = this.viewingRotations; this.viewing.scale(1.0,1.0,1.0) // 2.0,1.5,10.0 this.viewing.rotate(r.x, 1, 0, 0); this.viewing.rotate(r.y, 0, 1, 0); this.viewing.rotate(r.z, 0, 0, 1); }, zoomIn: function() { this.viewingTranslate.z -= 1; this.updateViewing(); }, zoomOut: function() { this.viewingTranslate.z += 1; this.updateViewing(); }, moveLeft: function() { this.viewingTranslate.x += 1; this.updateViewing(); }, moveRight: function() { this.viewingTranslate.x -= 1; this.updateViewing(); }, moveUp: function() { this.viewingTranslate.y += 1; this.updateViewing(); }, moveDown: function() { this.viewingTranslate.y -= 1; this.updateViewing(); }, rotateXAxis: function(offset) { this.viewingRotations.x = (this.viewingRotations.x + offset) % 360; this.updateViewing(); }, rotateYAxis: function(offset) { this.viewingRotations.y = (this.viewingRotations.y + offset) % 360; this.updateViewing(); }, rotateZAxis: function(offset) { this.viewingRotations.z = (this.viewingRotations.z + offset) % 360; this.updateViewing(); }, reset: function() { this.projection = new J3DIMatrix4(); this.viewing = new J3DIMatrix4(); this.init(); }, rotateObjectsLeft: function() { webgl.objectAngle = (webgl.objectAngle - 1) % 360; }, rotateObjectsRight: function() { webgl.objectAngle = (webgl.objectAngle + 1) % 360; }, }, /** * This message checks whether one of the error flags is set and * logs it to the console. If @p message is provided the message * is printed together with the error code. This allows to track * down an error by adding useful debug information to it. * * @param message Optional message printed together with the error. **/ checkError: function (message) { var errorToString = function(error) { switch (error) { case gl.NO_ERROR: return "NO_ERROR"; case gl.INVALID_ENUM: return "INVALID_ENUM"; case gl.INVALID_VALUE: return "INVALID_VALUE"; case gl.INVALID_OPERATION: return "INVALID_OPERATION"; case gl.OUT_OF_MEMORY: return "OUT_OF_MEMORY"; } return "UNKNOWN ERROR: " + error; }; var gl = webgl.gl; var error = gl.getError(); while (error !== gl.NO_ERROR) { if (message) { console.log(message + ": " + errorToString(error)); } else { console.log(errorToString(error)); } error = gl.getError(); } }, /** * This method logs information about the system: * @li VERSION * @li RENDERER * @li VENDOR * @li UNMASKED_RENDERER_WEBGL (Extension WEBGL_debug_renderer_info) * @li UNMASKED_VENDOR_WEBGL (Extension WEBGL_debug_renderer_info) * @li supportedExtensions **/ systemInfo: function () { var gl = webgl.gl; console.log("Version: " + gl.getParameter(gl.VERSION)); console.log("Renderer: " + gl.getParameter(gl.RENDERER)); console.log("Vendor: " + gl.getParameter(gl.VENDOR)); var extensions = gl.getSupportedExtensions(); for (var i = 0; i < extensions.length; i++) { if (extensions[i] == "WEBGL_debug_renderer_info") { var renderInfo = gl.getExtension("WEBGL_debug_renderer_info"); if (renderInfo) { console.log("Unmasked Renderer: " + gl.getParameter(renderInfo.UNMASKED_RENDERER_WEBGL)); console.log("Unmasked Vendor: " + gl.getParameter(renderInfo.UNMASKED_VENDOR_WEBGL)); } } } console.log("Extensions: "); console.log(extensions); }, /** * Creates a shader program out of @p vertex and @p fragment shaders. * * In case the linking of the shader program fails the programInfoLog is * logged to the console. * * @param vertex The compiled and valid WebGL Vertex Shader * @param fragment The compiled and valid WebGL Fragment Shader * @returns The linked WebGL Shader Program **/ createProgram: function (vertex, fragment) { var gl = webgl.gl; var shader = gl.createProgram(); gl.attachShader(shader, vertex); gl.attachShader(shader, fragment); gl.linkProgram(shader); gl.validateProgram(shader); var log = gl.getProgramInfoLog(shader); if (log != "") { console.log(log); } webgl.checkError("create Program"); return shader; }, /** * Generic method to render any @p object with any @p shader as TRIANGLES. * * This method can enable vertex, normal and texCoords depending on whether they * are defined in the @p object and @p shader. Everything is added in a completely * optional way, so there is no chance that an incorrect VertexAttribArray gets * enabled. * * Changes by: Benedikt Klotz * * The @p object can provide the following elements: * @li loaded: boolean indicating whether the object is completely loaded * @li blending: boolean indicating whether blending needs to be enabled * @li texture: texture object to bind if valid * @li vertexObject: ARRAY_BUFFER with three FLOAT values (x, y, z) * @li normalObject: ARRAY_BUFFER with three FLOAT values (x, y, z) * @li texCoordObject: ARRAY_BUFFER with two FLOAT values (s, t) * @li indexObject: ELEMENT_ARRAY_BUFFER * @li numIndices: Number of indices in indexObject * @li indexSize: The type of the index, must be one of GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT or GL_UNSIGNED_INT * * The @p shader can provide the following elements: * @li vertexLocation: attribute location for the vertexObject * @li normalLocation: attribute location for the normalObject * @li texCoordsLocation: attribute location for the texCoordsLocation * * It is expected that the shader program encapsulated in @p shader is already in use. **/ drawObject: function (gl, object, shader) { if (object.loaded === false) { // not yet loaded, don't render return; } // Set Time if(object.particle == true) { gl.uniform1f(shader.timeLocation, this.time); gl.uniform1f(shader.ageLocation, this.maxAge); } if (object.texture !== undefined) { gl.bindTexture(gl.TEXTURE_2D, object.texture); } if (shader.vertexLocation !== undefined && object.vertexObject !== undefined) { gl.enableVertexAttribArray(shader.vertexLocation); gl.bindBuffer(gl.ARRAY_BUFFER, object.vertexObject); gl.vertexAttribPointer(shader.vertexLocation, 3, gl.FLOAT, false, 0, 0); } // start: Particle System related Attributes if (shader.colorLocation !== undefined && object.colorObject !== undefined) { gl.enableVertexAttribArray(shader.colorLocation); gl.bindBuffer(gl.ARRAY_BUFFER, object.colorObject); gl.vertexAttribPointer(shader.colorLocation, 4, gl.FLOAT, false, 0, 0); } if (shader.velocityLocation !== undefined && object.velocityObject !== undefined) { gl.enableVertexAttribArray(shader.velocityLocation); gl.bindBuffer(gl.ARRAY_BUFFER, object.velocityObject); gl.vertexAttribPointer(shader.velocityLocation, 3, gl.FLOAT, false, 0, 0); } if (shader.startTimeLocation !== undefined && object.startTimeObject !== undefined) { gl.enableVertexAttribArray(shader.startTimeLocation); gl.bindBuffer(gl.ARRAY_BUFFER, object.startTimeObject); gl.vertexAttribPointer(shader.startTimeLocation, 1, gl.FLOAT, false, 0, 0); } if(object.particle == true) { gl.drawArrays(gl.POINTS, 0, object.particleObject.length); } // End: Particle System related Attributes if (shader.normalLocation !== undefined && object.normalObject !== undefined) { gl.enableVertexAttribArray(shader.normalLocation); gl.bindBuffer(gl.ARRAY_BUFFER, object.normalObject); gl.vertexAttribPointer(shader.normalLocation, 3, gl.FLOAT, false, 0, 0); } if (shader.texCoordsLocation !== undefined && object.texCoordObject !== undefined) { gl.enableVertexAttribArray(shader.texCoordsLocation); gl.bindBuffer(gl.ARRAY_BUFFER, object.texCoordObject); gl.vertexAttribPointer(shader.texCoordsLocation, 2, gl.FLOAT, false, 0, 0); } // Activate blending if (object.blending !== undefined && object.blending === true) { gl.blendFunc(gl.SRC_ALPHA, gl.ONE); // gl.enable(gl.BLEND); gl.uniform1f(shader.alphaLocation, 0.8); gl.disable(gl.DEPTH_TEST); // Set Alpha if blending for object is not activated } else{ gl.uniform1f(shader.alphaLocation, 1.0); } // Activate culling if(object.culling !== undefined && object.culling === true) { gl.enable(gl.CULL_FACE); gl.cullFace(gl.FRONT); } if (object.indexObject !== undefined && object.numIndices !== undefined && object.indexSize !== undefined) { gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, object.indexObject); gl.drawElements(gl.TRIANGLES, object.numIndices, object.indexSize, 0); } gl.bindTexture(gl.TEXTURE_2D, null); // Disbale Culling and enable Depth Test if (object.blending !== undefined && object.blending === true) { gl.enable(gl.DEPTH_TEST); gl.disable(gl.BLEND); } // Disable Culling if(object.culling !== undefined && object.culling === true) { gl.disable(gl.CULL_FACE); } }, repaintLoop: { frameRendering: false, setup: function() { var render = function(){ if (webgl.repaintLoop.frameRendering) { return; } webgl.repaintLoop.frameRendering = true; webgl.angle = (webgl.angle + 1) % 360; for (var i = 0; i < webgl.objects.length; i++) { var object = webgl.objects[i]; if (object.update === undefined) { continue; } object.update.call(object); } webgl.time += 16/1000; webgl.displayFunc.call(webgl); webgl.repaintLoop.frameRendering = false; window.requestAnimFrame(render); }; window.requestAnimFrame(render); render(); }, }, createShader: function (gl, type, source) { var shader = gl.createShader(type); gl.shaderSource(shader, source); gl.compileShader(shader); var log = gl.getShaderInfoLog(shader); if (log != "") { console.log(log); } webgl.checkError("create shader " + source); return shader; }, /** * Create a texture shader with Lighting enabled * * @author: Benedikt Klotz **/ createObjectShader: function() { var gl = this.gl; var shader = { program: -1, loaded: false, mvpLocation: -1, textureLocation: -1, vertexLocation: -1, texCoordsLocation: -1, lightDirLocation: -1, create: function() { if (this.vertexShader === undefined || this.fragmentShader === undefined) { return; } var program = webgl.createProgram(this.vertexShader, this.fragmentShader); this.program = program; this.use(); // resolve locations this.normalMatrixLocation = gl.getUniformLocation(program, "u_normalMatrix"), this.lightDirLocation = gl.getUniformLocation(program, "u_lightDir"), this.mvpLocation = gl.getUniformLocation(program, "modelViewProjection"), this.textureLocation = gl.getUniformLocation(program, "u_texture"), this.vertexLocation = gl.getAttribLocation(program, "vertex"), this.texCoordsLocation = gl.getAttribLocation(program, "texCoords"), this.alphaLocation = gl.getUniformLocation(program, "uAlpha"); // set uniform gl.uniform1i(this.textureLocation, 0); gl.uniform3f(this.lightDirLocation, 1.0, 1.0, 1.0); this.loaded = true; }, use: function () { gl.useProgram(this.program); } }; $.get("shaders/texture/vertex.glsl", function(data, response) { shader.vertexShader = webgl.createShader(webgl.gl, webgl.gl.VERTEX_SHADER, data); shader.create.call(shader); }, "html"); $.get("shaders/texture/fragment.glsl", function(data, response) { shader.fragmentShader = webgl.createShader(webgl.gl, webgl.gl.FRAGMENT_SHADER, data); shader.create.call(shader); }, "html"); return shader; }, /** * Create a special shader for the Particle System * * @author: Benedikt Klotz **/ createParticleShader: function () { var gl = this.gl; var shader = { program: -1, loaded: false, mvpLocation: -1, vertexLocation: -1, dirLocation: -1, create: function() { if (this.vertexShader === undefined || this.fragmentShader === undefined) { return; } var program = webgl.createProgram(this.vertexShader, this.fragmentShader); this.program = program; this.use(); var shader = {}; // resolve locations this.mvpLocation = gl.getUniformLocation(program, "modelViewProjection"), this.timeLocation = gl.getUniformLocation(program, "u_time"), this.vertexLocation = gl.getAttribLocation(program, "vertex"), this.ageLocation = gl.getUniformLocation(program, "maxAlter"); this.colorLocation = gl.getAttribLocation(program, "initialColor"), this.velocityLocation = gl.getAttribLocation(program, "velocity"), this.startTimeLocation = gl.getAttribLocation(program, "startTime"), this.sizeLocation = gl.getAttribLocation(program, "size"), this.loaded = true; }, use: function () { gl.useProgram(this.program); } }; $.get("shaders/particle/vertex.glsl", function(data) { shader.vertexShader = webgl.createShader(webgl.gl, webgl.gl.VERTEX_SHADER, data); shader.create.call(shader); }, "html"); $.get("shaders/particle/fragment.glsl", function(data) { shader.fragmentShader = webgl.createShader(webgl.gl, webgl.gl.FRAGMENT_SHADER, data); shader.create.call(shader); }, "html"); return shader; }, setupKeyHandler: function() { var m = this.matrices; $("body").keydown(function (event) { switch (event.keyCode) { case 107: m.zoomOut.call(m); break; case 109: m.zoomIn.call(m); break; case 39: if (event.shiftKey) { m.rotateZAxis.call(m, 1); } else { m.moveLeft.call(m); /** disabled * m.rotateObjectsLeft.call(m); **/ } break; case 37: if (event.shiftKey) { m.rotateZAxis.call(m, -1); } else { m.moveRight.call(m); /** disabled * m.rotateObjectsRight.call(m); **/ } break; case 38: if (event.shiftKey) { m.rotateXAxis.call(m, 1); } else { m.moveUp.call(m); } break; case 40: if (event.shiftKey) { m.rotateXAxis.call(m, -1); } else { m.moveDown.call(m); } break; case 82: m.reset.call(m); break; } }); }, /** * Create ground object * * @author: Benedikt Klotz */ makeGround: function (gl){ var buffer = { }; // vertices array var vertices = [ -1,-1,-1, 1,-1,-1, 1,-1, 1, -1,-1, 1 ]; // normal array var normals = [ 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0 ]; // texCoord array var texCoords = [ 0, 0, 1, 0, 1, 1, 0, 1 ]; // index array var indices = [ 0, 1, 2, 0, 2, 3 ]; buffer.vertexObject = this.createBuffer_f32(gl, vertices); buffer.texCoordObject = this.createBuffer_f32(gl, texCoords); buffer.normalObject = this.createBuffer_f32(gl,normals); buffer.indexObject = this.createBuffer_ui8(gl, indices); buffer.numIndices = indices.length; return buffer; }, /** * create an upwards open box * * @author: Benedikt Klotz **/ makeOpenBox: function (gl){ var buffer = { }; // vertices array var vertices = [ 1, 1, 1, -1, 1, 1, -1,-1, 1, 1,-1, 1, // v0-v1-v2-v3 front 1, 1, 1, 1,-1, 1, 1,-1,-1, 1, 1,-1, // v0-v3-v4-v5 right 1, 1, 1, 1, 1,-1, -1, 1,-1, -1, 1, 1, // v0-v5-v6-v1 top -1, 1, 1, -1, 1,-1, -1,-1,-1, -1,-1, 1, // v1-v6-v7-v2 left -1,-1,-1, 1,-1,-1, 1,-1, 1, -1,-1, 1, // v7-v4-v3-v2 bottom 1,-1,-1, -1,-1,-1, -1, 1,-1, 1, 1,-1 ]; // v4-v7-v6-v5 back // normal array var normals = [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, // v0-v1-v2-v3 front 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, // v0-v3-v4-v5 right 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // v0-v5-v6-v1 top -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // v1-v6-v7-v2 left 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, // v7-v4-v3-v2 bottom 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1 ]; // v4-v7-v6-v5 back // texCoord array var texCoords = [ 1, 1, 0, 1, 0, 0, 1, 0, // v0-v1-v2-v3 front 0, 1, 0, 0, 1, 0, 1, 1, // v0-v3-v4-v5 right 1, 0, 1, 1, 0, 1, 0, 0, // v0-v5-v6-v1 top 1, 1, 0, 1, 0, 0, 1, 0, // v1-v6-v7-v2 left 0, 0, 1, 0, 1, 1, 0, 1, // v7-v4-v3-v2 bottom 0, 0, 1, 0, 1, 1, 0, 1 ]; // v4-v7-v6-v5 back // index array var indices = [ 0, 1, 2, 0, 2, 3, // front 4, 5, 6, 4, 6, 7, // right 12,13,14, 12,14,15, // left 16,17,18, 16,18,19, // bottom 20,21,22, 20,22,23 ]; // back buffer.vertexObject = this.createBuffer_f32(gl, vertices); buffer.texCoordObject = this.createBuffer_f32(gl, texCoords); buffer.normalObject = this.createBuffer_f32(gl,normals); buffer.indexObject = this.createBuffer_ui8(gl, indices); buffer.numIndices = indices.length; return buffer; }, /** * * Create Buffer Objects in Bit Size 8 and 32 in float and unsigned int. * The function with a d is used for dynamic draws * * @author: Benedikt Klotz **/ createBuffer_f32: function (gl, data) { var vbo = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vbo); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); return vbo; }, createBuffer_f32_d: function (gl, data) { var vbo = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vbo); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); return vbo; }, createBuffer_ui8: function (gl, data) { var vbo = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, vbo); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint8Array(data), gl.STATIC_DRAW); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); return vbo; }, /** * Create a particle system, whose particle are black and are going in all directions * * @author: Benedikt Klotz, Silke Rohn **/ createParticle: function (dir) { var particle = {}; particle.position = [1, 1, 1]; switch(dir) { case 0: particle.velocity = [Math.random()*.1, Math.random()*.1, Math.random()*.1]; break; case 1: particle.velocity = [-Math.random()*.1, Math.random()*.1, Math.random()*.1]; break; case 2: particle.velocity = [Math.random()*.1, -Math.random()*.1, Math.random()*.1]; break; case 3: particle.velocity = [Math.random()*.1, Math.random()*.1, -Math.random()*.1]; break; case 4: particle.velocity = [-Math.random()*.1, -Math.random()*.1, Math.random()*.1]; break; case 5: particle.velocity = [-Math.random()*.1, Math.random()*.1, -Math.random()*.1]; break; case 6: particle.velocity = [Math.random()*.1, -Math.random()*.1, -Math.random()*.1]; break; case 7: particle.velocity = [-Math.random()*.1, -Math.random()*.1, -Math.random()*.1]; break; default: console.log("Error - particle creation: Unknown Direction - " + dir); break; } // start with black particles particle.color = [0.0, 0.0, 0.0, 1.0]; particle.startTime = Math.random() * 10 + 1; return particle; }, createParticelSystem: function(gl) { var particles = []; for (var i=0, dir=0; i<100000; i++, dir++) { if(dir == 8) { dir=0; } particles.push(this.createParticle(dir)); } var vertices = []; var velocities = []; var colors = []; var startTimes = []; var dirs = []; for (i=0; i<particles.length; i++) { var particle = particles[i]; vertices.push(particle.position[0]); vertices.push(particle.position[1]); vertices.push(particle.position[2]); velocities.push(particle.velocity[0]); velocities.push(particle.velocity[1]); velocities.push(particle.velocity[2]); colors.push(particle.color[0]); colors.push(particle.color[1]); colors.push(particle.color[2]); colors.push(particle.color[3]); startTimes.push(particle.startTime); dirs.push(particle.dir); } // create gl Buffer for particles var buffer = { }; buffer.particleObject = particles; buffer.vertexObject = this.createBuffer_f32(gl, vertices); buffer.velocityObject = this.createBuffer_f32_d(gl, velocities); buffer.colorObject = this.createBuffer_f32_d(gl, colors); buffer.startTimeObject = this.createBuffer_f32_d(gl, startTimes); buffer.dirObject = this.createBuffer_f32(gl, dirs); // save object properties for update later buffer.velocities = velocities; buffer.startTimes = startTimes; buffer.colors = colors; buffer.particle = true; return buffer; }, loadTexture: function(gl, path, object) { var texture = gl.createTexture(); var image = new Image(); g_loadingImages.push(image); image.onload = function() { webgl.doLoadTexture.call(webgl, gl, image, texture, object) } image.src = path; return texture; }, doLoadTexture: function(gl, image, texture, object) { g_loadingImages.splice(g_loadingImages.indexOf(image), 1); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); // Set Texture Parameter gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.bindTexture(gl.TEXTURE_2D, null); // Set texture loaded object.loaded = true; }, /** * Initialize all systems and objects * * @author: Benedikt Klotz **/ init: function (canvasName, vertexShaderName, fragmentShaderName) { var canvas, gl; // Setup Error reporting $(document).ajaxError(function(e,xhr,opt){ console.log("Error requesting " + opt.url + ": " + xhr.status + " " + xhr.statusText); }); // setup the API canvas = document.getElementById(canvasName); gl = canvas.getContext("experimental-webgl",{premultipliedAlpha:false}); this.gl = gl; gl.viewport(0, 0, canvas.width, canvas.height); // make background blue gl.clearColor(0.0, 0.0, 0.5, 0.6); gl.enable(gl.DEPTH_TEST); this.systemInfo(); // create the projection matrix this.matrices.init.call(this.matrices); // ground objects var object = this.makeGround.call(this, gl) object.indexSize = gl.UNSIGNED_BYTE; object.name = "ground"; object.blending = false; // Enable Front Face Culling object.culling = true; object.texture = this.loadTexture.call(this, gl, "textures/metall.jpg", object); object.shader = this.createObjectShader(); object.model = function() { var model = new J3DIMatrix4(); model.scale(1.6,1.2,1.8) model.rotate(this.objectAngle, 0.0, 1.0, 0.0); return model }; this.objects[this.objects.length] = object; // create a open box object = this.makeOpenBox.call(this, gl); object.indexSize = gl.UNSIGNED_BYTE; object.name = "box"; // enable object blending object.blending = true; object.texture = this.loadTexture.call(this, gl, "textures/glas.jpg", object); object.shader = this.createObjectShader(); object.model = function() { var model = new J3DIMatrix4(); model.scale(0.5,0.5,0.5) model.translate(0,-1.39,0); model.rotate(this.objectAngle, 0.0, 1.0, 0.0); return model; }; this.objects[this.objects.length] = object; // particle objects var object = this.createParticelSystem(gl) object.shader = this.createParticleShader(); object.loaded = true; object.blending = true; object.model = function() { var model = new J3DIMatrix4(); model.translate(-1.0,-1.7,-1.0); model.rotate(this.objectAngle, 0.0, 1.0, 0.0); return model; }; // Reset particle startTime if there are discarded setInterval(function() { var particles = object.particleObject; var changed = false; for (var i=0; i<particles.length; i++) { if(object.startTimes[i] + 7.0 <= webgl.time) { object.startTimes[i] = webgl.time + 3.0*Math.random(); changed = true; } } if(changed) { gl.bindBuffer(gl.ARRAY_BUFFER,object.startTimeObject); gl.bufferSubData(gl.ARRAY_BUFFER, 0, new Float32Array(object.startTimes)); } }, 1000); this.objects[this.objects.length] = object; // setup animation this.repaintLoop.setup.call(this); if(this.debug) { // setup handlers this.setupKeyHandler(); } }, displayFunc: function () { var gl = this.gl; gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); for (var i = 0; i < this.objects.length; i++) { var object, shader, modelView, normalMatrix, modelViewProjection; object = this.objects[i]; if (object.shader === undefined) { // no shader is set, cannot render continue; } if (object.shader.loaded !== undefined && object.shader.loaded === false) { // shader not yet loaded continue; } shader = object.shader; shader.use(); // create the matrices modelViewProjection = new J3DIMatrix4(this.matrices.projection); modelView = new J3DIMatrix4(this.matrices.viewing); if (object.model !== undefined) { modelView.multiply(object.model.call(this)); } modelViewProjection.multiply(modelView); if (shader.mvpLocation !== undefined) { modelViewProjection.setUniform(gl, shader.mvpLocation, false); } if (shader.normalMatrixLocation) { normalMatrix = new J3DIMatrix4(); normalMatrix.load(modelView); normalMatrix.invert(); normalMatrix.transpose(); normalMatrix.setUniform(gl, shader.normalMatrixLocation, false) } this.drawObject(gl, object, shader); this.checkError("drawObject: " + i); } this.checkError("displayFunc"); } };
Streamstormer/webGL-project
js/webgl.js
JavaScript
gpl-2.0
37,180
/* * Qt Authentication Library * Copyright (C) 2013 Martin Bříza <mbriza@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "Auth.h" #include "Constants.h" #include "AuthMessages.h" #include "SafeDataStream.h" #include <QtCore/QProcess> #include <QtCore/QUuid> #include <QtNetwork/QLocalServer> #include <QtNetwork/QLocalSocket> #include <QtQml/QtQml> #include <memory> #include <unistd.h> namespace SDDM { class Auth::SocketServer : public QLocalServer { Q_OBJECT public slots: void handleNewConnection(); public: static SocketServer *instance(); QMap<qint64, Auth::Private*> helpers; private: SocketServer(); }; class Auth::Private : public QObject { Q_OBJECT public: Private(Auth *parent); ~Private(); void setSocket(QLocalSocket *socket); public slots: void dataPending(); void childExited(int exitCode, QProcess::ExitStatus exitStatus); void childError(QProcess::ProcessError error); void requestFinished(); public: AuthRequest *request { nullptr }; QProcess *child { nullptr }; QLocalSocket *socket { nullptr }; QString displayServerCmd; QString sessionPath { }; QString user { }; QString cookie { }; bool autologin { false }; bool greeter { false }; QProcessEnvironment environment { }; qint64 id { 0 }; static qint64 lastId; }; qint64 Auth::Private::lastId = 1; Auth::SocketServer::SocketServer() : QLocalServer() { connect(this, &QLocalServer::newConnection, this, &Auth::SocketServer::handleNewConnection); } void Auth::SocketServer::handleNewConnection() { while (hasPendingConnections()) { Msg m = Msg::MSG_UNKNOWN; qint64 id; QLocalSocket *socket = nextPendingConnection(); SafeDataStream str(socket); str.receive(); str >> m >> id; if (m == Msg::HELLO && id && SocketServer::instance()->helpers.contains(id)) { helpers[id]->setSocket(socket); if (socket->bytesAvailable() > 0) helpers[id]->dataPending(); } } } Auth::SocketServer* Auth::SocketServer::instance() { static std::unique_ptr<Auth::SocketServer> self; if (!self) { self.reset(new SocketServer()); self->listen(QStringLiteral("sddm-auth%1").arg(QUuid::createUuid().toString().replace(QRegExp(QStringLiteral("[{}]")), QString()))); } return self.get(); } Auth::Private::Private(Auth *parent) : QObject(parent) , request(new AuthRequest(parent)) , child(new QProcess(this)) , id(lastId++) { SocketServer::instance()->helpers[id] = this; QProcessEnvironment env = child->processEnvironment(); bool langEmpty = true; QFile localeFile(QStringLiteral("/etc/locale.conf")); if (localeFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream in(&localeFile); while (!in.atEnd()) { QStringList parts = in.readLine().split(QLatin1Char('=')); if (parts.size() >= 2) { env.insert(parts[0], parts[1]); if (parts[0] == QLatin1String("LANG")) langEmpty = false; } } localeFile.close(); } if (langEmpty) env.insert(QStringLiteral("LANG"), QStringLiteral("C")); child->setProcessEnvironment(env); connect(child, QOverload<int,QProcess::ExitStatus>::of(&QProcess::finished), this, &Auth::Private::childExited); connect(child, &QProcess::errorOccurred, this, &Auth::Private::childError); connect(request, &AuthRequest::finished, this, &Auth::Private::requestFinished); connect(request, &AuthRequest::promptsChanged, parent, &Auth::requestChanged); } Auth::Private::~Private() { SocketServer::instance()->helpers.remove(id); } void Auth::Private::setSocket(QLocalSocket *socket) { this->socket = socket; connect(socket, &QLocalSocket::readyRead, this, &Auth::Private::dataPending); } void Auth::Private::dataPending() { Auth *auth = qobject_cast<Auth*>(parent()); Msg m = MSG_UNKNOWN; SafeDataStream str(socket); str.receive(); str >> m; switch (m) { case ERROR: { QString message; Error type = ERROR_NONE; str >> message >> type; Q_EMIT auth->error(message, type); break; } case INFO: { QString message; Info type = INFO_NONE; str >> message >> type; Q_EMIT auth->info(message, type); break; } case REQUEST: { Request r; str >> r; request->setRequest(&r); break; } case AUTHENTICATED: { QString user; str >> user; if (!user.isEmpty()) { auth->setUser(user); Q_EMIT auth->authentication(user, true); str.reset(); str << AUTHENTICATED << environment << cookie; str.send(); } else { Q_EMIT auth->authentication(user, false); } break; } case SESSION_STATUS: { bool status; str >> status; Q_EMIT auth->sessionStarted(status); str.reset(); str << SESSION_STATUS; str.send(); break; } case DISPLAY_SERVER_STARTED: { QString displayName; str >> displayName; Q_EMIT auth->displayServerReady(displayName); str.reset(); str << DISPLAY_SERVER_STARTED; str.send(); break; } default: { Q_EMIT auth->error(QStringLiteral("Auth: Unexpected value received: %1").arg(m), ERROR_INTERNAL); } } } void Auth::Private::childExited(int exitCode, QProcess::ExitStatus exitStatus) { if (exitStatus != QProcess::NormalExit) { qWarning("Auth: sddm-helper (%s) crashed (exit code %d)", qPrintable(child->arguments().join(QLatin1Char(' '))), HelperExitStatus(exitStatus)); Q_EMIT qobject_cast<Auth*>(parent())->error(child->errorString(), ERROR_INTERNAL); } if (exitCode == HELPER_SUCCESS) qDebug() << "Auth: sddm-helper exited successfully"; else qWarning("Auth: sddm-helper exited with %d", exitCode); Q_EMIT qobject_cast<Auth*>(parent())->finished((Auth::HelperExitStatus)exitCode); } void Auth::Private::childError(QProcess::ProcessError error) { Q_UNUSED(error); Q_EMIT qobject_cast<Auth*>(parent())->error(child->errorString(), ERROR_INTERNAL); } void Auth::Private::requestFinished() { SafeDataStream str(socket); Request r = request->request(); str << REQUEST << r; str.send(); request->setRequest(); } Auth::Auth(const QString &user, const QString &session, bool autologin, QObject *parent, bool verbose) : QObject(parent) , d(new Private(this)) { setUser(user); setAutologin(autologin); setSession(session); setVerbose(verbose); } Auth::Auth(QObject* parent) : QObject(parent) , d(new Private(this)) { } Auth::~Auth() { delete d; } void Auth::registerTypes() { qmlRegisterAnonymousType<AuthPrompt>("Auth", 1); qmlRegisterAnonymousType<AuthRequest>("Auth", 1); qmlRegisterType<Auth>("Auth", 1, 0, "Auth"); } bool Auth::autologin() const { return d->autologin; } bool Auth::isGreeter() const { return d->greeter; } const QString& Auth::cookie() const { return d->cookie; } const QString &Auth::session() const { return d->sessionPath; } const QString &Auth::user() const { return d->user; } bool Auth::verbose() const { return d->child->processChannelMode() == QProcess::ForwardedChannels; } AuthRequest *Auth::request() { return d->request; } bool Auth::isActive() const { return d->child->state() != QProcess::NotRunning; } void Auth::insertEnvironment(const QProcessEnvironment &env) { d->environment.insert(env); } void Auth::insertEnvironment(const QString &key, const QString &value) { d->environment.insert(key, value); } void Auth::setCookie(const QString& cookie) { if (cookie != d->cookie) { d->cookie = cookie; Q_EMIT cookieChanged(); } } void Auth::setUser(const QString &user) { if (user != d->user) { d->user = user; Q_EMIT userChanged(); } } void Auth::setAutologin(bool on) { if (on != d->autologin) { d->autologin = on; Q_EMIT autologinChanged(); } } void Auth::setGreeter(bool on) { if (on != d->greeter) { d->greeter = on; Q_EMIT greeterChanged(); } } void Auth::setDisplayServerCommand(const QString &command) { if (d->displayServerCmd != command) { d->displayServerCmd = command; Q_EMIT displayServerCommandChanged(); } } void Auth::setSession(const QString& path) { if (path != d->sessionPath) { d->sessionPath = path; Q_EMIT sessionChanged(); } } void Auth::setVerbose(bool on) { if (on != verbose()) { if (on) d->child->setProcessChannelMode(QProcess::ForwardedChannels); else d->child->setProcessChannelMode(QProcess::SeparateChannels); Q_EMIT verboseChanged(); } } void Auth::start() { QStringList args; args << QStringLiteral("--socket") << SocketServer::instance()->fullServerName(); args << QStringLiteral("--id") << QStringLiteral("%1").arg(d->id); if (!d->sessionPath.isEmpty()) args << QStringLiteral("--start") << d->sessionPath; if (!d->user.isEmpty()) args << QStringLiteral("--user") << d->user; if (d->autologin) args << QStringLiteral("--autologin"); if (!d->displayServerCmd.isEmpty()) args << QStringLiteral("--display-server") << d->displayServerCmd; if (d->greeter) args << QStringLiteral("--greeter"); d->child->start(QStringLiteral("%1/sddm-helper").arg(QStringLiteral(LIBEXEC_INSTALL_DIR)), args); } void Auth::stop() { d->child->terminate(); // wait for finished if (!d->child->waitForFinished(5000)) d->child->kill(); } } #include "Auth.moc"
l10n-tw/sddm
src/auth/Auth.cpp
C++
gpl-2.0
12,193
<?php // // ZoneMinder web frame view file, $Date$, $Revision$ // Copyright (C) 2001-2008 Philip Coombes // // 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. // require_once('includes/Frame.php'); $eid = validInt($_REQUEST['eid']); $fid = empty($_REQUEST['fid']) ? 0 : validInt($_REQUEST['fid']); $Event = new ZM\Event($eid); if (!$Event->canView()) { $view = 'error'; return; } $Monitor = $Event->Monitor(); # This is kinda weird.. so if we pass fid=0 or some other non-integer, then it loads max score # perhaps we should consider being explicit, like fid = maxscore if (!empty($fid)) { $sql = 'SELECT * FROM Frames WHERE EventId=? AND FrameId=?'; if (!($frame = dbFetchOne($sql, NULL, array($eid, $fid)))) $frame = array('EventId'=>$eid, 'FrameId'=>$fid, 'Type'=>'Normal', 'Score'=>0); } else { $frame = dbFetchOne('SELECT * FROM Frames WHERE EventId=? AND Score=?', NULL, array($eid, $Event->MaxScore())); } $Frame = new ZM\Frame($frame); $maxFid = $Event->Frames(); $firstFid = 1; $prevFid = $fid-1; $nextFid = $fid+1; $lastFid = $maxFid; $alarmFrame = ( $Frame->Type() == 'Alarm' ) ? 1 : 0; if (isset($_REQUEST['scale'])) { $scale = validNum($_REQUEST['scale']); } else if (isset($_COOKIE['zmWatchScale'.$Monitor->Id()])) { $scale = validNum($_COOKIE['zmWatchScale'.$Monitor->Id()]); } else if (isset($_COOKIE['zmWatchScale'])) { $scale = validNum($_COOKIE['zmWatchScale']); } else { $scale = max(reScale(SCALE_BASE, $Monitor->DefaultScale(), ZM_WEB_DEFAULT_SCALE), SCALE_BASE); } $scale = $scale ? $scale : 0; $imageData = $Event->getImageSrc($frame, $scale, 0); if (!$imageData) { ZM\Error("No data found for Event $eid frame $fid"); $imageData = array(); } $show = 'capt'; if (isset($_REQUEST['show']) && in_array($_REQUEST['show'], array('capt', 'anal'))) { $show = $_REQUEST['show']; if ($show == 'anal' and ! $imageData['hasAnalImage']) { $show = 'capt'; } } else if ($imageData['hasAnalImage']) { $show = 'anal'; } $imagePath = $imageData['thumbPath']; $eventPath = $imageData['eventPath']; $dImagePath = sprintf('%s/%0'.ZM_EVENT_IMAGE_DIGITS.'d-diag-d.jpg', $eventPath, $Frame->FrameId()); $rImagePath = sprintf('%s/%0'.ZM_EVENT_IMAGE_DIGITS.'d-diag-r.jpg', $eventPath, $Frame->FrameId()); $focusWindow = true; xhtmlHeaders(__FILE__, translate('Frame').' - '.$Event->Id().' - '.$Frame->FrameId()); ?> <body> <?php echo getNavBarHTML() ?> <div id="page p-0"> <div class="d-flex flex-row justify-content-between px-3 pt-1"> <div id="toolbar" > <button type="button" id="backBtn" class="btn btn-normal" data-toggle="tooltip" data-placement="top" title="<?php echo translate('Back') ?>" disabled><i class="fa fa-arrow-left"></i></button> <button type="button" id="refreshBtn" class="btn btn-normal" data-toggle="tooltip" data-placement="top" title="<?php echo translate('Refresh') ?>" ><i class="fa fa-refresh"></i></button> <button type="button" id="statsBtn" class="btn btn-normal" data-toggle="tooltip" data-placement="top" title="<?php echo translate('Stats') ?>" ><i class="fa fa-info"></i></button> <button type="button" id="statsViewBtn" class="btn btn-normal" data-toggle="tooltip" data-placement="top" title="<?php echo translate('Stats').' '.translate('View') ?>" ><i class="fa fa-table"></i></button> </div> <h2><?php echo translate('Frame') ?> <?php echo $Event->Id().'-'.$Frame->FrameId().' ('.$Frame->Score().')' ?></h2> <form> <div id="scaleControl"> <label for="scale"><?php echo translate('Scale') ?></label> <?php echo htmlSelect('scale', $scales, $scale, array('data-on-change'=>'changeScale','id'=>'scale')); ?> </div> <input type="hidden" name="base_width" id="base_width" value="<?php echo $Event->Width(); ?>"/> <input type="hidden" name="base_height" id="base_height" value="<?php echo $Event->Height(); ?>"/> </form> </div> <div id="content" class="d-flex flex-row justify-content-center"> <table id="frameStatsTable" class="table-sm table-borderless pr-3"> <!-- FRAME STATISTICS POPULATED BY AJAX --> </table> <div> <p id="image"> <?php if ($imageData['hasAnalImage']) { echo sprintf('<a href="?view=frame&amp;eid=%d&amp;fid=%d&scale=%d&amp;show=%s" title="Click to display frame %s analysis">', $Event->Id(), $Frame->FrameId(), $scale, ($show=='anal'?'capt':'anal'), ($show=='anal'?'without':'with') ); } ?> <img id="frameImg" src="<?php echo validHtmlStr($Frame->getImageSrc($show=='anal'?'analyse':'capture')) ?>" width="<?php echo reScale($Event->Width(), $Monitor->DefaultScale(), $scale) ?>" height="<?php echo reScale($Event->Height(), $Monitor->DefaultScale(), $scale) ?>" alt="<?php echo $Frame->EventId().'-'.$Frame->FrameId() ?>" class="<?php echo $imageData['imageClass'] ?>" /> <?php if ($imageData['hasAnalImage']) { ?></a><?php } ?> </p> <?php $frame_url_base = '?view=frame&amp;eid='.$Event->Id().'&amp;scale='.$scale.'&amp;show='.$show.'&amp;fid='; ?> <p id="controls"> <a id="firstLink" <?php echo (( $Frame->FrameId() > 1 ) ? 'href="'.$frame_url_base.$firstFid.'" class="btn-primary"' : 'class="btn-primary disabled"') ?>><?php echo translate('First') ?></a> <a id="prevLink" <?php echo ( $Frame->FrameId() > 1 ) ? 'href="'.$frame_url_base.$prevFid.'" class="btn-primary"' : 'class="btn-primary disabled"' ?>><?php echo translate('Prev') ?></a> <a id="nextLink" <?php echo ( $Frame->FrameId() < $maxFid ) ? 'href="'.$frame_url_base.$nextFid.'" class="btn-primary"' : 'class="btn-primary disabled"' ?>><?php echo translate('Next') ?></a> <a id="lastLink" <?php echo ( $Frame->FrameId() < $maxFid ) ? 'href="'.$frame_url_base.$lastFid .'" class="btn-primary"' : 'class="btn-primary disabled"' ?>><?php echo translate('Last') ?></a> </p> <?php if (file_exists($dImagePath)) { ?> <p id="diagImagePath"><?php echo $dImagePath ?></p> <p id="diagImage"> <img src="<?php echo viewImagePath($dImagePath) ?>" width="<?php echo reScale($Event->Width(), $Monitor->DefaultScale(), $scale) ?>" height="<?php echo reScale($Event->Height(), $Monitor->DefaultScale(), $scale) ?>" class="<?php echo $imageData['imageClass'] ?>" /> </p> <?php } if (file_exists($rImagePath)) { ?> <p id="refImagePath"><?php echo $rImagePath ?></p> <p id="refImage"> <img src="<?php echo viewImagePath($rImagePath) ?>" width="<?php echo reScale($Event->Width(), $Monitor->DefaultScale(), $scale) ?>" height="<?php echo reScale($Event->Height(), $Monitor->DefaultScale(), $scale) ?>" class="<?php echo $imageData['imageClass'] ?>" /> </p> </div> <?php } ?> </div> </div> <?php xhtmlFooter() ?>
connortechnology/ZoneMinder
web/skins/classic/views/frame.php
PHP
gpl-2.0
7,597
import React from "react"; import PropTypes from "prop-types"; import styled from "styled-components"; const StyledTag = styled.span` color: ${props => props.color}; background: ${props => props.bgcolor}; padding: ${props => props.padding}; margin: ${props => props.margin}; border-radius: 3px; border: ${props => `1px solid ${props.border}`}; max-width: ${props => props.maxWidth}; word-break: break-all; line-height: 20px; `; const Tag = ({ text, size = "medium", color = { bgcolor: "#fafafa", border: "#d9d9d9", color: "rgba(0,0,0,0.65)" }, margin = "", maxWidth = "300px" }) => { const getPaddingBySize = size => { const choices = { small: "0px 5px", medium: "1px 6px", large: "5px 10px" }; return choices[size]; }; return ( <StyledTag bgcolor={color.bgcolor} border={color.border} color={color.color} padding={getPaddingBySize(size)} margin={margin} maxWidth={maxWidth} > {text} </StyledTag> ); }; Tag.propTypes = { color: PropTypes.shape({ bgcolor: PropTypes.string, border: PropTypes.string, color: PropTypes.string }), text: PropTypes.string, size: PropTypes.string, margin: PropTypes.string, maxWidth: PropTypes.string }; export default Tag;
pamfilos/data.cern.ch
ui/cap-react/src/components/partials/Tag.js
JavaScript
gpl-2.0
1,314
<?php /** * The switch customize control extends the WP_Customize_Control class. This class allows * developers to create switch settings within the WordPress theme customizer. * * @package Bulan * @author Theme Junkie, Kirki * @copyright Copyright (c) 2015, Theme Junkie * @license http://www.gnu.org/licenses/gpl-2.0.html * @since 1.0.0 */ if ( ! class_exists( 'WP_Customize_Control' ) ) { return NULL; } /** * Create a switch control. * props https://github.com/reduxframework/kirki/blob/master/includes/controls/class-kirki-controls-switch-control.php */ class Customizer_Library_Switch extends WP_Customize_Control { /** * The type of customize control being rendered. */ public $type = 'switch'; /** * Enqueue needed style and script */ public function enqueue() { // Path $path = str_replace( WP_CONTENT_DIR, WP_CONTENT_URL, dirname( dirname( __FILE__ ) ) ); wp_enqueue_script( 'customizer-library-switch-script', trailingslashit( $path ) . 'js/switch.js', array( 'jquery' ), '1.0.0', true ); wp_enqueue_style( 'customizer-library-switch-style', trailingslashit( $path ) . 'css/switch.css' ); } public function render_content() { ?> <label> <div class="switch-info"> <input style="display: none;" type="checkbox" value="<?php echo esc_attr( $this->value() ); ?>" <?php $this->link(); checked( $this->value() ); ?> /> </div> <?php if ( ! empty( $this->label ) ) : ?> <span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span> <?php endif; if ( ! empty( $this->description ) ) : ?> <span class="description customize-control-description"><?php echo $this->description; ?></span> <?php endif; ?> <?php $classes = ( esc_attr( $this->value() ) ) ? ' on' : ' off'; ?> <div class="switch<?php echo $classes; ?>"> <div class="toggle"></div> <span class="on"><?php _e( 'On', 'bulan' ); ?></span> <span class="off"><?php _e( 'Off', 'bulan' ); ?></span> </div> </label> <?php } }
rkarpeles/taylorkarpeles
wp-content/themes/bulan/admin/controls/switch.php
PHP
gpl-2.0
2,026
package e.scm; import java.awt.*; import javax.swing.*; public class AnnotatedLineRenderer extends e.gui.EListCellRenderer<AnnotatedLine> { /** Used to draw the dashed line between adjacent lines from different revisions. */ private static final Stroke DASHED_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[] { 2.0f, 3.0f }, 0.0f); /** The RevisionView we're rendering for. */ private RevisionView revisionView; /** Whether or not we should draw a dashed line above this row. */ private boolean shouldDrawLine; public AnnotatedLineRenderer(RevisionView parentRevisionView) { super(false); this.revisionView = parentRevisionView; } @Override public void doCustomization(JList<AnnotatedLine> list, AnnotatedLine line, int row, boolean isSelected, boolean isFocused) { // Find out if this line is from a different revision to the // previous line. shouldDrawLine = false; if (row > 0) { ListModel<AnnotatedLine> model = list.getModel(); AnnotatedLine previousLine = model.getElementAt(row - 1); if (line.revision != previousLine.revision) { shouldDrawLine = true; } } setText(line.formattedLine); if (isSelected == false) { setForeground((revisionView.getAnnotatedRevision() == line.revision) ? Color.BLUE : Color.BLACK); } } public void paint(Graphics oldGraphics) { Graphics2D g = (Graphics2D) oldGraphics; super.paint(g); if (shouldDrawLine) { g.setColor(Color.LIGHT_GRAY); g.setStroke(DASHED_STROKE); g.drawLine(0, 0, getWidth(), 0); } } }
software-jessies-org/scm
src/e/scm/AnnotatedLineRenderer.java
Java
gpl-2.0
1,792
from utils import textAppend, textPrepend, textCut, textEditLastChar, error, textCursorPos class File: """ Represents a file (A separated class allow to open several files at a time. The class also holds the whole file content. (The vim buffers only store either the accepted chunks, or the editing statement) """ def __init__(self, plugin, buffers): self.windowsManager = plugin.windowsManager self.coqManager = plugin.coqManager self.input = buffers[0] self.output = buffers[1] # Each chunk is describe by the following tuple : (startPos, endPos, newLine), where startPos and endPos are coords tuple self.chunks = [] # The whole file content self.code = [] self.editPosition = (0, 0) # We manage a virtual new-line at the end of the compiled buffer. self.initOutputCursor() def initOutputCursor(self): """ Init the newline-cursor in the Compiled buffer. """ self.output.options['modifiable'] = True del self.output[:] self.drawNewlineCursor(False) self.output.options['modifiable'] = False self.editNewLine = False # We backtrack every chunks self.chunks = self.chunks[:- self.coqManager.rewind(len(self.chunks))] def drawNewlineCursor(self, newLine): if newLine: self.windowsManager.commands('__Compiled__', ["normal G$a Dt"]) else: self.windowsManager.commands('__Compiled__', ["normal G$a PR"]) def next(self): nextChunk = self.windowsManager.input.getChunk(self.input, (0, 0)) if nextChunk : if self.coqManager.sendChunk(nextChunk[0]): if self.editNewLine: chunkStart = (0, textCursorPos(self.output)[1] + 1, 2) else: chunkStart = textCursorPos(self.output, diffX = 3) # diffX=2 to ignore the newline-cursor chunkStart = (chunkStart[0], chunkStart[1], 0) chunk = textCut(self.input, (0, 0, 2), nextChunk[1]) self.output.options['modifiable'] = True # Remove the last newline-cursor self.windowsManager.commands('__Compiled__', ["normal G$a"]) textAppend(self.output, chunk, self.editNewLine) self.editNewLine = nextChunk[2] chunkEnd = textCursorPos(self.output) if self.editNewLine: self.drawNewlineCursor(True) chunkEnd = (chunkEnd[0] + 1, chunkEnd[1], 1) else: self.drawNewlineCursor(False) chunkEnd = (chunkEnd[0] + 1, chunkEnd[1], 0) self.output.options['modifiable'] = False self.chunks.append((chunkStart, chunkEnd, self.editNewLine)) def prev(self): """ Backtrack of one chunk """ if len(self.chunks) <= 0: print("No chunk to backtrack !") return None actualRewind = self.coqManager.rewind(1) if actualRewind == 1: self.output.options['modifiable'] = True # Remove the last newline-cursor self.windowsManager.commands('__Compiled__', ["normal G$a"]) lastChunk = self.chunks[-1] chunk = textCut(self.output, lastChunk[0], lastChunk[1]) textPrepend(self.input, chunk, lastChunk[2]) self.chunks.pop() if len(self.chunks) == 0: self.editNewLine = False else: self.editNewLine = self.chunks[-1][2] self.drawNewlineCursor(self.editNewLine) self.output.options['modifiable'] = False def write(self, filename): try: file = open(filename, 'w') # We write the compiled buffer, and then the edit buffer for i in xrange(len(self.output) - 1): file.write(self.output[i] + "\n") interline = self.output[-1][:-4] # We don't take the newline-cursor if not self.editNewLine: interline += self.input[0] file.write(interline + "\n") for i in xrange(0 if self.editNewLine else 1, len(self.input)): file.write(self.input[i] + "\n") file.close() except IOError as e: error(str(e)) def open(self, filename): # First, clear the buffers self.initOutputCursor() del self.chunks[:] del self.input[:] try: file = open(filename, 'r') # We simply add every lines in the Edit buffer firstLine = True for line in file: if firstLine: # We don't want to skip the first line self.input[0] = line firstLine = False else: self.input.append(line) file.close() except IOError as e: error(str(e))
QuanticPotato/vcoq
plugin/file.py
Python
gpl-2.0
4,084
// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2019 The MMapper Authors #include "abstractparser.h" #include <map> #include <memory> #include <optional> #include <ostream> #include <sstream> #include <vector> #include "../configuration/configuration.h" #include "../display/InfoMarkSelection.h" #include "../expandoracommon/room.h" #include "../global/TextUtils.h" #include "../mapdata/DoorFlags.h" #include "../mapdata/ExitDirection.h" #include "../mapdata/ExitFlags.h" #include "../mapdata/customaction.h" #include "../mapdata/enums.h" #include "../mapdata/infomark.h" #include "../mapdata/mapdata.h" #include "../mapdata/mmapper2room.h" #include "../syntax/SyntaxArgs.h" #include "../syntax/TreeParser.h" #include "AbstractParser-Commands.h" #include "AbstractParser-Utils.h" NODISCARD static const char *getTypeName(const InfoMarkTypeEnum type) { #define CASE(UPPER, s) \ do { \ case InfoMarkTypeEnum::UPPER: \ return s; \ } while (false) switch (type) { CASE(TEXT, "text"); CASE(LINE, "line"); CASE(ARROW, "arrow"); } return "unknown"; #undef CASE } class NODISCARD ArgMarkClass final : public syntax::IArgument { private: syntax::MatchResult virt_match(const syntax::ParserInput &input, syntax::IMatchErrorLogger *) const override; std::ostream &virt_to_stream(std::ostream &os) const override; }; syntax::MatchResult ArgMarkClass::virt_match(const syntax::ParserInput &input, syntax::IMatchErrorLogger *logger) const { if (input.empty()) return syntax::MatchResult::failure(input); const auto arg = toLowerLatin1(input.front()); StringView sv(arg); for (const auto &clazz : ::enums::getAllInfoMarkClasses()) { const auto &command = getParserCommandName(clazz); if (!command.matches(sv)) continue; return syntax::MatchResult::success(1, input, Value(clazz)); } if (logger) { std::ostringstream os; for (const auto &clazz : ::enums::getAllInfoMarkClasses()) os << getParserCommandName(clazz).getCommand() << " "; logger->logError("input was not a valid mark class: " + os.str()); } return syntax::MatchResult::failure(input); } std::ostream &ArgMarkClass::virt_to_stream(std::ostream &os) const { return os << "<class>"; } void AbstractParser::parseMark(StringView input) { using namespace ::syntax; static const auto abb = syntax::abbrevToken; auto getPositionCoordinate = [this]() -> Coordinate { // get scaled coordinates of room center. static_assert(INFOMARK_SCALE % 2 == 0); const Coordinate halfRoomOffset{INFOMARK_SCALE / 2, INFOMARK_SCALE / 2, 0}; // do not scale the z-coordinate! only x,y should get scaled. const Coordinate pos = m_mapData.getPosition(); Coordinate c{pos.x * INFOMARK_SCALE, pos.y * INFOMARK_SCALE, pos.z}; c += halfRoomOffset; return c; }; auto getInfoMarkSelection = [this](const Coordinate &c) -> std::shared_ptr<InfoMarkSelection> { // the scaling + offset operation looks like `A*x + b` where A is a 3x3 // transformation matrix and b,x are 3-vectors // A = [[INFOMARK_SCALE/2, 0 0] // [0, INFOMARK_SCALE/2, 0] // [0, 0, 1]] // b = halfRoomOffset // x = m_mapData->getPosition() // // c = A*x + b static_assert(INFOMARK_SCALE % 5 == 0); static constexpr auto INFOMARK_ROOM_RADIUS = INFOMARK_SCALE / 2; const auto lo = c + Coordinate{-INFOMARK_ROOM_RADIUS, -INFOMARK_ROOM_RADIUS, 0}; const auto hi = c + Coordinate{+INFOMARK_ROOM_RADIUS, +INFOMARK_ROOM_RADIUS, 0}; return InfoMarkSelection::alloc(m_mapData, lo, hi); }; auto listMark = Accept( [getPositionCoordinate, getInfoMarkSelection](User &user, const Pair * /*args*/) { auto &os = user.getOstream(); auto printCoordinate = [&os](const Coordinate c) { os << "(" << c.x << ", " << c.y << ", " << c.z << ")"; }; const Coordinate c = getPositionCoordinate(); os << "Marks near coordinate "; printCoordinate(c); os << std::endl; int n = 0; std::shared_ptr<InfoMarkSelection> is = getInfoMarkSelection(c); for (const auto &mark : *is) { if (n != 0) os << std::endl; os << "\x1b[32m" << ++n << "\x1b[0m: " << getTypeName(mark->getType()) << std::endl; os << " angle: " << mark->getRotationAngle() << std::endl; os << " class: " << getParserCommandName(mark->getClass()).getCommand() << std::endl; if (mark->getType() == InfoMarkTypeEnum::TEXT) os << " text: " << mark->getText().getStdString() << std::endl; else { os << " pos1: "; printCoordinate(mark->getPosition1()); os << std::endl; os << " pos2: "; printCoordinate(mark->getPosition2()); os << std::endl; } } }, "list marks"); auto listSyntax = buildSyntax(abb("list"), listMark); auto removeMark = Accept( [this, getPositionCoordinate, getInfoMarkSelection](User &user, const Pair *args) { auto &os = user.getOstream(); const auto v = getAnyVectorReversed(args); if constexpr (IS_DEBUG_BUILD) { const auto &set = v[0].getString(); assert(set == "remove"); } const Coordinate c = getPositionCoordinate(); std::shared_ptr<InfoMarkSelection> is = getInfoMarkSelection(c); const auto index = static_cast<size_t>(v[1].getInt() - 1); assert(index >= 0); if (index >= is->size()) throw std::runtime_error("unable to select mark"); // delete the infomark const auto &mark = is->at(index); m_mapData.removeMarker(mark); emit sig_infoMarksChanged(); send_ok(os); }, "remove mark"); auto removeSyntax = buildSyntax(abb("remove"), TokenMatcher::alloc_copy<ArgInt>(ArgInt::withMin(1)), removeMark); auto addRoomMark = Accept( [this, getPositionCoordinate](User &user, const Pair *const args) { auto &os = user.getOstream(); const auto v = getAnyVectorReversed(args); if constexpr (IS_DEBUG_BUILD) { const auto &set = v[0].getString(); assert(set == "add"); } const std::string text = concatenate_unquoted(v[1].getVector()); if (text.empty()) { os << "What do you want to set the mark to?\n"; return; } // create a text infomark above this room const Coordinate c = getPositionCoordinate(); auto mark = InfoMark::alloc(m_mapData); mark->setType(InfoMarkTypeEnum::TEXT); mark->setText(InfoMarkText{text}); mark->setClass(InfoMarkClassEnum::COMMENT); mark->setPosition1(c); m_mapData.addMarker(mark); emit sig_infoMarksChanged(); send_ok(os); }, "add mark"); auto addSyntax = buildSyntax(abb("add"), TokenMatcher::alloc<ArgRest>(), addRoomMark); auto modifyText = Accept( [this, getPositionCoordinate, getInfoMarkSelection](User &user, const Pair *const args) { auto &os = user.getOstream(); const auto v = getAnyVectorReversed(args); if constexpr (IS_DEBUG_BUILD) { const auto &set = v[0].getString(); assert(set == "set"); const auto &text = v[2].getString(); assert(text == "text"); } const Coordinate c = getPositionCoordinate(); std::shared_ptr<InfoMarkSelection> is = getInfoMarkSelection(c); const auto index = static_cast<size_t>(v[1].getInt() - 1); assert(index >= 0); if (index >= is->size()) throw std::runtime_error("unable to select mark"); const auto &mark = is->at(index); if (mark->getType() != InfoMarkTypeEnum::TEXT) throw std::runtime_error("unable to set text to this mark"); // update text of the first existing text infomark in this room const std::string text = concatenate_unquoted(v[3].getVector()); if (text.empty()) { os << "What do you want to set the mark's text to?\n"; return; } mark->setText(InfoMarkText{text}); emit sig_infoMarksChanged(); send_ok(os); }, "modify mark text"); auto modifyClass = Accept( [this, getPositionCoordinate, getInfoMarkSelection](User &user, const Pair *const args) { auto &os = user.getOstream(); const auto v = getAnyVectorReversed(args); if constexpr (IS_DEBUG_BUILD) { const auto &set = v[0].getString(); assert(set == "set"); const auto &clazz = v[2].getString(); assert(clazz == "class"); } const Coordinate c = getPositionCoordinate(); std::shared_ptr<InfoMarkSelection> is = getInfoMarkSelection(c); const auto index = static_cast<size_t>(v[1].getInt() - 1); assert(index >= 0); if (index >= is->size()) throw std::runtime_error("unable to select mark"); const auto clazz = v[3].getInfoMarkClass(); const auto &mark = is->at(index); mark->setClass(clazz); emit sig_infoMarksChanged(); send_ok(os); }, "modify mark class"); auto modifyAngle = Accept( [this, getPositionCoordinate, getInfoMarkSelection](User &user, const Pair *const args) { auto &os = user.getOstream(); const auto v = getAnyVectorReversed(args); if constexpr (IS_DEBUG_BUILD) { const auto &set = v[0].getString(); assert(set == "set"); const auto &angle = v[2].getString(); assert(angle == "angle"); } const Coordinate c = getPositionCoordinate(); std::shared_ptr<InfoMarkSelection> is = getInfoMarkSelection(c); const auto index = static_cast<size_t>(v[1].getInt() - 1); assert(index >= 0); if (index >= is->size()) throw std::runtime_error("unable to select mark"); const auto &mark = is->at(index); if (mark->getType() != InfoMarkTypeEnum::TEXT) throw std::runtime_error("unable to set angle to this mark"); const auto angle = v[3].getInt(); mark->setRotationAngle(angle); emit sig_infoMarksChanged(); send_ok(os); }, "modify mark angle"); // REVISIT: Does it make sense to allow user to change the type to arrow or line? What about position? auto setSyntax = buildSyntax(abb("set"), TokenMatcher::alloc_copy<ArgInt>(ArgInt::withMin(1)), buildSyntax(abb("angle"), TokenMatcher::alloc_copy<ArgInt>(ArgInt::withMinMax(0, 360)), modifyAngle), buildSyntax(abb("class"), TokenMatcher::alloc<ArgMarkClass>(), modifyClass), buildSyntax(abb("text"), TokenMatcher::alloc<ArgRest>(), modifyText)); auto markSyntax = buildSyntax(addSyntax, listSyntax, removeSyntax, setSyntax); eval("mark", markSyntax, input); }
MUME/MMapper
src/parser/AbstractParser-Mark.cpp
C++
gpl-2.0
12,204
/* KeePass Password Safe - The Open-Source Password Manager Copyright (C) 2003-2017 Dominik Reichl <dominik.reichl@t-online.de> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Diagnostics; using KeePass.UI; using KeePass.Resources; using KeePassLib; namespace KeePass.Forms { public partial class ImportMethodForm : Form { PwMergeMethod m_mmSelected = PwMergeMethod.CreateNewUuids; public PwMergeMethod MergeMethod { get { return m_mmSelected; } } public ImportMethodForm() { InitializeComponent(); Program.Translation.ApplyTo(this); } private void OnFormLoad(object sender, EventArgs e) { GlobalWindowManager.AddWindow(this); try { if(this.Owner == null) this.Owner = Program.MainForm; } catch(Exception) { Debug.Assert(false); } BannerFactory.CreateBannerEx(this, m_bannerImage, Properties.Resources.B48x48_Folder_Download, KPRes.ImportBehavior, KPRes.ImportBehaviorDesc); this.Icon = Properties.Resources.KeePass; this.Text = KPRes.ImportBehavior; m_radioCreateNew.Text = KPRes.CreateNewIDs; m_radioKeepExisting.Text = KPRes.KeepExisting; m_radioOverwrite.Text = KPRes.OverwriteExisting; m_radioOverwriteIfNewer.Text = KPRes.OverwriteIfNewer; m_radioSynchronize.Text = KPRes.OverwriteIfNewerAndApplyDel; FontUtil.AssignDefaultBold(m_radioCreateNew); FontUtil.AssignDefaultBold(m_radioKeepExisting); FontUtil.AssignDefaultBold(m_radioOverwrite); FontUtil.AssignDefaultBold(m_radioOverwriteIfNewer); FontUtil.AssignDefaultBold(m_radioSynchronize); m_radioCreateNew.Checked = true; } private void OnBtnOK(object sender, EventArgs e) { if(m_radioCreateNew.Checked) m_mmSelected = PwMergeMethod.CreateNewUuids; else if(m_radioKeepExisting.Checked) m_mmSelected = PwMergeMethod.KeepExisting; else if(m_radioOverwrite.Checked) m_mmSelected = PwMergeMethod.OverwriteExisting; else if(m_radioOverwriteIfNewer.Checked) m_mmSelected = PwMergeMethod.OverwriteIfNewer; else if(m_radioSynchronize.Checked) m_mmSelected = PwMergeMethod.Synchronize; } private void OnBtnCancel(object sender, EventArgs e) { } private void OnFormClosed(object sender, FormClosedEventArgs e) { GlobalWindowManager.RemoveWindow(this); } } }
FSteitz/KeePass
KeePass/Forms/ImportMethodForm.cs
C#
gpl-2.0
3,187
using System.Collections.Generic; using System.Linq; using System.Web.Http; using Business.Logic.Factories; using Business.Logic.Objects; using Business.Logic.Queries; namespace DFWOutdoors.Controllers { public class CampInfoController : ApiController { [HttpPost] public IEnumerable<CampSite> CheckCampsiteAvailability(CampsiteSearchCriteria campsiteSearchCriteria) { var campsiteQuery = new QueryFactory<GetCampsitesByCampsiteSearchCriteria>().Create(); campsiteQuery.Url = Urls.GetAllCampsitesBySearchCriteria; campsiteQuery.CampsiteSearchCriteria = campsiteSearchCriteria; return campsiteQuery.Execute().OfType<CampSite>().ToList(); } } }
SparkyCoder/Xenocide
DFWOutdoors/DFWOutdoors/Controllers/CampInfoController.cs
C#
gpl-2.0
740
/* * Copyright (c) 2010 Mark Liversedge (liversedge@gmail.com) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "ICalendar.h" #include "GcCalendarModel.h" #include "CalendarDownload.h" #include <libical/ical.h> #define tr(s) QObject::tr(s) static struct { icalproperty_kind type; QString friendly; } ICalendarProperties[] = { { ICAL_ACTION_PROPERTY, tr("Action") }, { ICAL_ALLOWCONFLICT_PROPERTY, tr("Allow Conflict") }, { ICAL_ATTACH_PROPERTY, tr("Attachment") }, { ICAL_ATTENDEE_PROPERTY, tr("Attendee") }, { ICAL_CALID_PROPERTY, tr("Calendar Identifier") }, { ICAL_CALMASTER_PROPERTY, tr("Master") }, { ICAL_CALSCALE_PROPERTY, tr("Scale") }, { ICAL_CAPVERSION_PROPERTY, tr("Version") }, { ICAL_CARLEVEL_PROPERTY, tr("Level") }, { ICAL_CARID_PROPERTY, tr("Event Identifier") }, { ICAL_CATEGORIES_PROPERTY, tr("Category") }, { ICAL_CLASS_PROPERTY, tr("Class") }, { ICAL_CMD_PROPERTY, tr("Command") }, { ICAL_COMMENT_PROPERTY, tr("Comment") }, { ICAL_COMPLETED_PROPERTY, tr("Completed") }, { ICAL_COMPONENTS_PROPERTY, tr("") }, { ICAL_CONTACT_PROPERTY, tr("Contact") }, { ICAL_CREATED_PROPERTY, tr("Date Created") }, { ICAL_CSID_PROPERTY, tr("CSID?") }, { ICAL_DATEMAX_PROPERTY, tr("No later than") }, { ICAL_DATEMIN_PROPERTY, tr("No earlier than") }, { ICAL_DECREED_PROPERTY, tr("Decreed") }, { ICAL_DEFAULTCHARSET_PROPERTY, tr("Default character set") }, { ICAL_DEFAULTLOCALE_PROPERTY, tr("Default locale") }, { ICAL_DEFAULTTZID_PROPERTY, tr("Default timezone") }, { ICAL_DEFAULTVCARS_PROPERTY, tr("Default VCar") }, { ICAL_DENY_PROPERTY, tr("Deny") }, { ICAL_DESCRIPTION_PROPERTY, tr("Description") }, { ICAL_DTEND_PROPERTY, tr("End Date & Time") }, { ICAL_DTSTAMP_PROPERTY, tr("Timestamp") }, { ICAL_DTSTART_PROPERTY, tr("Start Date & Time") }, { ICAL_DUE_PROPERTY, tr("Due Date") }, { ICAL_DURATION_PROPERTY, tr("Duration") }, { ICAL_EXDATE_PROPERTY, tr("Expiry Date") }, { ICAL_EXPAND_PROPERTY, tr("Expand") }, { ICAL_EXRULE_PROPERTY, tr("Exclusive rule") }, { ICAL_FREEBUSY_PROPERTY, tr("Freebusy") }, { ICAL_GEO_PROPERTY, tr("Geo") }, { ICAL_GRANT_PROPERTY, tr("Grant") }, { ICAL_ITIPVERSION_PROPERTY, tr("ITIP Version") }, { ICAL_LASTMODIFIED_PROPERTY, tr("Modified Date") }, { ICAL_LOCATION_PROPERTY, tr("Location") }, { ICAL_MAXCOMPONENTSIZE_PROPERTY, tr("Max component size") }, { ICAL_MAXDATE_PROPERTY, tr("No later than") }, { ICAL_MAXRESULTS_PROPERTY, tr("Maximum results") }, { ICAL_MAXRESULTSSIZE_PROPERTY, tr("Maximum results size") }, { ICAL_METHOD_PROPERTY, tr("Method") }, { ICAL_MINDATE_PROPERTY, tr("Np earlier than") }, { ICAL_MULTIPART_PROPERTY, tr("Is Multipart") }, { ICAL_NAME_PROPERTY, tr("Name") }, { ICAL_ORGANIZER_PROPERTY, tr("Organised by") }, { ICAL_OWNER_PROPERTY, tr("Owner") }, { ICAL_PERCENTCOMPLETE_PROPERTY, tr("Percent Complete") }, { ICAL_PERMISSION_PROPERTY, tr("Permissions") }, { ICAL_PRIORITY_PROPERTY, tr("Priority") }, { ICAL_PRODID_PROPERTY, tr("Prod Identifier") }, { ICAL_QUERY_PROPERTY, tr("Query") }, { ICAL_QUERYLEVEL_PROPERTY, tr("Query Level") }, { ICAL_QUERYID_PROPERTY, tr("Query Identifier") }, { ICAL_QUERYNAME_PROPERTY, tr("Query Name") }, { ICAL_RDATE_PROPERTY, tr("Recurring Date") }, { ICAL_RECURACCEPTED_PROPERTY, tr("Recurring Accepted") }, { ICAL_RECUREXPAND_PROPERTY, tr("Recurring Expanded") }, { ICAL_RECURLIMIT_PROPERTY, tr("Recur no later than") }, { ICAL_RECURRENCEID_PROPERTY, tr("Reccurrence Identifier") }, { ICAL_RELATEDTO_PROPERTY, tr("Related to") }, { ICAL_RELCALID_PROPERTY, tr("Related to Calendar Identifier") }, { ICAL_REPEAT_PROPERTY, tr("Repeat") }, { ICAL_REQUESTSTATUS_PROPERTY, tr("Request Status") }, { ICAL_RESOURCES_PROPERTY, tr("Resources") }, { ICAL_RESTRICTION_PROPERTY, tr("Restriction") }, { ICAL_RRULE_PROPERTY, tr("Rule") }, { ICAL_SCOPE_PROPERTY, tr("Scope") }, { ICAL_SEQUENCE_PROPERTY, tr("Sequence Number") }, { ICAL_STATUS_PROPERTY, tr("Status") }, { ICAL_STORESEXPANDED_PROPERTY, tr("Stores Expanded") }, { ICAL_SUMMARY_PROPERTY, tr("Summary") }, { ICAL_TARGET_PROPERTY, tr("Target") }, { ICAL_TRANSP_PROPERTY, tr("Transport") }, { ICAL_TRIGGER_PROPERTY, tr("Trigger") }, { ICAL_TZID_PROPERTY, tr("Timezone Identifier") }, { ICAL_TZNAME_PROPERTY, tr("Timezone Name") }, { ICAL_TZOFFSETFROM_PROPERTY, tr("Timezone Offset from") }, { ICAL_TZOFFSETTO_PROPERTY, tr("Timezone Offset to") }, { ICAL_TZURL_PROPERTY, tr("Timezone URL") }, { ICAL_UID_PROPERTY, tr("Unique Identifier") }, { ICAL_URL_PROPERTY, tr("URL") }, { ICAL_VERSION_PROPERTY, tr("Version") }, { ICAL_X_PROPERTY, tr("X-Property") }, { ICAL_XLICCLASS_PROPERTY, tr("XLI Class") }, { ICAL_XLICCLUSTERCOUNT_PROPERTY, tr("XLI Cluster count") }, { ICAL_XLICERROR_PROPERTY, tr("XLI error") }, { ICAL_XLICMIMECHARSET_PROPERTY, tr("XLI mime character set") }, { ICAL_XLICMIMECID_PROPERTY, tr("XLI mime class Identifier") }, { ICAL_XLICMIMECONTENTTYPE_PROPERTY, tr("XLI mime content type") }, { ICAL_XLICMIMEENCODING_PROPERTY, tr("XLI mime encoding") }, { ICAL_XLICMIMEFILENAME_PROPERTY, tr("XLI mime filename") }, { ICAL_XLICMIMEOPTINFO_PROPERTY, tr("XLI mime optional information") }, { ICAL_NO_PROPERTY, tr("") } //XXX ICAL_NO_PROPERTY must always be last!! }; // convert property to a string static QString propertyToString(icalproperty *p) { if (p) { icalvalue *v = icalproperty_get_value(p); QString converted(icalvalue_as_ical_string(v)); // some special characters are escaped in the text converted.replace("\\n", "\n"); converted.replace("\\;", ";"); return converted; } else { return QString(""); } } // convert property to a DateTime static QDateTime propertyToDate(icalproperty *p) { if (p) { icalvalue *v = icalproperty_get_value(p); struct icaltimetype date = icalvalue_get_datetime(v); QDateTime when(QDate(date.year, date.month, date.day), QTime(date.hour, date.minute, date.second)); return when; } else { return QDateTime(); } } ICalendar::ICalendar(MainWindow *parent) : QWidget(parent), main(parent) { // get from local and remote calendar // local file QString localFilename = main->home.absolutePath()+"/calendar.ics"; QFile localFile(localFilename); if (localFile.exists() && localFile.open(QFile::ReadOnly | QFile::Text)) { // read in the whole thing QTextStream in(&localFile); QString fulltext = in.readAll(); localFile.close(); // parse parse(fulltext, localCalendar); } // remote file main->calendarDownload->download(); } void ICalendar::refreshRemote(QString fulltext) { parse(fulltext, remoteCalendar); } void ICalendar::parse(QString fulltext, QMap<QDate, QList<icalcomponent*>*>&calendar) { // parse the contents using libical icalcomponent *root = icalparser_parse_string(fulltext.toLatin1().constData()); clearCalendar(calendar,false); if (root) { // iterate over events (not interested in the rest for now) //for (icalcomponent *c = icalcomponent_get_first_component(root, ICAL_VEVENT_COMPONENT); for (icalcomponent *event = icalcomponent_get_first_component(root, ICAL_VEVENT_COMPONENT); event != NULL; event = icalcomponent_get_next_component(root, ICAL_VEVENT_COMPONENT)) { // Get start date... icalproperty *date = icalcomponent_get_first_property(event, ICAL_DTSTART_PROPERTY); if (date) { // ignore events with no date! QDate startDate = propertyToDate(date).date(); QList<icalcomponent*>* events = calendar.value(startDate, NULL); if (!events) { events = new QList<icalcomponent*>; calendar.insert(startDate, events); } events->append(event); } } } emit dataChanged(); } void ICalendar::clearCalendar(QMap<QDate, QList<icalcomponent*>*>&calendar, bool signal) { QMapIterator<QDate, QList<icalcomponent*>* >i(calendar); while (i.hasNext()) { i.next(); delete i.value(); } calendar.clear(); if (signal) emit dataChanged(); } // for models to pass straight through to access and // set the calendar data QVariant ICalendar::data(QDate date, int role) { switch (role) { case GcCalendarModel::EventCountRole: { int count = 0; QList<icalcomponent*>*p = localCalendar.value(date, NULL); if (p) count += p->count(); p = remoteCalendar.value(date, NULL); if (p) count += p->count(); return count; } case Qt::DisplayRole: // returns a list for the given date case Qt::EditRole: // returns a list for the given date { QStringList strings; // local QList<icalcomponent*>*p = localCalendar.value(date, NULL); if (p) { foreach(icalcomponent*event, *p) { QString desc; icalproperty *summary = icalcomponent_get_first_property(event, ICAL_SUMMARY_PROPERTY); desc = propertyToString(summary); icalproperty *property = icalcomponent_get_first_property(event, ICAL_DESCRIPTION_PROPERTY); desc += " "; desc += propertyToString(property); strings << desc; } } // remote p = remoteCalendar.value(date, NULL); if (p) { foreach(icalcomponent*event, *p) { QString desc; icalproperty *summary = icalcomponent_get_first_property(event, ICAL_SUMMARY_PROPERTY); desc = propertyToString(summary); icalproperty *property = icalcomponent_get_first_property(event, ICAL_DESCRIPTION_PROPERTY); desc += " "; desc += propertyToString(property); strings << desc; } } return strings; } break; default: break; } return QVariant(); }
g3rg/GoldenCheetah
src/ICalendar.cpp
C++
gpl-2.0
11,408
/** * This file is a part of Luminance HDR package. * ---------------------------------------------------------------------- * Copyright (C) 2011 Franco Comida * * 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 * ---------------------------------------------------------------------- * * @author Franco Comida <fcomida@users.sourceforge.net> * */ #include "TonemappingPanel/ui_SavingParametersDialog.h" #include "TonemappingPanel/SavingParametersDialog.h" SavingParameters::SavingParameters(QWidget *parent) : QDialog(parent), m_Ui(new Ui::SavingParameters) { m_Ui->setupUi(this); } SavingParameters::~SavingParameters() {} QString SavingParameters::getComment() { return m_Ui->comment->text(); }
LuminanceHDR/LuminanceHDR
src/TonemappingPanel/SavingParametersDialog.cpp
C++
gpl-2.0
1,393
/** * */ package agentRefactoringStrand; /** * @author Daavid * */ public class Attribute { private String name; }
danaderp/unalcol
projects/optimizationRefactoringStrand/src/agentRefactoringStrand/Attribute.java
Java
gpl-2.0
137
/* * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "Common.h" #include "Language.h" #include "WorldPacket.h" #include "WorldSession.h" #include "World.h" #include "ObjectMgr.h" #include "Log.h" #include "Opcodes.h" #include "Guild.h" #include "ArenaTeam.h" #include "GossipDef.h" #include "SocialMgr.h" /*enum PetitionType // dbc data { PETITION_TYPE_GUILD = 1, PETITION_TYPE_ARENA_TEAM = 3 };*/ // Charters ID in item_template #define GUILD_CHARTER 5863 #define GUILD_CHARTER_COST 1000 // 10 S #define ARENA_TEAM_CHARTER_2v2 23560 #define ARENA_TEAM_CHARTER_2v2_COST 800000 // 80 G #define ARENA_TEAM_CHARTER_3v3 23561 #define ARENA_TEAM_CHARTER_3v3_COST 1200000 // 120 G #define ARENA_TEAM_CHARTER_5v5 23562 #define ARENA_TEAM_CHARTER_5v5_COST 2000000 // 200 G #define CHARTER_DISPLAY_ID 16161 void WorldSession::HandlePetitionBuyOpcode(WorldPacket & recv_data) { DEBUG_LOG("Received opcode CMSG_PETITION_BUY"); recv_data.hexlike(); uint64 guidNPC; uint32 unk2; std::string name; recv_data >> guidNPC; // NPC GUID recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint64>(); // 0 recv_data >> name; // name recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint32>(); // 0 recv_data.read_skip<uint16>(); // 0 recv_data.read_skip<uint8>(); // 0 recv_data >> unk2; // index recv_data.read_skip<uint32>(); // 0 DEBUG_LOG("Petitioner with GUID %u tried sell petition: name %s", GUID_LOPART(guidNPC), name.c_str()); // prevent cheating Creature *pCreature = GetPlayer()->GetNPCIfCanInteractWith(guidNPC,UNIT_NPC_FLAG_PETITIONER); if (!pCreature) { DEBUG_LOG("WORLD: HandlePetitionBuyOpcode - Unit (GUID: %u) not found or you can't interact with him.", GUID_LOPART(guidNPC)); return; } // remove fake death if(GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); uint32 charterid = 0; uint32 cost = 0; uint32 type = 0; if(pCreature->isTabardDesigner()) { // if tabard designer, then trying to buy a guild charter. // do not let if already in guild. if(_player->GetGuildId()) return; charterid = GUILD_CHARTER; cost = GUILD_CHARTER_COST; type = 9; } else { // TODO: find correct opcode if(_player->getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) { SendNotification(LANG_ARENA_ONE_TOOLOW, sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)); return; } switch(unk2) { case 1: charterid = ARENA_TEAM_CHARTER_2v2; cost = ARENA_TEAM_CHARTER_2v2_COST; type = 2; // 2v2 break; case 2: charterid = ARENA_TEAM_CHARTER_3v3; cost = ARENA_TEAM_CHARTER_3v3_COST; type = 3; // 3v3 break; case 3: charterid = ARENA_TEAM_CHARTER_5v5; cost = ARENA_TEAM_CHARTER_5v5_COST; type = 5; // 5v5 break; default: DEBUG_LOG("unknown selection at buy petition: %u", unk2); return; } if(_player->GetArenaTeamId(unk2 - 1)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ALREADY_IN_ARENA_TEAM); return; } } if(type == 9) { if(sObjectMgr.GetGuildByName(name)) { SendGuildCommandResult(GUILD_CREATE_S, name, ERR_GUILD_NAME_EXISTS_S); return; } if(sObjectMgr.IsReservedName(name) || !ObjectMgr::IsValidCharterName(name)) { SendGuildCommandResult(GUILD_CREATE_S, name, ERR_GUILD_NAME_INVALID); return; } } else { if(sObjectMgr.GetArenaTeamByName(name)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_EXISTS_S); return; } if(sObjectMgr.IsReservedName(name) || !ObjectMgr::IsValidCharterName(name)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_INVALID); return; } } ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(charterid); if(!pProto) { _player->SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, charterid, 0); return; } if(_player->GetMoney() < cost) { //player hasn't got enough money _player->SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, charterid, 0); return; } ItemPosCountVec dest; uint8 msg = _player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, charterid, pProto->BuyCount ); if(msg != EQUIP_ERR_OK) { _player->SendBuyError(msg, pCreature, charterid, 0); return; } _player->ModifyMoney(-(int32)cost); Item *charter = _player->StoreNewItem(dest, charterid, true); if(!charter) return; charter->SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1, charter->GetGUIDLow()); // ITEM_FIELD_ENCHANTMENT_1_1 is guild/arenateam id // ITEM_FIELD_ENCHANTMENT_1_1+1 is current signatures count (showed on item) charter->SetState(ITEM_CHANGED, _player); _player->SendNewItem(charter, 1, true, false); // a petition is invalid, if both the owner and the type matches // we checked above, if this player is in an arenateam, so this must be data corruption QueryResult *result = CharacterDatabase.PQuery("SELECT petitionguid FROM petition WHERE ownerguid = '%u' AND type = '%u'", _player->GetGUIDLow(), type); std::ostringstream ssInvalidPetitionGUIDs; if (result) { do { Field *fields = result->Fetch(); ssInvalidPetitionGUIDs << "'" << fields[0].GetUInt32() << "' , "; } while (result->NextRow()); delete result; } // delete petitions with the same guid as this one ssInvalidPetitionGUIDs << "'" << charter->GetGUIDLow() << "'"; DEBUG_LOG("Invalid petition GUIDs: %s", ssInvalidPetitionGUIDs.str().c_str()); CharacterDatabase.escape_string(name); CharacterDatabase.BeginTransaction(); CharacterDatabase.PExecute("DELETE FROM petition WHERE petitionguid IN ( %s )", ssInvalidPetitionGUIDs.str().c_str()); CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE petitionguid IN ( %s )", ssInvalidPetitionGUIDs.str().c_str()); CharacterDatabase.PExecute("INSERT INTO petition (ownerguid, petitionguid, name, type) VALUES ('%u', '%u', '%s', '%u')", _player->GetGUIDLow(), charter->GetGUIDLow(), name.c_str(), type); CharacterDatabase.CommitTransaction(); } void WorldSession::HandlePetitionShowSignOpcode(WorldPacket & recv_data) { // ok DEBUG_LOG("Received opcode CMSG_PETITION_SHOW_SIGNATURES"); //recv_data.hexlike(); uint8 signs = 0; uint64 petitionguid; recv_data >> petitionguid; // petition guid // solve (possible) some strange compile problems with explicit use GUID_LOPART(petitionguid) at some GCC versions (wrong code optimization in compiler?) uint32 petitionguid_low = GUID_LOPART(petitionguid); QueryResult *result = CharacterDatabase.PQuery("SELECT type FROM petition WHERE petitionguid = '%u'", petitionguid_low); if(!result) { sLog.outError("any petition on server..."); return; } Field *fields = result->Fetch(); uint32 type = fields[0].GetUInt32(); delete result; // if guild petition and has guild => error, return; if(type == 9 && _player->GetGuildId()) return; result = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE petitionguid = '%u'", petitionguid_low); // result==NULL also correct in case no sign yet if(result) signs = (uint8)result->GetRowCount(); DEBUG_LOG("CMSG_PETITION_SHOW_SIGNATURES petition entry: '%u'", petitionguid_low); WorldPacket data(SMSG_PETITION_SHOW_SIGNATURES, (8+8+4+1+signs*12)); data << uint64(petitionguid); // petition guid data << _player->GetObjectGuid(); // owner guid data << uint32(petitionguid_low); // guild guid (in mangos always same as GUID_LOPART(petitionguid) data << uint8(signs); // sign's count for(uint8 i = 1; i <= signs; ++i) { Field *fields2 = result->Fetch(); uint64 plguid = fields2[0].GetUInt64(); data << uint64(plguid); // Player GUID data << uint32(0); // there 0 ... result->NextRow(); } delete result; SendPacket(&data); } void WorldSession::HandlePetitionQueryOpcode(WorldPacket & recv_data) { DEBUG_LOG("Received opcode CMSG_PETITION_QUERY"); //recv_data.hexlike(); uint32 guildguid; ObjectGuid petitionguid; recv_data >> guildguid; // in mangos always same as GUID_LOPART(petitionguid) recv_data >> petitionguid; // petition guid DEBUG_LOG("CMSG_PETITION_QUERY Petition %s Guild GUID %u", petitionguid.GetString().c_str(), guildguid); SendPetitionQueryOpcode(petitionguid); } void WorldSession::SendPetitionQueryOpcode(ObjectGuid petitionguid) { uint32 petitionLowGuid = petitionguid.GetCounter(); ObjectGuid ownerguid; uint32 type; std::string name = "NO_NAME_FOR_GUID"; uint8 signs = 0; QueryResult *result = CharacterDatabase.PQuery( "SELECT ownerguid, name, " " (SELECT COUNT(playerguid) FROM petition_sign WHERE petition_sign.petitionguid = '%u') AS signs, " " type " "FROM petition WHERE petitionguid = '%u'", petitionLowGuid, petitionLowGuid); if (result) { Field* fields = result->Fetch(); ownerguid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); name = fields[1].GetCppString(); signs = fields[2].GetUInt8(); type = fields[3].GetUInt32(); delete result; } else { DEBUG_LOG("CMSG_PETITION_QUERY failed for petition (GUID: %u)", petitionLowGuid); return; } WorldPacket data(SMSG_PETITION_QUERY_RESPONSE, (4+8+name.size()+1+1+4*13)); data << uint32(petitionLowGuid); // guild/team guid (in mangos always same as GUID_LOPART(petition guid) data << ownerguid; // charter owner guid data << name; // name (guild/arena team) data << uint8(0); // 1 if (type == 9) { data << uint32(9); data << uint32(9); data << uint32(0); // bypass client - side limitation, a different value is needed here for each petition } else { data << type-1; data << type-1; data << type; // bypass client - side limitation, a different value is needed here for each petition } data << uint32(0); // 5 data << uint32(0); // 6 data << uint32(0); // 7 data << uint32(0); // 8 data << uint16(0); // 9 2 bytes field data << uint32(0); // 10 data << uint32(0); // 11 data << uint32(0); // 13 count of next strings? data << uint32(0); // 14 if (type == 9) data << uint32(0); // 15 0 - guild, 1 - arena team else data << uint32(1); SendPacket(&data); } void WorldSession::HandlePetitionRenameOpcode(WorldPacket & recv_data) { DEBUG_LOG("Received opcode MSG_PETITION_RENAME"); // ok //recv_data.hexlike(); uint64 petitionguid; uint32 type; std::string newname; recv_data >> petitionguid; // guid recv_data >> newname; // new name Item *item = _player->GetItemByGuid(petitionguid); if(!item) return; QueryResult *result = CharacterDatabase.PQuery("SELECT type FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); if(result) { Field* fields = result->Fetch(); type = fields[0].GetUInt32(); delete result; } else { DEBUG_LOG("CMSG_PETITION_QUERY failed for petition (GUID: %u)", GUID_LOPART(petitionguid)); return; } if(type == 9) { if(sObjectMgr.GetGuildByName(newname)) { SendGuildCommandResult(GUILD_CREATE_S, newname, ERR_GUILD_NAME_EXISTS_S); return; } if(sObjectMgr.IsReservedName(newname) || !ObjectMgr::IsValidCharterName(newname)) { SendGuildCommandResult(GUILD_CREATE_S, newname, ERR_GUILD_NAME_INVALID); return; } } else { if(sObjectMgr.GetArenaTeamByName(newname)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, newname, "", ERR_ARENA_TEAM_NAME_EXISTS_S); return; } if(sObjectMgr.IsReservedName(newname) || !ObjectMgr::IsValidCharterName(newname)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, newname, "", ERR_ARENA_TEAM_NAME_INVALID); return; } } std::string db_newname = newname; CharacterDatabase.escape_string(db_newname); CharacterDatabase.PExecute("UPDATE petition SET name = '%s' WHERE petitionguid = '%u'", db_newname.c_str(), GUID_LOPART(petitionguid)); DEBUG_LOG("Petition (GUID: %u) renamed to '%s'", GUID_LOPART(petitionguid), newname.c_str()); WorldPacket data(MSG_PETITION_RENAME, (8+newname.size()+1)); data << uint64(petitionguid); data << newname; SendPacket(&data); } void WorldSession::HandlePetitionSignOpcode(WorldPacket & recv_data) { DEBUG_LOG("Received opcode CMSG_PETITION_SIGN"); // ok //recv_data.hexlike(); Field *fields; ObjectGuid petitionGuid; uint8 unk; recv_data >> petitionGuid; // petition guid recv_data >> unk; uint32 petitionLowGuid = petitionGuid.GetCounter(); QueryResult *result = CharacterDatabase.PQuery( "SELECT ownerguid, " " (SELECT COUNT(playerguid) FROM petition_sign WHERE petition_sign.petitionguid = '%u') AS signs, " " type " "FROM petition WHERE petitionguid = '%u'", petitionLowGuid, petitionLowGuid); if(!result) { sLog.outError("any petition on server..."); return; } fields = result->Fetch(); uint32 ownerLowGuid = fields[0].GetUInt32(); ObjectGuid ownerguid = ObjectGuid(HIGHGUID_PLAYER, ownerLowGuid); uint8 signs = fields[1].GetUInt8(); uint32 type = fields[2].GetUInt32(); delete result; if (ownerguid == _player->GetObjectGuid()) return; // not let enemies sign guild charter if (!sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GUILD) && GetPlayer()->GetTeam() != sObjectMgr.GetPlayerTeamByGUID(ownerguid)) { if(type != 9) SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", "", ERR_ARENA_TEAM_NOT_ALLIED); else SendGuildCommandResult(GUILD_CREATE_S, "", ERR_GUILD_NOT_ALLIED); return; } if(type != 9) { if(_player->getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, "", _player->GetName(), ERR_ARENA_TEAM_TARGET_TOO_LOW_S); return; } uint8 slot = ArenaTeam::GetSlotByType(type); if(slot >= MAX_ARENA_SLOT) return; if(_player->GetArenaTeamId(slot)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", _player->GetName(), ERR_ALREADY_IN_ARENA_TEAM_S); return; } if(_player->GetArenaTeamIdInvited()) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", _player->GetName(), ERR_ALREADY_INVITED_TO_ARENA_TEAM_S); return; } } else { if(_player->GetGuildId()) { SendGuildCommandResult(GUILD_INVITE_S, _player->GetName(), ERR_ALREADY_IN_GUILD_S); return; } if(_player->GetGuildIdInvited()) { SendGuildCommandResult(GUILD_INVITE_S, _player->GetName(), ERR_ALREADY_INVITED_TO_GUILD_S); return; } } if(++signs > type) // client signs maximum return; //client doesn't allow to sign petition two times by one character, but not check sign by another character from same account //not allow sign another player from already sign player account result = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE player_account = '%u' AND petitionguid = '%u'", GetAccountId(), petitionLowGuid); if(result) { delete result; WorldPacket data(SMSG_PETITION_SIGN_RESULTS, (8+8+4)); data << petitionGuid; data << _player->GetObjectGuid(); data << uint32(PETITION_SIGN_ALREADY_SIGNED); // close at signer side SendPacket(&data); // update for owner if online if(Player *owner = sObjectMgr.GetPlayer(ownerguid)) owner->GetSession()->SendPacket(&data); return; } CharacterDatabase.PExecute("INSERT INTO petition_sign (ownerguid,petitionguid, playerguid, player_account) VALUES ('%u', '%u', '%u','%u')", ownerLowGuid, petitionLowGuid, _player->GetGUIDLow(), GetAccountId()); DEBUG_LOG("PETITION SIGN: GUID %u by player: %s (GUID: %u Account: %u)", petitionLowGuid, _player->GetName(), _player->GetGUIDLow(), GetAccountId()); WorldPacket data(SMSG_PETITION_SIGN_RESULTS, (8+8+4)); data << petitionGuid; data << _player->GetObjectGuid(); data << uint32(PETITION_SIGN_OK); // close at signer side SendPacket(&data); // update signs count on charter, required testing... //Item *item = _player->GetItemByGuid(petitionguid)); //if(item) // item->SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1+1, signs); // update for owner if online if(Player *owner = sObjectMgr.GetPlayer(ownerguid)) owner->GetSession()->SendPacket(&data); } void WorldSession::HandlePetitionDeclineOpcode(WorldPacket & recv_data) { DEBUG_LOG("Received opcode MSG_PETITION_DECLINE"); // ok //recv_data.hexlike(); ObjectGuid petitionGuid; recv_data >> petitionGuid; // petition guid DEBUG_LOG("Petition %s declined by %s", petitionGuid.GetString().c_str(), _player->GetObjectGuid().GetString().c_str()); uint32 petitionLowGuid = petitionGuid.GetCounter(); QueryResult *result = CharacterDatabase.PQuery("SELECT ownerguid FROM petition WHERE petitionguid = '%u'", petitionLowGuid); if (!result) return; Field *fields = result->Fetch(); ObjectGuid ownerguid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); delete result; Player *owner = sObjectMgr.GetPlayer(ownerguid); if(owner) // petition owner online { WorldPacket data(MSG_PETITION_DECLINE, 8); data << _player->GetObjectGuid(); owner->GetSession()->SendPacket(&data); } } void WorldSession::HandleOfferPetitionOpcode(WorldPacket & recv_data) { DEBUG_LOG("Received opcode CMSG_OFFER_PETITION"); // ok //recv_data.hexlike(); uint8 signs = 0; uint64 petitionguid, plguid; uint32 type, junk; Player *player; recv_data >> junk; // this is not petition type! recv_data >> petitionguid; // petition guid recv_data >> plguid; // player guid player = ObjectAccessor::FindPlayer(plguid); if (!player) return; QueryResult *result = CharacterDatabase.PQuery("SELECT type FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); if (!result) return; Field *fields = result->Fetch(); type = fields[0].GetUInt32(); delete result; DEBUG_LOG("OFFER PETITION: type %u, GUID1 %u, to player id: %u", type, GUID_LOPART(petitionguid), GUID_LOPART(plguid)); if (!sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GUILD) && GetPlayer()->GetTeam() != player->GetTeam() ) { if(type != 9) SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", "", ERR_ARENA_TEAM_NOT_ALLIED); else SendGuildCommandResult(GUILD_CREATE_S, "", ERR_GUILD_NOT_ALLIED); return; } if(type != 9) { if(player->getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) { // player is too low level to join an arena team SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, "", player->GetName(), ERR_ARENA_TEAM_TARGET_TOO_LOW_S); return; } uint8 slot = ArenaTeam::GetSlotByType(type); if(slot >= MAX_ARENA_SLOT) return; if(player->GetArenaTeamId(slot)) { // player is already in an arena team SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, "", player->GetName(), ERR_ALREADY_IN_ARENA_TEAM_S); return; } if(player->GetArenaTeamIdInvited()) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_INVITE_SS, "", _player->GetName(), ERR_ALREADY_INVITED_TO_ARENA_TEAM_S); return; } } else { if(player->GetGuildId()) { SendGuildCommandResult(GUILD_INVITE_S, _player->GetName(), ERR_ALREADY_IN_GUILD_S); return; } if(player->GetGuildIdInvited()) { SendGuildCommandResult(GUILD_INVITE_S, _player->GetName(), ERR_ALREADY_INVITED_TO_GUILD_S); return; } } result = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); // result==NULL also correct charter without signs if(result) signs = (uint8)result->GetRowCount(); WorldPacket data(SMSG_PETITION_SHOW_SIGNATURES, (8+8+4+signs+signs*12)); data << uint64(petitionguid); // petition guid data << _player->GetObjectGuid(); // owner guid data << uint32(GUID_LOPART(petitionguid)); // guild guid (in mangos always same as GUID_LOPART(petition guid) data << uint8(signs); // sign's count for(uint8 i = 1; i <= signs; ++i) { Field *fields2 = result->Fetch(); plguid = fields2[0].GetUInt64(); data << uint64(plguid); // Player GUID data << uint32(0); // there 0 ... result->NextRow(); } delete result; player->GetSession()->SendPacket(&data); } void WorldSession::HandleTurnInPetitionOpcode(WorldPacket & recv_data) { DEBUG_LOG("Received opcode CMSG_TURN_IN_PETITION"); // ok //recv_data.hexlike(); WorldPacket data; uint64 petitionguid; uint32 ownerguidlo; uint32 type; std::string name; recv_data >> petitionguid; DEBUG_LOG("Petition %u turned in by %u", GUID_LOPART(petitionguid), _player->GetGUIDLow()); // data QueryResult *result = CharacterDatabase.PQuery("SELECT ownerguid, name, type FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); if(result) { Field *fields = result->Fetch(); ownerguidlo = fields[0].GetUInt32(); name = fields[1].GetCppString(); type = fields[2].GetUInt32(); delete result; } else { sLog.outError("petition table has broken data!"); return; } if(type == 9) { if(_player->GetGuildId()) { data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4); data << uint32(PETITION_TURN_ALREADY_IN_GUILD); // already in guild _player->GetSession()->SendPacket(&data); return; } } else { uint8 slot = ArenaTeam::GetSlotByType(type); if(slot >= MAX_ARENA_SLOT) return; if(_player->GetArenaTeamId(slot)) { //data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4); //data << (uint32)PETITION_TURN_ALREADY_IN_GUILD; // already in guild //_player->GetSession()->SendPacket(&data); SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ALREADY_IN_ARENA_TEAM); return; } } if(_player->GetGUIDLow() != ownerguidlo) return; // signs uint8 signs; result = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); if(result) signs = (uint8)result->GetRowCount(); else signs = 0; uint32 count; //if(signs < sWorld.getConfig(CONFIG_UINT32_MIN_PETITION_SIGNS)) if(type == 9) count = sWorld.getConfig(CONFIG_UINT32_MIN_PETITION_SIGNS); else count = type - 1; if(signs < count) { data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4); data << uint32(PETITION_TURN_NEED_MORE_SIGNATURES); // need more signatures... SendPacket(&data); delete result; return; } if(type == 9) { if(sObjectMgr.GetGuildByName(name)) { SendGuildCommandResult(GUILD_CREATE_S, name, ERR_GUILD_NAME_EXISTS_S); delete result; return; } } else { if(sObjectMgr.GetArenaTeamByName(name)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_EXISTS_S); delete result; return; } } // and at last charter item check Item *item = _player->GetItemByGuid(petitionguid); if(!item) { delete result; return; } // OK! // delete charter item _player->DestroyItem(item->GetBagSlot(), item->GetSlot(), true); if(type == 9) // create guild { Guild* guild = new Guild; if(!guild->Create(_player, name)) { delete guild; delete result; return; } // register guild and add guildmaster sObjectMgr.AddGuild(guild); // add members for(uint8 i = 0; i < signs; ++i) { Field* fields = result->Fetch(); ObjectGuid signguid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); if (signguid.IsEmpty()) continue; guild->AddMember(signguid, guild->GetLowestRank()); result->NextRow(); } } else // or arena team { ArenaTeam* at = new ArenaTeam; if (!at->Create(_player->GetObjectGuid(), type, name)) { sLog.outError("PetitionsHandler: arena team create failed."); delete at; delete result; return; } uint32 icon, iconcolor, border, bordercolor, backgroud; recv_data >> backgroud >> icon >> iconcolor >> border >> bordercolor; at->SetEmblem(backgroud, icon, iconcolor, border, bordercolor); // register team and add captain sObjectMgr.AddArenaTeam(at); DEBUG_LOG("PetitonsHandler: arena team added to objmrg"); // add members for(uint8 i = 0; i < signs; ++i) { Field* fields = result->Fetch(); ObjectGuid memberGUID = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); if (memberGUID.IsEmpty()) continue; DEBUG_LOG("PetitionsHandler: adding arena member %s", memberGUID.GetString().c_str()); at->AddMember(memberGUID); result->NextRow(); } } delete result; CharacterDatabase.BeginTransaction(); CharacterDatabase.PExecute("DELETE FROM petition WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE petitionguid = '%u'", GUID_LOPART(petitionguid)); CharacterDatabase.CommitTransaction(); // created DEBUG_LOG("TURN IN PETITION GUID %u", GUID_LOPART(petitionguid)); data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4); data << uint32(PETITION_TURN_OK); SendPacket(&data); } void WorldSession::HandlePetitionShowListOpcode(WorldPacket & recv_data) { DEBUG_LOG("Received CMSG_PETITION_SHOWLIST"); // ok //recv_data.hexlike(); uint64 guid; recv_data >> guid; SendPetitionShowList(guid); } void WorldSession::SendPetitionShowList(uint64 guid) { Creature *pCreature = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_PETITIONER); if (!pCreature) { DEBUG_LOG("WORLD: HandlePetitionShowListOpcode - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(guid))); return; } // remove fake death if(GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); uint8 count = 0; if(pCreature->isTabardDesigner()) count = 1; else count = 3; WorldPacket data(SMSG_PETITION_SHOWLIST, 8+1+4*6); data << uint64(guid); // npc guid data << uint8(count); // count if(count == 1) { data << uint32(1); // index data << uint32(GUILD_CHARTER); // charter entry data << uint32(CHARTER_DISPLAY_ID); // charter display id data << uint32(GUILD_CHARTER_COST); // charter cost data << uint32(0); // unknown data << uint32(9); // required signs? } else { // 2v2 data << uint32(1); // index data << uint32(ARENA_TEAM_CHARTER_2v2); // charter entry data << uint32(CHARTER_DISPLAY_ID); // charter display id data << uint32(ARENA_TEAM_CHARTER_2v2_COST); // charter cost data << uint32(2); // unknown data << uint32(2); // required signs? // 3v3 data << uint32(2); // index data << uint32(ARENA_TEAM_CHARTER_3v3); // charter entry data << uint32(CHARTER_DISPLAY_ID); // charter display id data << uint32(ARENA_TEAM_CHARTER_3v3_COST); // charter cost data << uint32(3); // unknown data << uint32(3); // required signs? // 5v5 data << uint32(3); // index data << uint32(ARENA_TEAM_CHARTER_5v5); // charter entry data << uint32(CHARTER_DISPLAY_ID); // charter display id data << uint32(ARENA_TEAM_CHARTER_5v5_COST); // charter cost data << uint32(5); // unknown data << uint32(5); // required signs? } //for(uint8 i = 0; i < count; ++i) //{ // data << uint32(i); // index // data << uint32(GUILD_CHARTER); // charter entry // data << uint32(CHARTER_DISPLAY_ID); // charter display id // data << uint32(GUILD_CHARTER_COST+i); // charter cost // data << uint32(0); // unknown // data << uint32(9); // required signs? //} SendPacket(&data); DEBUG_LOG("Sent SMSG_PETITION_SHOWLIST"); }
MiLk/mangos
src/game/PetitionsHandler.cpp
C++
gpl-2.0
34,581
<?php /* Template Name:aboutus */ ?> <?php get_header(); ?> <div class="about_bt"> <div class="about_bt_ka"> <div class="about_bt_left"> <h1>ABOUT US</h1> <p>关于我们</p> </div> <div class="about_bt_right"> <a href="<?php echo get_option('mytheme_news_title'); ?>"> <img src="<? bloginfo('template_url'); ?>/images/pages/aboutus_03.png" /></a> <a href=" <?php $name = 'contact'; //page别名 global $wpdb; $page_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '$name'"); echo get_page_link( $page_id );?>"><img src="<? bloginfo('template_url'); ?>/images/pages/aboutus_05.png" /></a> </div> </div> </div> <div class="maim_pages"> <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/xuant.js"></script> <div class="jiao"> <DIV id=imgPlay> <UL class=imgs id=actor> <LI> <?php if (get_option('mytheme_about_text1')!=""): ?> <img src="<?php echo get_option('mytheme_about_text1'); ?>" /> <?php else : ?> <img src="<? bloginfo('template_url'); ?>/images/jiao_05.gif" /> <?php endif; ?> </LI> <LI> <div class="imgplay_wen"> <h1>ABOUT US</h1><h1>关于我们</h1> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php the_content(); ?> <?php endwhile; ?> <?php else : ?> <?php endif; ?> </div> <?php if (get_option('mytheme_about_tit1')!=""): ?> <img src="<?php echo get_option('mytheme_about_tit1'); ?>" width="369" height="480" /> <?php else : ?> <img src="<? bloginfo('template_url'); ?>/images/about_07.gif" width="369" height="480" /> <?php endif; ?> </LI> <LI> <?php if (get_option('mytheme_about_img1')!=""): ?> <img src="<?php echo get_option('mytheme_about_img1'); ?>" /> <?php else : ?> <img src="<? bloginfo('template_url'); ?>/images/jiao_06.gif" /> <?php endif; ?> </LI> <LI> <?php if (get_option('mytheme_about_url1')!=""): ?> <img src="<?php echo get_option('mytheme_about_url1'); ?>" /> <?php else : ?> <img src="<? bloginfo('template_url'); ?>/images/jiao_05.gif" /> <?php endif; ?> </LI> </UL> <DIV class=prev><img src="<? bloginfo('template_url'); ?>/images/prev.png" /></DIV> <DIV class=next><img src="<? bloginfo('template_url'); ?>/images/next.png" /></DIV></DIV> </div> </DIV> <?php get_footer(); ?>
xiaofanmeirong/weizhen
wp-content/themes/wood-themes/aboutus.php
PHP
gpl-2.0
2,587
package com.example.kickfor; import com.example.kickfor.team.ChangingRoomEntity; import android.os.Handler; import android.os.Message; public class ProgressBarTimer implements Runnable{ private Object v=null; private Handler handler=null; private int what=-1; private Object b=null; public ProgressBarTimer(Handler handler, int what, Object v, Object b){ this.handler=handler; this.what=what; this.v=v; this.b=b; } @Override public void run() { // TODO Auto-generated method stub try{ Thread.sleep(10000); }catch(Exception e){ e.printStackTrace(); } if(b!=null && b instanceof ChangingRoomEntity){ ((ChangingRoomEntity)b).pb1=true; ((ChangingRoomEntity)b).pb2=true; Message msg=handler.obtainMessage(); msg.obj=v; msg.what=what; handler.sendMessage(msg); } else{ Message msg=handler.obtainMessage(); msg.obj=v; msg.what=what; handler.sendMessage(msg); } } }
yumjade/KickFor
src/com/example/kickfor/ProgressBarTimer.java
Java
gpl-2.0
941
<?php // Bloxx - Open Source Content Management System // // Copyright (c) 2002 - 2005 The Bloxx Team. All rights reserved. // // Bloxx 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. // // Bloxx 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 Bloxx; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Authors: Telmo Menezes <telmo@cognitiva.net> // // $Id: bloxx_lang_PT_personalinfo.php,v 1.3 2005-02-18 17:34:56 tmenezes Exp $ define('F_LANG_PERSONALINFO_USER_ID', 'ID do Utilizador'); define('F_LANG_PERSONALINFO_FULL_NAME', 'Nome Completo'); define('F_LANG_PERSONALINFO_ADDRESS', 'Morada'); define('F_LANG_PERSONALINFO_POSTAL_CODE', 'Código Postal'); define('F_LANG_PERSONALINFO_CITY', 'Cidade'); define('F_LANG_PERSONALINFO_PHONE_HOME', 'Telefone de Casa'); define('F_LANG_PERSONALINFO_PHONE_WORK', 'Telefone do Trabalho'); define('F_LANG_PERSONALINFO_PHONE_MOBILE', 'Telemóvel'); define('F_LANG_PERSONALINFO_BIRTH_DATE', 'Data de Nascimento'); define('F_LANG_PERSONALINFO_INFO', 'Informações'); define('LANG_PERSONALINFO_CREATE_INFO', 'Criar informação pessoal'); define('LANG_PERSONALINFO_EDIT_INFO', 'Editar informação pessoal'); ?>
telmomenezes/bloxx
lang/PT/bloxx_lang_PT_personalinfo.php
PHP
gpl-2.0
1,664
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RielAp.Domain.Models { public class Order : IModel { public Guid OrderId { get; set; } public string Description { get; set; } public decimal Ammount { get; set; } public DateTime Created { get; set; } public string Status { get; set; } [ForeignKey("Profile")] public int ProfileId { get; set; } public virtual Profile Profile { get; set; } [ForeignKey("User")] public int UserId { get; set; } public virtual User User { get; set; } } }
tarashor/Rielstartup
RielAp.Domain/Models/Order.cs
C#
gpl-2.0
722
<?php /** * Header Template * * Please do not edit this file. This file is part of the Cyber Chimps Framework and all modifications * should be made in a child theme. * * @category CyberChimps Framework * @package Framework * @since 1.0 * @author CyberChimps * @license http://www.opensource.org/licenses/gpl-license.php GPL v3.0 (or later) * @link http://www.cyberchimps.com/ */ ?> <!DOCTYPE html> <!--[if lt IE 7]> <html class="ie ie6 lte9 lte8 lte7" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 7]> <html class="ie ie7 lte9 lte8 lte7" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 8]> <html class="ie ie8 lte9 lte8" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 9]> <html class="ie ie9" <?php language_attributes(); ?>> <![endif]--> <!--[if gt IE 9]> <html <?php language_attributes(); ?>> <![endif]--> <!--[if !IE]><!--> <html <?php language_attributes(); ?>> <!--<![endif]--> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"/> <meta name="viewport" content="width=device-width"/> <title><?php wp_title( '' ); ?></title> <link rel="profile" href="http://gmpg.org/xfn/11"/> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>"/> <!-- IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="<?php echo get_template_directory_uri(); ?>/inc/js/html5.js" type="text/javascript"></script> <![endif]--> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <div id="top_header" class="container-full-width"> <div class="container"> <div id="wrapper" class="container-fluid"> <div class="row-fluid"> <div class="span6"> <div class="top-head-description"> <?php echo get_bloginfo( 'description' ); ?> </div> <!-- description --> </div> <!-- span 6 --> <div class="top-head-social span6"> <?php cyberchimps_header_social_icons(); ?> </div> <!-- top head social --> </div> <!-- row fluid --> </div> <!-- wrapper --> </div> <!-- container --> </div> <!-- top header --> <div id="main_header" class="container-full-width"> <div class="container"> <div id="wrapper" class="container-fluid"> <div class="row-fluid"> <div class="span6"> <?php do_action( 'cyberchimps_header' ); ?> </div> <div class="span6"> <?php do_action( 'cyberchimps_before_navigation' ); ?> <nav id="navigation" role="navigation"> <div class="main-navigation navbar"> <div class="navbar-inner"> <div class="container"> <?php /* hide collapsing menu if not responsive */ if (cyberchimps_get_option( 'responsive_design', 'checked' )): ?> <div class="nav-collapse collapse"> <?php endif; ?> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav', 'walker' => new cyberchimps_walker(), 'fallback_cb' => 'cyberchimps_fallback_menu' ) ); ?> <?php /* hide collapsing menu if not responsive */ if (cyberchimps_get_option( 'responsive_design', 'checked' )): ?> </div> <!-- collapse --> <!-- .btn-navbar is used as the toggle for collapsed navbar content --> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <?php endif; ?> </div> <!-- container --> </div> <!-- .navbar-inner .row-fluid --> </div> <!-- main-navigation navbar --> </nav> <!-- #navigation --> <?php do_action( 'cyberchimps_after_navigation' ); ?> </div> <!-- nav span 6 --> </div> <!-- row-fluid --> </div> <!-- wrapper --> </div> <!-- container --> </div> <!-- main header --> <?php do_action( 'cyberchimps_before_wrapper' ); ?>
campusIdOpenRov/campusrovblog
wp-content/themes/eclipse/header.php
PHP
gpl-2.0
3,888
<?php /** * Created by PhpStorm. * User: ROGER * Date: 16.03.14 * Time: 04:08 */ add_action('admin_notices', 'my_admin_notice'); function my_admin_notice() { $set_errors = get_settings_errors(); if (!isset($_SESSION['page_for_posts']) || !isset($_SESSION['page_on_front'])) { $_SESSION['page_for_posts'] = get_option('page_for_posts'); $_SESSION['page_on_front'] = get_option('page_on_front'); } if (current_user_can('manage_options') && !empty($set_errors) && $_SERVER['PHP_SELF'] === '/wp-admin/options-reading.php' ) { if ($set_errors[0]['code'] == 'settings_updated' && isset($_GET['settings-updated']) && ($_SESSION['page_for_posts'] !== get_option('page_for_posts') || $_SESSION['page_on_front'] !== get_option('page_on_front')) ) { $_SESSION['page_for_posts'] = get_option('page_for_posts'); $_SESSION['page_on_front'] = get_option('page_on_front'); if (get_option('show_on_front') == 'page') { echo '<div id="message" class="updated "> <p>Please, don\'t forget to update your Blog page. Click here: <a href="' . admin_url ('edit.php?post_type=page') . '">Edit Pages</a> </p> </div>'; } else { echo '<div id="message" class="updated "> <p>Please, don\'t forget to update Front and Posts pages. Click here: <a href="' . admin_url ('edit.php?post_type=page') . '">Edit Pages</a> </p> </div>'; } } } }
HRoger/angularpresstheme
library/inc/angular/admin/reading-settings.php
PHP
gpl-2.0
1,450
<?php namespace Shippingpickup; use Sumo; use App; class ModelSetup extends App\Model { public function install() { Sumo\Database::query(" CREATE TABLE IF NOT EXISTS PREFIX_app_shippingpickup ( `setting_id` int(11) NOT NULL AUTO_INCREMENT, `store_id` int(11) NOT NULL, `setting_name` varchar(255) NOT NULL, `setting_value` text, `json` int(1) DEFAULT 0, PRIMARY KEY (`setting_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; "); return true; } public function deinstall() { Sumo\Database::query("DROP TABLE IF EXISTS PREFIX_app_shippingpickup"); return true; } public function wasInstalled() { try { $this->select(); return true; } catch (\Exception $e) { return false; } return true; } }
wardvanderput/SumoStore
upload/apps/shippingpickup/model/setup.php
PHP
gpl-2.0
975
<?php /** * @copyright Ilch 2.0 * @package ilch */ return [ 'menuRules' => 'Rules', 'paragraph' => 'Paragraph', 'title' => 'Title', 'text' => 'Text', 'noRules' => 'No rules available', ];
Saarlonz/Ilch-2.0
application/modules/rule/translations/en.php
PHP
gpl-2.0
212
<?php /* * Add-on Name: Advanced Image * Add-on URI: http://highgradelab.com/plugins/highgrade-extender/ * Since: 1.0 * Author: Eugen Petcu */ if(!class_exists('HGR_VC_ADVIMAGE')) { class HGR_VC_ADVIMAGE { function __construct() { add_action('admin_init', array($this, 'hgr_advimage_init')); } /* Visual Composer mapping function Public API Refference: http://kb.wpbakery.com/index.php?title=Vc_map Example: http://kb.wpbakery.com/index.php?title=Visual_Composer_tutorial */ function hgr_advimage_init() { if(function_exists('vc_map')) { vc_map( array( "name" => __("HGR Advanced Image", "hgr_lang"), "holder" => "div", "base" => "hgr_advimage", "class" => "", "icon" => "hgr_advimage", "description" => __("Image with advanced parameters", "hgr_lang"), "category" => __("HighGrade Extender", "hgr_lang"), "content_element" => true, "params" => array( array( "type" => "attach_image", "class" => "", "heading" => __("Image:", "hgr_lang"), "param_name" => "hgr_advimage_image", "admin_label" => true, "value" => "", "description" => __("Upload or select image to use", "hgr_lang"), ), array( "type" => "colorpicker", "class" => "", "heading" => __("Image overlay color:", "hgr_lang"), "param_name" => "hgr_advimage_overlaycolor", "value" => "", "description" => __("Select overlay color on mouseover image.", "hgr_lang"), ), array( "type" => "colorpicker", "class" => "", "heading" => __("Overlay text color:", "hgr_lang"), "param_name" => "hgr_advimage_overlaytextcolor", "value" => "#000000", "description" => __("Select overlay text color.", "hgr_lang"), ), array( "type" => "vc_link", "class" => "", "heading" => __("General link on overlay","hgr_lang"), "param_name" => "hgr_advimage_overlaylink", "value" => "", "description" => __("Optional link on overlay","hgr_lang"), ), array( "type" => "textarea", "class" => "", "heading" => __("Overlay content:","hgr_lang"), "param_name" => "hgr_advimage_overlaycontent", "value" => "", "description" => __("Insert the content to be displayed on image hover.","hgr_lang") ), ) ) ); } } } new HGR_VC_ADVIMAGE; }
domowit/BOOTSTRAP_V2
wp-content/plugins/hgr_vc_extender/elements/hgr_xtnd_advanced_image.php
PHP
gpl-2.0
2,596
package it.unimarconi.utils; import it.unimarconi.beans.Job; import java.util.Comparator; public class JobComparator implements Comparator<Job> { public int compare(Job a, Job b) { return a.compareTo(b); } }
Kalimaha/MLS_Barbaglia
src/main/java/it/unimarconi/utils/JobComparator.java
Java
gpl-2.0
228
<?php /** Latvian (latviešu) * * See MessagesQqq.php for message documentation incl. usage of parameters * To improve a translation please visit http://translatewiki.net * * @ingroup Language * @file * * @author Admresdeserv. * @author Dark Eagle * @author FnTmLV * @author Geimeris * @author Gleb Borisov * @author GreenZeb * @author Kaganer * @author Karlis * @author Kikos * @author Knakts * @author Marozols * @author Papuass * @author Reedy * @author Xil * @author Yyy * @author לערי ריינהארט */ /** * @copyright Copyright © 2006, Niklas Laxström * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 2.0 or later */ $namespaceNames = array( NS_MEDIA => 'Media', NS_SPECIAL => 'Special', NS_TALK => 'Diskusija', NS_USER => 'Lietotājs', NS_USER_TALK => 'Lietotāja_diskusija', NS_PROJECT_TALK => '{{grammar:ģenitīvs|$1}}_diskusija', NS_FILE => 'Attēls', NS_FILE_TALK => 'Attēla_diskusija', NS_MEDIAWIKI => 'MediaWiki', NS_MEDIAWIKI_TALK => 'MediaWiki_diskusija', NS_TEMPLATE => 'Veidne', NS_TEMPLATE_TALK => 'Veidnes_diskusija', NS_HELP => 'Palīdzība', NS_HELP_TALK => 'Palīdzības_diskusija', NS_CATEGORY => 'Kategorija', NS_CATEGORY_TALK => 'Kategorijas_diskusija', ); $separatorTransformTable = array( ',' => "\xc2\xa0", '.' => ',' ); $messages = array( # User preference toggles 'tog-underline' => 'Pasvītrot saites:', 'tog-highlightbroken' => 'Saites uz neesošām lapām rādīt <a href="" class="new">šādi</a> (alternatīva: šādi<a href="" class="internal">?</a>).', 'tog-justify' => 'Izlīdzināt rindkopām abas malas', 'tog-hideminor' => 'Paslēpt maznozīmīgus labojumus pēdējo izmaiņu lapā', 'tog-hidepatrolled' => 'Slēpt apstiprinātās izmaņas pēdējo izmaiņu sarakstā', 'tog-newpageshidepatrolled' => 'Paslēpt pārbaudītās lapas jauno lapu sarakstā', 'tog-extendwatchlist' => 'Izvērst uzraugāmo lapu sarakstu, lai parādītu visas veiktās izmaiņas (ne tikai pašas svaigākās)', 'tog-usenewrc' => "Grupēt izmaiņas pēc lapas pēdējās izmaiņās un uzraugāmo lapu sarakstā (izmanto ''JavaScript'')", 'tog-numberheadings' => 'Automātiski numurēt virsrakstus', 'tog-showtoolbar' => 'Rādīt rediģēšanas rīkjoslu', 'tog-editondblclick' => "Atvērt rediģēšanas lapu ar dubultklikšķi (izmanto ''JavaScript'')", 'tog-editsection' => 'Rādīt sadaļām izmainīšanas saiti "[labot]"', 'tog-editsectiononrightclick' => "Atvērt sadaļas rediģēšanas lapu, uzklikšķinot ar labo peles pogu uz sadaļas virsraksta (izmanto ''JavaScript'')", 'tog-showtoc' => 'Parādīt satura rādītāju (lapām, kurās ir vairāk par 3 virsrakstiem)', 'tog-rememberpassword' => 'Atcerēties manu lietotājvārdu pēc pārlūka aizvēršanas (ne vairāk kā $1 {{PLURAL:$1|diena|dienas}}).', 'tog-watchcreations' => 'Pievienot manis radītās lapas un manis augšuplādētos failus uzraugāmo lapu sarakstam', 'tog-watchdefault' => 'Pievienot manis izmainītās lapas un failus uzraugāmo lapu sarakstam', 'tog-watchmoves' => 'Pievienot manis pārvietotās lapas un failus uzraugāmo lapu sarakstam', 'tog-watchdeletion' => 'Pievienot manis izdzēstās lapas un failus uzraugāmo lapu sarakstam', 'tog-minordefault' => 'Atzīmēt visus labojumus jau sākotnēji par maznozīmīgiem', 'tog-previewontop' => 'Parādīt priekšskatījumu virs rediģēšanas lauka, nevis zem', 'tog-previewonfirst' => 'Parādīt priekšskatījumu jau uzsākot rediģēšanu', 'tog-nocache' => 'Atslēgt pārlūka lapu saglabāšanu kešatmiņā', 'tog-enotifwatchlistpages' => 'Paziņot pa e-pastu par izmaiņām uzraugāmo rakstu sarakstā esošos rakstos un failos', 'tog-enotifusertalkpages' => 'Paziņot pa e-pastu par izmaiņām manā diskusiju lapā', 'tog-enotifminoredits' => 'Paziņot pa e-pastu arī par maznozīmīgiem labojumiem rakstos un failos', 'tog-enotifrevealaddr' => 'Atklāt manu e-pasta adresi paziņojumu vēstulēs', 'tog-shownumberswatching' => 'Rādīt uzraudzītāju skaitu', 'tog-oldsig' => 'Pašreizējais paraksts:', 'tog-fancysig' => 'Vienkāršs paraksts (bez automātiskās saites)', 'tog-externaleditor' => 'Pēc noklusējuma izmantot ārēju programmu lapu izmainīšanai (tikai pieredzējušiem lietotājiem, lai darbotos nepieciešami speciāli uzstādījumi tavā datorā sk. [//www.mediawiki.org/wiki/Manual:External_editor šeit])', 'tog-externaldiff' => 'Pēc noklusējuma izmantot ārēju programmu izmaiņu parādīšanai (tikai pieredzējušiem lietotājiem, lai darbotos nepieciešami speciāli uzstādījumi tavā datorā sk. [//www.mediawiki.org/wiki/Manual:External_editor šeit])', 'tog-showjumplinks' => 'Rādīt pārlēkšanas saites', 'tog-uselivepreview' => "Lietot tūlītējo priekšskatījumu (izmanto ''JavaScript''; eksperimentāla iespēja)", 'tog-forceeditsummary' => 'Atgādināt man, ja kopsavilkuma ailīte ir tukša', 'tog-watchlisthideown' => 'Paslēpt manus labojumus uzraugāmo lapu sarakstā', 'tog-watchlisthidebots' => 'Paslēpt botu labojumus uzraugāmo lapu sarakstā', 'tog-watchlisthideminor' => 'Paslēpt maznozīmīgos labojumus uzraugāmo lapu sarakstā', 'tog-watchlisthideliu' => 'Paslēpt reģistrēto lietotāju labojumus uzraugāmo lapu sarakstā', 'tog-watchlisthideanons' => 'Paslēpt anonīmo lietotāju labojumus uzraugāmo lapu sarakstā', 'tog-watchlisthidepatrolled' => 'Paslēpt pārbaudītās lapas uzraugāmo lapu sarakstā', 'tog-ccmeonemails' => 'Sūtīt sev citiem lietotājiem nosūtīto epastu kopijas', 'tog-diffonly' => 'Nerādīt lapu saturu zem izmaiņām', 'tog-showhiddencats' => 'Rādīt slēptās kategorijas', 'tog-norollbackdiff' => 'Neņemt vērā atšķirības, veicot atriti', 'underline-always' => 'vienmēr', 'underline-never' => 'nekad', 'underline-default' => 'kā pārlūkā vai apdarē', # Font style option in Special:Preferences 'editfont-style' => 'Fonta veids rediģēšanas laukā:', 'editfont-default' => 'kā pārlūkā', 'editfont-monospace' => 'Vienplatuma fonts', 'editfont-sansserif' => 'Bezserifa fonts', 'editfont-serif' => 'Serifa fonts', # Dates 'sunday' => 'svētdiena', 'monday' => 'Pirmdiena', 'tuesday' => 'otrdiena', 'wednesday' => 'trešdiena', 'thursday' => 'ceturtdiena', 'friday' => 'piektdiena', 'saturday' => 'sestdiena', 'sun' => 'Sv', 'mon' => 'Pr', 'tue' => 'Ot', 'wed' => 'Tr', 'thu' => 'Ce', 'fri' => 'Pk', 'sat' => 'Se', 'january' => 'Janvārs', 'february' => 'Februārs', 'march' => 'martā', 'april' => 'aprīlī', 'may_long' => 'maijā', 'june' => 'jūnijā', 'july' => 'jūlijā', 'august' => 'augustā', 'september' => 'septembrī', 'october' => 'oktobrī', 'november' => 'novembrī', 'december' => 'decembrī', 'january-gen' => 'Janvāra', 'february-gen' => 'Februāra', 'march-gen' => 'Marta', 'april-gen' => 'Aprīļa', 'may-gen' => 'Maija', 'june-gen' => 'Jūnija', 'july-gen' => 'Jūlija', 'august-gen' => 'Augusta', 'september-gen' => 'Septembra', 'october-gen' => 'Oktobra', 'november-gen' => 'Novembra', 'december-gen' => 'Decembra', 'jan' => 'janvārī,', 'feb' => 'februārī,', 'mar' => 'martā,', 'apr' => 'aprīlī,', 'may' => 'maijā,', 'jun' => 'jūnijā,', 'jul' => 'jūlijā,', 'aug' => 'augustā,', 'sep' => 'septembrī,', 'oct' => 'oktobrī,', 'nov' => 'novembrī,', 'dec' => 'decembrī,', # Categories related messages 'pagecategories' => '{{PLURAL:$1|Kategorija|Kategorijas}}', 'category_header' => 'Raksti, kas ietverti kategorijā "$1".', 'subcategories' => 'Apakškategorijas', 'category-media-header' => 'Faili kategorijā "$1"', 'category-empty' => "''Šī kategorija šobrīd nesatur ne lapas, ne failus''", 'hidden-categories' => '{{PLURAL:$1|Slēpta kategorija|Slēptas kategorijas}}', 'hidden-category-category' => 'Slēptās kategorijas', 'category-subcat-count' => '{{PLURAL:$2|Šajai kategorijai ir tikai viena apakškategorija.|Šajai kategorijai ir $2 apakškategorijas, no kurām ir {{PLURAL:$1|redzama viena|redzamas $1}}.}}', 'category-subcat-count-limited' => 'Šai kategorijai ir {{PLURAL:$1|viena apakškategorija|$1 apakškategorijas}}.', 'category-article-count' => '{{PLURAL:$2|Šī kategorija satur tikai šo vienu lapu.|Šajā kategorijā kopā ir $2 lapas, šobrīd ir {{PLURAL:$1|redzama viena no tām|redzamas $1 no tām}}.}}', 'category-article-count-limited' => 'Šajā kategorijā ir {{PLURAL:$1|šī viena lapa|šīs $1 lapas}}.', 'category-file-count' => '{{PLURAL:$2|Šī kategorija satur tikai šo vienu failu.|Šajā kategorijā ir $2 faili, no kuriem {{PLURAL:$1|redzams ir viens|ir redzami $1}}.}}', 'category-file-count-limited' => 'Šajā kategorijā atrodas {{PLURAL:$1|tikai šis fails|šie $1 faili}}.', 'listingcontinuesabbrev' => ' (turpinājums)', 'index-category' => 'Indeksētās lapas', 'noindex-category' => 'Neindeksētās lapas', 'broken-file-category' => 'Lapas, kurās ir bojātas failu saites', 'about' => 'Par', 'article' => 'Raksts', 'newwindow' => '(atveras jaunā logā)', 'cancel' => 'Atcelt', 'moredotdotdot' => 'Vairāk...', 'mypage' => 'Lapa', 'mytalk' => 'Diskusijas', 'anontalk' => 'Šīs IP adreses diskusija', 'navigation' => 'Navigācija', 'and' => '&#32;un', # Cologne Blue skin 'qbfind' => 'Meklēšana', 'qbbrowse' => 'Navigācija', 'qbedit' => 'Izmainīšana', 'qbpageoptions' => 'Šī lapa', 'qbpageinfo' => 'Konteksts', 'qbmyoptions' => 'Manas lapas', 'qbspecialpages' => 'Īpašās lapas', 'faq' => 'BUJ', 'faqpage' => 'Project:BUJ', # Vector skin 'vector-action-addsection' => 'Jauna sadaļa', 'vector-action-delete' => 'Dzēst', 'vector-action-move' => 'Pārvietot', 'vector-action-protect' => 'Aizsargāt', 'vector-action-undelete' => 'Atjaunot', 'vector-action-unprotect' => 'Mainīt aizsardzību', 'vector-simplesearch-preference' => 'Ieslēgt vienkāršoto meklēšanas joslu (tikai Vector apdarē)', 'vector-view-create' => 'Izveidot', 'vector-view-edit' => 'Labot', 'vector-view-history' => 'Hronoloģija', 'vector-view-view' => 'Skatīt', 'vector-view-viewsource' => 'Aplūkot kodu', 'actions' => 'Darbības', 'namespaces' => 'Vārdtelpas', 'variants' => 'Varianti', 'errorpagetitle' => 'Kļūda', 'returnto' => 'Atgriezties: $1.', 'tagline' => "No ''{{grammar:ģenitīvs|{{SITENAME}}}}''", 'help' => 'Palīdzība', 'search' => 'Meklēt', 'searchbutton' => 'Meklēt', 'go' => 'Aiziet!', 'searcharticle' => 'Aiziet!', 'history' => 'hronoloģija', 'history_short' => 'Vēsture', 'updatedmarker' => 'atjaunināti kopš pēdējā apmeklējuma', 'printableversion' => 'Drukājama versija', 'permalink' => 'Pastāvīgā saite', 'print' => 'Drukāt', 'view' => 'Skatīt', 'edit' => 'Izmainīt šo lapu', 'create' => 'Izveidot', 'editthispage' => 'Izmainīt šo lapu', 'create-this-page' => 'Izveidot šo lapu', 'delete' => 'Dzēst', 'deletethispage' => 'Dzēst šo lapu', 'undelete_short' => 'Atjaunot $1 {{PLURAL:$1|versiju|versijas}}', 'viewdeleted_short' => 'Apskatīt {{PLURAL:$1|vienu dzēstu labojumu|$1 dzēstus labojumus}}', 'protect' => 'Aizsargāt', 'protect_change' => 'izmainīt', 'protectthispage' => 'Aizsargāt šo lapu', 'unprotect' => 'Mainīt aizsardzību', 'unprotectthispage' => 'Mainīt šīs lapas aizsardzību', 'newpage' => 'Jauna lapa', 'talkpage' => 'Diskusija par šo lapu', 'talkpagelinktext' => 'Diskusija', 'specialpage' => 'Īpašā Lapa', 'personaltools' => 'Lietotāja rīki', 'postcomment' => 'Pievienot komentāru', 'articlepage' => 'Apskatīt rakstu', 'talk' => 'Diskusija', 'views' => 'Apskates', 'toolbox' => 'Rīki', 'userpage' => 'Skatīt lietotāja lapu', 'projectpage' => 'Skatīt projekta lapu', 'imagepage' => 'Skatīt faila lapu', 'mediawikipage' => 'Skatīt paziņojuma lapu', 'templatepage' => 'Skatīt veidnes lapu', 'viewhelppage' => 'Atvērt palīdzību', 'categorypage' => 'Apskatīt kategorijas lapu', 'viewtalkpage' => 'Skatīt diskusiju', 'otherlanguages' => 'Citās valodās', 'redirectedfrom' => '(Pāradresēts no $1)', 'redirectpagesub' => 'Pāradresācijas lapa', 'lastmodifiedat' => 'Šajā lapā pēdējās izmaiņas izdarītas $2, $1.', 'viewcount' => 'Šī lapa ir tikusi apskatīta $1 {{PLURAL:$1|reizi|reizes}}.', 'protectedpage' => 'Aizsargāta lapa', 'jumpto' => 'Pārlēkt uz:', 'jumptonavigation' => 'navigācija', 'jumptosearch' => 'meklēt', 'view-pool-error' => 'Atvainojiet, šobrīd serveri ir pārslogoti. Pārāk daudz lietotāju mēģina apskatīt šo lapu. Lūdzu, brīdi uzgaidiet un mēģiniet šo lapu apskatīties vēlreiz. $1', 'pool-errorunknown' => 'Nezināma kļūda', # All link text and link target definitions of links into project namespace that get used by other message strings, with the exception of user group pages (see grouppage) and the disambiguation template definition (see disambiguations). 'aboutsite' => 'Par {{grammar:akuzatīvs|{{SITENAME}}}}', 'aboutpage' => 'Project:Par', 'copyright' => 'Saturs ir pieejams saskaņā ar $1.', 'copyrightpage' => '{{ns:project}}:Autortiesības', 'currentevents' => 'Aktualitātes', 'currentevents-url' => 'Project:Aktualitātes', 'disclaimers' => 'Saistību atrunas', 'disclaimerpage' => 'Project:Saistību atrunas', 'edithelp' => 'Rediģēšanas palīdzība', 'edithelppage' => 'Help:Rediģēšana', 'helppage' => 'Help:Saturs', 'mainpage' => 'Sākumlapa', 'mainpage-description' => 'Sākumlapa', 'policy-url' => 'Project:Politika', 'portal' => 'Kopienas portāls', 'portal-url' => 'Project:Kopienas portāls', 'privacy' => 'Privātuma politika', 'privacypage' => 'Project:Privātuma politika', 'badaccess' => 'Atļaujas kļūda', 'badaccess-group0' => 'Tev nav atļauts izpildīt darbību, kuru tu pieprasīji.', 'badaccess-groups' => 'Darbības izpilde, ko Tu pieprasīji, ir pieejama tikai $1 {{PLURAL:$2|lietotāju grupai|lietotāju grupām}}.', 'versionrequired' => "Nepieciešamā ''MediaWiki'' versija: $1.", 'versionrequiredtext' => "Lai lietotu šo lapu, nepieciešama ''MediaWiki'' versija $1. Sk. [[Special:Version|versija]].", 'ok' => 'Labi', 'retrievedfrom' => 'Saturs iegūts no "$1"', 'youhavenewmessages' => 'Tev ir $1 (skatīt $2).', 'newmessageslink' => 'jauns vēstījums', 'newmessagesdifflink' => 'pēdējā izmaiņa', 'youhavenewmessagesmulti' => 'Tev ir jauns ziņojums: $1', 'editsection' => 'labot', 'editold' => 'labot', 'viewsourceold' => 'aplūkot kodu', 'editlink' => 'labot', 'viewsourcelink' => 'aplūkot kodu', 'editsectionhint' => 'Rediģēt sadaļu: $1', 'toc' => 'Satura rādītājs', 'showtoc' => 'parādīt', 'hidetoc' => 'paslēpt', 'collapsible-collapse' => 'Sakļaut', 'collapsible-expand' => 'Izplest', 'thisisdeleted' => 'Apskatīt vai atjaunot $1?', 'viewdeleted' => 'Skatīt $1?', 'restorelink' => '$1 {{PLURAL:$1|dzēsto versiju|dzēstās versijas}}', 'feedlinks' => 'Barotne:', 'feed-invalid' => 'Nederīgs abonētās barotnes veids.', 'feed-unavailable' => 'Sindicētās plūsmas nav pieejamas', 'site-rss-feed' => '$1 RSS padeve', 'site-atom-feed' => '$1 Atom padeve', 'page-rss-feed' => '"$1" RSS barotne', 'page-atom-feed' => '"$1" Atom barotne', 'red-link-title' => '$1 (lapa neeksistē)', 'sort-descending' => 'Kārtot dilstošā secībā', 'sort-ascending' => 'Kārtot augošā secībā', # Short words for each namespace, by default used in the namespace tab in monobook 'nstab-main' => 'Raksts', 'nstab-user' => 'Lietotāja lapa', 'nstab-media' => 'Multivides lapa', 'nstab-special' => 'Īpašā lapa', 'nstab-project' => 'Projekta lapa', 'nstab-image' => 'Attēls', 'nstab-mediawiki' => 'Paziņojums', 'nstab-template' => 'Veidne', 'nstab-help' => 'Palīdzība', 'nstab-category' => 'Kategorija', # Main script and global functions 'nosuchaction' => 'Šādas darbības nav.', 'nosuchactiontext' => 'Iekš URL norādītā darbība ir nederīga. Tas var būt no drukas kļūdas URL, vai arī no kļūdainas saites. Tas arī var būt saistīts ar {{GRAMMAR:ģenitīvs|{{SITENAME}}}} programmatūras kļūdu.', 'nosuchspecialpage' => 'Nav tādas īpašās lapas', 'nospecialpagetext' => 'Tu esi pieprasījis īpašo lapu, ko wiki neatpazīst. Derīgo īpašo lapu saraksts atrodas te: [[Special:SpecialPages|{{int:specialpages}}]].', # General errors 'error' => 'Kļūda', 'databaseerror' => 'Datu bāzes kļūda', 'dberrortext' => 'Konstatēta sintakses kļūda datubāzes pieprasījumā. Iespējams, tā radusies dēļ kļūdas programmatūrā. Pēdējais datubāzes pieprasījums bija: <blockquote><code>$1</code></blockquote> no funkcijas "<code>$2</code>". Datubāzes atgrieztais kļūdas paziņojums: "<samp>$3: $4</samp>".', 'dberrortextcl' => 'Datubāzes vaicājumā pieļauta sintakses kļūda. Pēdējais priekšraksts: "$1" palaists funkcijā "$2". Izdotā MySQL kļūda: "$3: $4"', 'laggedslavemode' => 'Uzmanību: Iespējams, šajā lapā nav redzami nesen izdarītie papildinājumi.', 'readonly' => 'Datubāze bloķēta', 'enterlockreason' => 'Ievadiet bloķēšanas iemeslu, ieskaitot aplēses, kad bloķēšana tiks beigta.', 'readonlytext' => 'Datubāze šobrīd ir bloķēta jaunu ierakstu izveidošanai un citām izmaiņām, visticamāk, kārtējā datubāzes uzturēšanas pasākuma dēļ, pēc kura tā tiks atjaunota normālā stāvoklī. Administrators, kurš nobloķēja datubāzi, norādīja šādu iemeslu: $1', 'missing-article' => 'Teksts lapai ar nosaukumu "$1" $2 datubāzē nav atrodams. Tas parasti notiek novecojušu saišu gadījumā: pieprasot izmaiņas vai hronoloģiju lapai, kas ir izdzēsta. Ja lapai ir jābūt, tad, iespējams, ir kļūda programmā. Par to varat ziņot [[Special:ListUsers/sysop|kādam administratoram]], norādot arī URL.', 'missingarticle-rev' => '(Pārskatīšana #: $1)', 'missingarticle-diff' => '(Salīdz.: $1, $2)', 'internalerror' => 'Iekšēja kļūda', 'internalerror_info' => 'Iekšējā kļūda: $1', 'fileappenderror' => 'Neizdevās pievienot "$1" pie "$2".', 'filecopyerror' => 'Nav iespējams nokopēt failu "$1" uz "$2"', 'filerenameerror' => 'Neizdevās pārdēvēt failu "$1" par "$2".', 'filedeleteerror' => 'Nevar izdzēst failu "$1".', 'directorycreateerror' => 'Nevar izveidot mapi "$1".', 'filenotfound' => 'Neizdevās atrast failu "$1".', 'fileexistserror' => 'Nevar saglabāt failā "$1": fails jau pastāv', 'unexpected' => 'Negaidīta vērtība: "$1"="$2".', 'formerror' => 'Kļūda: neizdevās nosūtīt saturu', 'badarticleerror' => 'Šo darbību nevar veikt šajā lapā.', 'cannotdelete' => 'Nevar izdzēst lapu vai failu $1. Iespējams, to jau ir izdzēsis kāds cits.', 'cannotdelete-title' => 'Nevar izdzēst lapu "$1"', 'badtitle' => 'Nepiemērots nosaukums', 'badtitletext' => 'Pieprasītā lapa ir kļūdaina, tukša, vai nepareizi saistīts starpvalodu vai starp-vikiju virsrakstas. Tas var saturēt vienu vai vairākus simbolus, ko nedrīkst izmantot nosaukumos.', 'perfcached' => 'Šie dati ir no servera kešatmiņas un var būt novecojuši. A maximum of {{PLURAL:$1|one result is|$1 results are}} available in the cache.', 'perfcachedts' => "Šie dati ir no servera kešatmiņas (''cache''), kas pēdējo reizi bija atjaunota $1. A maximum of {{PLURAL:$4|one result is|$4 results are}} available in the cache.", 'querypage-no-updates' => 'Šīs lapas atjaunošana pagaidām ir atslēgta. Te esošie dati tuvākajā laikā netiks atjaunoti.', 'wrong_wfQuery_params' => 'Nekorekti wfQuery() parametri<br /> Funkcija: $1<br /> Vaicājums: $2', 'viewsource' => 'Aplūkot kodu', 'actionthrottled' => 'Darbība netika atļauta', 'protectedpagetext' => 'Šī lapa ir aizsargāta lai novērstu tās izmainīšanu vai citas darbības.', 'viewsourcetext' => 'Tu vari apskatīties un nokopēt šīs lapas vikitekstu:', 'protectedinterface' => 'Šī lapa satur programmatūras interfeisā lietotu tekstu un ir bloķēta pret izmaiņām, lai pasargātu no bojājumiem.', 'editinginterface' => "'''Brīdinājums:''' Tu izmaini lapu, kuras saturu izmanto wiki programmatūras lietotāja saskarnē (''interfeisā''). Šīs lapas izmaiņas ietekmēs lietotāja saskarni citiem lietotājiem. Pēc modificēšanas, šīs izmaiņas būtu lietderīgi pievienot arī [//translatewiki.net/wiki/Main_Page?setlang=en translatewiki.net], kas ir MediaWiki lokalizēšanas projekts.", 'sqlhidden' => '(SQL vaicājums paslēpts)', 'namespaceprotected' => "Tev nav atļaujas izmainīt lapas, kas atrodas '''$1''' ''namespacē''.", 'ns-specialprotected' => 'Nevar izmainīt īpašās lapas.', 'titleprotected' => "Šī lapa ir aizsargāta pret izveidošanu. To aizsargāja [[User:$1|$1]]. Norādītais iemesls bija ''$2''.", # Virus scanner 'virus-badscanner' => "Nekorekta konfigurācija: nezināms vīrusu skeneris: ''$1''", 'virus-scanfailed' => 'skenēšana neizdevās (kods $1)', 'virus-unknownscanner' => 'nezināms antivīruss:', # Login and logout pages 'logouttext' => "'''Tu esi izgājis no {{grammar:ģenitīvs|{{SITENAME}}}}.''' Vari turpināt to izmantot anonīmi, vari [[Special:UserLogin|atgriezties]] kā cits lietotājs vai varbūt tas pats. Ņem vērā, ka arī pēc iziešanas, dažas lapas var tikt parādītas tā, it kā tu vēl būtu iekšā, līdz tiks iztīrīta pārlūka kešatmiņa.", 'welcomecreation' => '== Laipni lūdzam, $1! == Tavs lietotāja konts ir izveidots. Neaizmirsti, ka ir iespējams mainīt [[Special:Preferences|{{grammar:ģenitīvs|{{SITENAME}}}} izmantošanas izvēles]].', 'yourname' => 'Tavs lietotājvārds', 'yourpassword' => 'Tava parole:', 'yourpasswordagain' => 'Atkārto paroli', 'remembermypassword' => 'Atcerēties pēc pārlūka aizvēršanas (spēkā ne vairāk kā $1 {{PLURAL:$1|diena|dienas}}).', 'securelogin-stick-https' => 'Saglabāt HTTPS savienojumu pēc pieslēgšanās', 'yourdomainname' => 'Tavs domēns', 'externaldberror' => 'Notikusi vai nu ārējās autentifikācijas datubāzes kļūda, vai arī tev nav atļauts izmainīt savu ārējo kontu.', 'login' => 'Pieslēgties', 'nav-login-createaccount' => 'Izveidot jaunu lietotāju vai doties iekšā', 'loginprompt' => 'Lai ieietu {{grammar:lokatīvs|{{SITENAME}}}}, tavam datoram ir jāpieņem sīkdatnes (<i>cookies</i>).', 'userlogin' => 'Izveidot jaunu lietotāju vai doties iekšā', 'userloginnocreate' => 'Pieslēgties', 'logout' => 'Iziet', 'userlogout' => 'Iziet', 'notloggedin' => 'Neesi iegājis', 'nologin' => "Nav lietotājvārda? '''$1'''.", 'nologinlink' => 'Reģistrējies', 'createaccount' => 'Izveidot jaunu lietotāju', 'gotaccount' => "Tev jau ir lietotājvārds? '''$1'''!", 'gotaccountlink' => 'Dodies iekšā', 'userlogin-resetlink' => 'Esat aizmirsis savu pieslēgšanās informāciju?', 'createaccountmail' => 'Pa e-pastu', 'createaccountreason' => 'Iemesls:', 'badretype' => 'Tevis ievadītās paroles nesakrīt.', 'userexists' => 'Ievadītais lietotājvārds jau ir aizņemts. Lūdzu, izvēlieties citu vārdu.', 'loginerror' => 'Neveiksmīga ieiešana', 'createaccounterror' => 'Neizdevās izveidot kontu: $1', 'nocookiesnew' => 'Lietotājvārds tika izveidots, bet tu neesi iegājis iekšā. {{SITENAME}} izmanto sīkdatnes (<i>cookies</i>), lai lietotāji varētu tajā ieiet. Tavs pārlūks nepieņem tās. Lūdzu, atļauj to pieņemšanu un tad nāc iekšā ar savu lietotājvārdu un paroli.', 'nocookieslogin' => '{{SITENAME}} izmanto sīkdatnes (<i>cookies</i>), lai lietotāji varētu ieiet tajā. Diemžēl tavs pārlūks tos nepieņem. Lūdzu, atļauj to pieņemšanu un mēģini vēlreiz.', 'noname' => 'Tu neesi norādījis derīgu lietotāja vārdu.', 'loginsuccesstitle' => 'Ieiešana veiksmīga', 'loginsuccess' => 'Tu esi ienācis {{grammar:lokatīvs|{{SITENAME}}}} kā "$1".', 'nosuchuser' => 'Šeit nav lietotāja ar vārdu "$1". Lietotājvārdi ir reģistrjutīgi (lielie un mazie burti nav viens un tas pats) Pārbaudi, vai pareizi uzrakstīts, vai arī [[Special:UserLogin/signup|izveido jaunu kontu]].', 'nosuchusershort' => 'Šeit nav lietotāja ar vārdu "$1". Pārbaudi, vai nav drukas kļūda.', 'nouserspecified' => 'Tev jānorāda lietotājvārds.', 'login-userblocked' => 'Šis lietotājs ir bloķēts. Pieslēgšanās nav atļauta.', 'wrongpassword' => 'Tu ievadīji nepareizu paroli. Lūdzu, mēģini vēlreiz.', 'wrongpasswordempty' => 'Parole bija tukša. Lūdzu mēģini vēlreiz.', 'passwordtooshort' => 'Tava parole ir pārāk īsa. Tajā jābūt vismaz {{PLURAL:$1|1 zīmei|$1 zīmēm}}.', 'password-name-match' => 'Tava parole nedrīkst būt tāda pati kā tavs lietotājvārds.', 'mailmypassword' => 'Atsūtīt man jaunu paroli', 'passwordremindertitle' => 'Jauna pagaidu parole no {{SITENAME}}s', 'passwordremindertext' => 'Kads (iespejams, Tu pats, no IP adreses $1) ludza, lai nosutam Tev jaunu {{SITENAME}} ($4) paroli. Lietotajam $2 pagaidu parole tagad ir $3. Ludzu, nomaini paroli, kad esi veiksmigi iekluvis ieksa. Tavas pagaidu paroles deriiguma terminsh beigsies peec {{PLURAL:$5|vienas dienas|$5 dienaam}}. Ja paroles pieprasījumu bija nosūtījis kāds cits, vai arī tu atcerējies savu veco paroli, šo var ignorēt. Vecā parole joprojām darbojas.', 'noemail' => 'Lietotājs "$1" nav reģistrējis e-pasta adresi.', 'noemailcreate' => 'Tev jānorāda derīgu e-pasta adresi', 'passwordsent' => 'Esam nosūtījuši jaunu paroli uz e-pasta adresi, kuru ir norādījis lietotājs $1. Lūdzu, nāc iekšā ar jauno paroli, kad būsi to saņēmis.', 'blocked-mailpassword' => "Tava IP adrese ir bloķēta un tāpēc nevar lietot paroles atjaunošanas (''recovery'') funkciju, lai nevarētu apiet bloku.", 'eauthentsent' => "Apstiprinājuma e-pasts tika nosūtīts uz norādīto e-pasta adresi. Lai varētu saņemt citus ''meilus'', izpildi vēstulē norādītās instrukcijas, lai apstiprinātu, ka šī tiešām ir tava e-pasta adrese.", 'throttled-mailpassword' => 'Paroles atgādinājums jau ir ticis nosūtīts {{PLURAL:$1|pēdējās stundas|pēdējo $1 stundu}} laikā. Lai novērstu šīs funkcijas ļaunprātīgu izmantošanu, iespējams nosūtīt tikai vienu paroles atgādinājumu, {{PLURAL:$1|katru stundu|katras $1 stundas}}.', 'mailerror' => 'E-pasta sūtīšanas kļūda: $1', 'acct_creation_throttle_hit' => 'Lietotāji no tavas IP adreses šajā viki pēdējo 24 stundu laikā jau ir izveidojuši {{PLURAL:$1|1 kontu|$1 kontus}}, kas ir maksimālais atļautais skaits šajā laika periodā. Tādēļ šobrīd no šīs IP adreses vairs nevar izveidot jaunus kontus.', 'emailauthenticated' => 'Tava e-pasta adrese tika apstiprināta $2, $3.', 'emailnotauthenticated' => 'Tava e-pasta adrese <strong>vēl nav apstiprināta</strong> un zemāk norādītās iespējas nav pieejamas.', 'noemailprefs' => 'Norādi e-pasta adresi, lai lietotu šīs iespējas.', 'emailconfirmlink' => 'Apstiprināt tavu e-pasta adresi', 'invalidemailaddress' => 'E-pasta adrese nevar tikt apstiprināta, jo izskatās nederīga. Lūdzu ievadi korekti noformētu e-pasta adresi, vai arī atstāj to lauku tukšu.', 'cannotchangeemail' => 'Konta e-pasta adresi nevar nomainīt šajā wiki.', 'accountcreated' => 'Konts izveidots', 'accountcreatedtext' => 'Lietotāja konts priekš $1 tika izveidots.', 'createaccount-title' => 'Lietotāja konta izveidošana {{grammar:lokatīvs|{{SITENAME}}}}', 'usernamehasherror' => 'Lietotājvārds nevar saturēt hash simbolus', 'login-throttled' => 'Tu esi veicis pārāk daudz ieiešanas mēģinājumus. Lūdzu uzgaidi pirms mēģini vēlreiz.', 'login-abort-generic' => 'Jūsu pieteikšanās bija neveiksmīga — Darbība pārtraukta', 'loginlanguagelabel' => 'Valoda: $1', # Email sending 'php-mail-error-unknown' => 'Nezināma kļūda PHP mail() funkcijā', # Change password dialog 'resetpass' => 'Mainīt paroli', 'resetpass_header' => 'Mainīt konta paroli', 'oldpassword' => 'Vecā parole', 'newpassword' => 'Jaunā parole', 'retypenew' => 'Atkārto jauno paroli', 'resetpass_submit' => 'Uzstādīt paroli un ieiet', 'resetpass_success' => 'Parole nomainīta veiksmīgi! Notiek ieiešana...', 'resetpass_forbidden' => 'Paroles nav iespējams nomainīt', 'resetpass-no-info' => 'Jums ir nepieciešams ieiet, lai tūlīt piekļūtu šai lapai.', 'resetpass-submit-loggedin' => 'Mainīt paroli', 'resetpass-submit-cancel' => 'Atcelt', 'resetpass-wrong-oldpass' => 'Nepareiza pagaidu vai galvenā parole. Tu jau esi veiksmīgi nomainījis savu galveno paroli, vai arī esi pieprasījis jaunu pagaidu paroli.', 'resetpass-temp-password' => 'Pagaidu parole:', # Special:PasswordReset 'passwordreset' => 'Paroles atiestatīšana', 'passwordreset-legend' => 'Atiestatīt paroli', 'passwordreset-disabled' => 'Paroles atiestates šajā viki ir atspējotas.', 'passwordreset-username' => 'Lietotājvārds:', 'passwordreset-domain' => 'Domēns:', 'passwordreset-capture' => 'Apskatīt izveidoto e-pastu?', 'passwordreset-email' => 'E-pasta adrese:', 'passwordreset-emailtitle' => 'Konta informācija {{SITENAME}}', 'passwordreset-emailelement' => 'Lietotājvārds: $1 Pagaidu parole: $2', 'passwordreset-emailsent' => 'Atgādinājuma e-pasts ir nosūtīts.', 'passwordreset-emailsent-capture' => 'Atgādinājuma e-pasta ziņojums ir nosūtīts, tas parādīts zemāk.', 'passwordreset-emailerror-capture' => 'Atgādinājuma e-pasta ziņojums tika izveidots, tas parādīts zemāk, bet nosūtīšana lietotājam neizdevās: $1', # Special:ChangeEmail 'changeemail' => 'Mainīt e-pasta adresi', 'changeemail-header' => 'Mainīt konta e-pasta adresi', 'changeemail-oldemail' => 'Pašreizējā e-pasta adrese:', 'changeemail-newemail' => 'Jaunā e-pasta adrese:', 'changeemail-none' => '(nav)', 'changeemail-submit' => 'Mainīt e-pastu', 'changeemail-cancel' => 'Atcelt', # Edit page toolbar 'bold_sample' => 'Teksts boldā', 'bold_tip' => 'Teksts treknrakstā', 'italic_sample' => 'Teksts kursīvā', 'italic_tip' => 'Teksts kursīvā', 'link_sample' => 'Lapas nosaukums', 'link_tip' => 'Iekšējā saite', 'extlink_sample' => 'http://www.example.com saites apraksts', 'extlink_tip' => 'Ārējā saite (neaizmirsti sākumā pierakstīt "http://")', 'headline_sample' => 'Virsraksta teksts', 'headline_tip' => '2. līmeņa virsraksts', 'nowiki_sample' => 'Šeit raksti neformatētu tekstu', 'nowiki_tip' => 'Ignorēt wiki formatējumu', 'image_sample' => 'Piemers.jpg', 'image_tip' => 'Ievietots attēls', 'media_sample' => 'Piemers.ogg', 'media_tip' => 'Saite uz multimēdiju failu', 'sig_tip' => 'Tavs paraksts ar laika atzīmi', 'hr_tip' => 'Horizontāla līnija (neizmanto lieki)', # Edit pages 'summary' => 'Kopsavilkums:', 'subject' => 'Tēma/virsraksts:', 'minoredit' => 'maznozīmīgs labojums', 'watchthis' => 'Uzraudzīt šo lapu', 'savearticle' => 'Saglabāt lapu', 'preview' => 'Pirmskats', 'showpreview' => 'Rādīt pirmskatu', 'showlivepreview' => 'Tūlītējs pirmskats', 'showdiff' => 'Rādīt izmaiņas', 'anoneditwarning' => "'''Uzmanību:''' tu neesi iegājis. Lapas hronoloģijā tiks ierakstīta tava IP adrese.", 'anonpreviewwarning' => "''Tu neesi ienācis. Saglabājot lapu, Tava IP adrese tiks ierakstīta šīs lapas hronoloģijā.''", 'missingsummary' => "'''Atgādinājums''': Tu neesi norādījis izmaiņu kopsavilkumu. Vēlreiz klikšķinot uz \"Saglabāt lapu\", Tavas izmaiņas tiks saglabātas bez kopsavilkuma.", 'missingcommenttext' => 'Lūdzu, ievadi tekstu zemāk redzamajā logā!', 'missingcommentheader' => "'''Atgādinājums:''' Tu šim komentāram neesi norādījis virsrakstu/tematu. Ja tu vēlreiz spiedīsi uz \"{{int:savearticle}}\", tavas izmaiņas tiks saglabātas bez virsraksta.", 'summary-preview' => 'Kopsavilkuma pirmskats:', 'subject-preview' => 'Kopsavilkuma/virsraksta pirmskats:', 'blockedtitle' => 'Lietotājs ir bloķēts.', 'blockedtext' => "'''Tavs lietotāja vārds vai IP adrese ir nobloķēta.''' \$1 nobloķēja tavu lietotāja vārdu vai IP adresi. Bloķējot norādītais iemesls bija: ''\$2''. *Bloka sākums: \$8 *Bloka beigas: \$6 *Bija domāts nobloķēt: \$7 Tu vari sazināties ar \$1 vai kādu citu [[{{MediaWiki:Grouppage-sysop}}|administratoru]] lai apspriestu šo bloku. Pievērs uzmanību, tam, ka ja tu neesi norādījis derīgu e-pasta adresi ''[[Special:Preferences|savās izvēlēs]]'', tev nedarbosies \"sūtīt e-pastu\" iespēja. Tava IP adrese ir \$3 un bloka identifikators ir #\$5. Lūdzu iekļauj vienu no tiem, vai abus, visos turpmākajos pieprasījumos.", 'autoblockedtext' => 'Tava IP adrese ir tikusi automātiski nobloķēta, tāpēc, ka to (nupat kā) ir lietojis cits lietotājs, kuru nobloķēja $1. Norādītais bloķēšanas iemesls bija: :\'\'$2\'\' * Bloka sākums: $8 * Bloka beigas: $6 * Bija domāts nobloķēt: $7 Tu vari sazināties ar $1 vai kādu citu [[{{MediaWiki:Grouppage-sysop}}|adminu]] lai apspriestu šo bloku. Atceries, ka tu nevari lietot "sūtīt e-pastu šim lietotājam" iespēju, ja tu neesi norādījis derīgu e-pasta adresi savās [[Special:Preferences|lietotāja izvelēs]] un bloķējot tev nav aizbloķēta iespēja sūtīt e-pastu. Tava pašreizējā IP adrese ir $3 un bloka ID ir $5. Lūdzu iekļauj šos visos ziņojumos, kurus sūti adminiem, apspriežot šo bloku.', 'blockednoreason' => 'iemesls nav norādīts', 'whitelistedittext' => 'Tev $1 lai varētu rediģēt lapas.', 'confirmedittext' => 'Lai varētu izmainīt lapas, vispirms jāapstiprina savu e-pasta adresi. Norādi un apstiprini e-pasta adresi savos [[Special:Preferences|lietotāja uzstādījumos]].', 'nosuchsectiontitle' => 'Nevaru atrast sadaļu', 'nosuchsectiontext' => 'Jūs mēģinājāt rediģēt sadaļu, kas neeksistē. Tā var būt pārvietota vai dzēsta, kamēr jūs apskatījāt lapu.', 'loginreqtitle' => 'Nepieciešama ieiešana', 'loginreqlink' => 'login', 'loginreqpagetext' => 'Tev nepieciešams $1, lai apskatītu citas lapas.', 'accmailtitle' => 'Parole nosūtīta.', 'accmailtext' => "Nejauši ģenerēta parole lietotājam [[User talk:$1|$1]] tika nosūtīta uz $2. Šī konta paroli pēc ielogošanās varēs nomainīt ''[[Special:ChangePassword|šeit]]''.", 'newarticle' => '(Jauns raksts)', 'newarticletext' => "Tu šeit nonāci sekojot saitei uz, pagaidām vēl neuzrakstītu, lapu. Lai izveidotu lapu, sāc rakstīt teksta logā apakšā (par teksta formatēšanu un sīkākai informācija skatīt [[{{MediaWiki:Helppage}}|palīdzības lapu]]). Ja tu šeit nonāci kļūdas pēc, vienkārši uzspied '''back''' pogu pārlūkprogrammā.", 'anontalkpagetext' => "----''Šī ir diskusiju lapa anonīmam lietotājam, kurš vēl nav kļuvis par reģistrētu lietotāju vai arī neizmanto savu lietotājvārdu. Tādēļ mums ir jāizmanto skaitliskā IP adrese, lai viņu identificētu. Šāda IP adrese var būt vairākiem lietotājiem. Ja tu esi anonīms lietotājs un uzskati, ka tev ir adresēti neatbilstoši komentāri, lūdzu, [[Special:UserLogin/signup|kļūsti par lietotāju]] vai arī [[Special:UserLogin|izmanto jau izveidotu lietotājvārdu]], lai izvairītos no turpmākām neskaidrībām un tu netiktu sajaukts ar citiem anonīmiem lietotājiem.''", 'noarticletext' => 'Šajā lapā šobrīd nav nekāda teksta, tu vari [[Special:Search/{{PAGENAME}}|meklēt citās lapās pēc šīs lapas nosaukuma]], <span class="plainlinks">[{{fullurl:{{#Special:Log}}|page={{FULLPAGENAMEE}}}} meklēt saistītos reģistru ierakstos] vai arī [{{fullurl:{{FULLPAGENAME}}|action=edit}} sākt rediģēt šo lapu]</span>.', 'noarticletext-nopermission' => 'Šajā lapā pašlaik nav nekāda teksta. Tu vari [[Special:Search/{{PAGENAME}}|meklēt šīs lapas nosaukumu]] citās lapās, vai <span class="plainlinks">[{{fullurl:{{#Special:Log}}|page={{FULLPAGENAMEE}}}} meklēt saistītus reģistru ierakstus]</span>.', 'userpage-userdoesnotexist' => 'Lietotājs "<nowiki>$1</nowiki>" nav reģistrēts. Lūdzu, pārliecinies vai vēlies izveidot/izmainīt šo lapu.', 'userpage-userdoesnotexist-view' => 'Lietotājs "$1" nav reģistrēts.', 'blocked-notice-logextract' => 'Šis lietotājs pašlaik ir nobloķēts. Pēdējais bloķēšanas reģistra ieraksts ir apskatāms zemāk:', 'clearyourcache' => "'''Piezīme:''' Lai redzētu izmaiņas, pēc saglabāšanas jums var nākties iztīrīt sava pārlūka kešatmiņu. * '''Firefox / Safari:''' Pieturiet ''Shift'' un klikšķiniet uz ''Pārlādēt'' vai nospiediet ''Ctrl-F5'' vai ''Ctrl-R'' (''Command-R'' uz Mac) * '''Google Chrome:''' Nospiediet ''Ctrl-Shift-R'' (''Command-Shift-R'' uz Mac) * '''Internet Explorer:''' Pieturiet ''Ctrl'' un klikšķiniet uz ''Pārlādēt'' vai nospiediet ''Ctrl-F5'' * '''Konqueror:''' Klikšķiniet uz ''Pārlādēt'' vai nospiediet ''F5'' * '''Opera:''' Iztīriet kešatmiņu ''Tools → Preferences''", 'usercssyoucanpreview' => "'''Ieteikums:''' Lieto pogu \"{{int:showpreview}}\", lai pārbaudītu savu jauno CSS pirms saglabāšanas.", 'userjsyoucanpreview' => "'''Ieteikums:''' Lieto pogu \"{{int:showpreview}}\", lai pārbaudītu savu jauno JavaScript pirms saglabāšanas.", 'usercsspreview' => "'''Atceries, ka šis ir tikai tava lietotāja CSS pirmskats, lapa vēl nav saglabāta!'''", 'userjspreview' => "'''Atceries, ka šis ir tikai tava lietotāja JavaScript pirmskats/tests, lapa vēl nav saglabāta!'''", 'sitecsspreview' => "'''Atcerieties, ka jūs veicat tikai šī CSS priekšapskati.''' '''Tas vēl nav saglabāts!'''", 'sitejspreview' => "'''Atcerieties, ka jūs veicat tikai šī JavaScript koda priekšapskati.''' '''Tas vēl nav saglabāts!'''", 'updated' => '(Atjaunots)', 'note' => "'''Piezīme: '''", 'previewnote' => "'''Atceries, ka šis ir tikai pirmskats un teksts vēl nav saglabāts!'''", 'session_fail_preview' => "'''Neizdevās apstrādāt tavas izmaiņas, jo tika pazaudēti sesijas dati. Lūdzu mēģini vēlreiz. Ja tas joprojām nedarbojas, mēģini [[Special:UserLogout|izlogoties ārā]] un ielogoties no jauna.'''", 'session_fail_preview_html' => "'''Neizdevās apstrādāt tavas izmaiņas, jo tika pazaudēti sesijas dati.''' ''Tā, kā {{grammar:ģenitīvs|{{SITENAME}}}} darbojas neapstrādāts HTML, pirmskats ir paslēpts, lai aizsargātos no JavaScripta uzbrukumiem.'' '''Ja šis bija parasts rediģēšanas mēģinājums, mēģini vēlreiz. Ja tas joprojām nedarbojas, mēģini [[Special:UserLogout|izlogoties ārā]] un ielogoties no jauna.'''", 'editing' => 'Izmainīt $1', 'editingsection' => 'Izmainīt $1 (sadaļa)', 'editingcomment' => 'Izmainīt $1 (jauna sadaļa)', 'editconflict' => 'Izmaiņu konflikts: $1', 'explainconflict' => "Kāds cits ir izmainījis šo lapu pēc tam, kad tu sāki to mainīt. Augšējā teksta logā ir lapas teksts tā pašreizējā versijā. Tevis veiktās izmaiņas ir redzamas apakšējā teksta logā. Lai saglabātu savas izmaiņas, tev ir jāapvieno savs teksts ar saglabāto pašreizējo variantu. Kad spiedīsi pogu \"{{int:savearticle}}\", tiks saglabāts '''tikai''' teksts, kas ir augšējā teksta logā.", 'yourtext' => 'Tavs teksts', 'storedversion' => 'Saglabātā versija', 'nonunicodebrowser' => "'''Brīdinājums: Tavs pārlūks neatbalsta unikodu. Ir pieejams risinājums, kas ļaus tev droši rediģēt lapas: zīmes, kas nav ASCII, parādīsies izmaiņu logā kā heksadecimāli kodi.'''", 'editingold' => "'''BRĪDINĀJUMS: Saglabājot šo lapu, tu izmainīsi šīs lapas novecojušu versiju, un ar to tiks dzēstas visas izmaiņas, kas izdarītas pēc šīs versijas.'''", 'yourdiff' => 'Atšķirības', 'copyrightwarning' => "Lūdzu, ņem vērā, ka viss ieguldījums, kas veikts {{grammar:lokatīvs|{{SITENAME}}}}, ir uzskatāms par publiskotu saskaņā ar \$2 (vairāk info skat. \$1). Ja nevēlies, lai Tevis rakstīto kāds rediģē un izplata tālāk, tad, lūdzu, nepievieno to šeit!<br /> Izvēloties \"Saglabāt lapu\", Tu apliecini, ka šo rakstu esi rakstījis vai papildinājis pats vai izmantojis informāciju no darba, ko neaizsargā autortiesības, vai tamlīdzīga brīvi pieejama resursa. '''BEZ ATĻAUJAS NEPIEVIENO DARBU, KO AIZSARGĀ AUTORTIESĪBAS!'''", 'copyrightwarning2' => "Lūdz ņem vērā, ka visu ieguldījumu {{grammar:lokatīvs|{{SITENAME}}}} var rediģēt, mainīt vai izdzēst citi lietotāji. Ja negribi lai ar tavu rakstīto tā izrīkojas, nepievieno to šeit. Tu apliecini, ka šo rakstu esi rakstījis vai papildinājis pats vai izmantojis informāciju no darba, ko neaizsargā autortiesības, vai tamlīdzīga brīvi pieejama resursa (sīkāk skatīt $1). '''BEZ ATĻAUJAS NEPIEVIENO DARBU, KO AIZSARGĀ AUTORTIESĪBAS!'''", 'longpageerror' => "'''Kļūda: Teksts, kuru tu mēģināji saglabāt, ir $1 kilobaitus garš, kas ir vairāk nekā pieļaujamie $2 kilobaiti. Tas nevar tikt saglabāts.'''", 'readonlywarning' => "'''Brīdinājums: Datubāze ir slēgta apkopei, tāpēc tu tagad nevarēsi saglabāt veiktās izmaiņas. Tu vari nokopēt tekstu un saglabāt kā teksta failu vēlākam laikam.''' Admins, kas slēdza datubāzi, norādīja šādu paskaidrojumu: $1", 'protectedpagewarning' => "'''BRĪDINĀJUMS: Šī lapa ir aizsargāta, tikai lietotāji ar administratora privilēģijām var to izmainīt.''' Pēdējais aizsargāšanas reģistra ieraksts ir apskatāms zemāk:", 'semiprotectedpagewarning' => "'''Piezīme:''' Šī lapa ir aizsargāta, lai to varētu labot tikai reģistrēti lietotāji. Pēdējais reģistra ieraksts ir apskatāms zemāk:", 'titleprotectedwarning' => "'''Brīdinājums: Šī lapa ir slēgta un to var izveidot tikai [[Special:ListGroupRights|noteikti]] lietotāji.'''", 'templatesused' => 'Šajā lapā {{PLURAL:$1|izmantotā veidne|izmantotās veidnes}}:', 'templatesusedpreview' => 'Šajā pirmskatā {{PLURAL:$1|izmanotā veidne|izmantotās veidnes}}:', 'templatesusedsection' => 'Šajā sadaļā {{PLURAL:$1|izmantotā veidne|izmantotās veidnes}}:', 'template-protected' => '(aizsargāta)', 'template-semiprotected' => '(daļēji aizsargāta)', 'hiddencategories' => 'Šī lapa ietilpst {{PLURAL:$1|1 slēptajā kategorijā|$1 slēptajās kategorijās}}:', 'nocreatetitle' => 'Lapu veidošana ierobežota', 'nocreatetext' => '{{grammar:lokatīvs|{{SITENAME}}}} ir atslēgta iespēja izveidot jauinas lapas. Tu vari atgriezties atpakaļ un izmainīt esošu lapu, vai arī [[Special:UserLogin|ielogoties, vai izveidot kontu]].', 'nocreate-loggedin' => 'Tev nav atļaujas veidot jaunas lapas.', 'sectioneditnotsupported-title' => 'Sadaļa rediģēšana nav atbalstīta', 'sectioneditnotsupported-text' => 'Sadaļu rediģēsana šajā lapā nav atļauta.', 'permissionserrors' => 'Atļaujas kļūdas', 'permissionserrorstext' => 'Tev nav atļauts veikt šo darbību {{PLURAL:$1|šāda iemesla|šādu iemeslu}} dēļ:', 'permissionserrorstext-withaction' => 'Tev nav atļauts $2 {{PLURAL:$1|šāda iemesla|šādu iemeslu}} dēļ:', 'recreate-moveddeleted-warn' => "'''Brīdinājums: Tu atjauno lapu, kas ir tikusi izdzēsta''' Tev vajadzētu pārliecināties, vai ir lietderīgi turpināt izmainīt šo lapu. Te var apskatīties dzēšanas un pārvietošanas reģistrus, kuros jābūt datiem par to kas, kad un kāpēc šo lapu izdzēsa.", 'moveddeleted-notice' => 'Šī lapa ir tikusi izdzēsta. Te var apskatīties dzēšanas un pārvietošanas reģistru fragmentus, lai noskaidrotu kurš, kāpēc un kad to izdzēsa.', 'log-fulllog' => 'Paskatīties pilnu reģistru', 'edit-hook-aborted' => 'Aizķere pārtrauca labojumu. Netika sniegts paskaidrojums.', 'edit-gone-missing' => 'Nevar atjaunināt lapu. Izskatās, ka lapa ir dzēsta.', 'edit-conflict' => 'Labošanas konflikts.', 'edit-no-change' => 'Tavs labojums tika ignorēts, jo tekstā netika izdarītas izmaiņas.', 'edit-already-exists' => 'Nevar izveidot jaunu lapu. Tā jau eksistē.', # Parser/template warnings 'expensive-parserfunction-category' => 'Lapas ar pārāk daudz laikietilpīgiem apstrādes funkciju izsaukumiem', 'post-expand-template-inclusion-warning' => "'''Brīdinājums:''' iekļauto veidņu izmērs ir par lielu. Dažas veidnes netiks iekļautas.", 'post-expand-template-inclusion-category' => 'Lapas, kurām pārsniegts iekļauto veidņu apjoms', 'post-expand-template-argument-warning' => "'''Brīdinājums:''' Šī lapa satur vairāk neka vienu veidni argumentu, kas ir pārāk liels pec paplašināšanas. Šie argumenti ir izlaists.", 'post-expand-template-argument-category' => 'Lapas, kurās ir izlaisti veidņu argumenti', 'parser-template-loop-warning' => 'Veidne ir ievietota tādā pašā veidnē: [[$1]]', # "Undo" feature 'undo-success' => 'Šo izmaiņu ir iespējams atcelt. Lūdzu, pārbaudi zemāk redzamajā salīdzinājumā, vai tu to tiešām vēlies darīt, un pēc tam saglabā lapu, lai pabeigtu izmaiņas atcelšanu.', 'undo-failure' => 'Šo labojumu nevar atcelt, jo ir veikti nozīmīgi labojumi vēl pēc šī labojuma izdarīšanas.', 'undo-norev' => 'Šo izmaiņu nevar atcelt, jo tādas nav vai tā ir izdzēsta.', 'undo-summary' => 'Atcēlu [[Special:Contributions/$2|$2]] ([[User talk:$2|Diskusija]]) izdarīto izmaiņu $1', # Account creation failure 'cantcreateaccounttitle' => 'Nevar izveidot lietotāju', 'cantcreateaccount-text' => "[[Lietotājs:$3|$3]] ir bloķējis lietotāja izveidošanu no šīs IP adreses ('''$1'''). $3 norādītais iemesls ir ''$2''", # History pages 'viewpagelogs' => 'Apskatīt ar šo lapu saistītos reģistru ierakstus', 'nohistory' => 'Šai lapai nav pieejama versiju hronoloģija.', 'currentrev' => 'Pašreizējā versija', 'currentrev-asof' => 'Pašreizējā versija, $1', 'revisionasof' => 'Versija, kas saglabāta $1', 'revision-info' => 'Versija $1 laikā, kādu to atstāja $2', 'previousrevision' => '← Senāka versija', 'nextrevision' => 'Jaunāka versija →', 'currentrevisionlink' => 'skatīt pašreizējo versiju', 'cur' => 'ar pašreizējo', 'next' => 'nākamais', 'last' => 'ar iepriekšējo', 'page_first' => 'pirmā', 'page_last' => 'pēdējā', 'histlegend' => 'Atšķirību izvēle: atzīmē vajadzīgo versiju apaļās pogas un spied "Salīdzināt izvēlētās versijas".<br /> Apzīmējumi: "ar pašreizējo" = salīdzināt ar pašreizējo versiju, "ar iepriekšējo" = salīdzināt ar iepriekšējo versiju, m = maznozīmīgs labojums.', 'history-fieldset-title' => 'Meklēt hronoloģijā', 'history-show-deleted' => 'Tikai dzēstās', 'histfirst' => 'Senākās', 'histlast' => 'Jaunākās', 'historysize' => '({{PLURAL:$1|1 baits|$1 baiti}})', 'historyempty' => '(tukša)', # Revision feed 'history-feed-title' => 'Versiju hronoloģija', 'history-feed-description' => 'Šīs wiki lapas versiju hronoloģija', 'history-feed-item-nocomment' => '$1 : $2', 'history-feed-empty' => 'Pieprasītā lapa nepastāv. Iespējams, tā ir izdzēsta vai pārdēvēta. Mēģiniet [[Special:Search|meklēt]], lai atrastu saistītas lapas!', # Revision deletion 'rev-deleted-comment' => '(labojuma kopsavilkums dzēsts)', 'rev-deleted-user' => '(lietotāja vārds nodzēsts)', 'rev-deleted-event' => '(reģistra ieraksts nodzēsts)', 'rev-deleted-user-contribs' => '[lietotājvārds vai IP adrese ir dzēsta — izmaiņa slēpta no devuma]', 'rev-deleted-text-permission' => "Šī lapas versija ir '''dzēsta'''. Sīkāku informāciju var atrast [{{fullurl:{{#Special:Log}}/delete|page={{FULLPAGENAMEE}}}} dzēšanas reģistrā].", 'rev-deleted-text-view' => "Šī lapas versija ir '''dzēsta'''. To varat apskatīt, jo esat administrators. Sīkāku informāciju var atrast [{{fullurl:{{#Special:Log}}/delete|page={{FULLPAGENAMEE}}}} dzēšanas reģistrā].", 'rev-deleted-no-diff' => "Tu nevari aplūkot šīs izmaiņas, jo viena no versijām ir '''dzēsta'''. Sīkāku informāciju var atrast [{{fullurl:{{#Special:Log}}/delete|page={{FULLPAGENAMEE}}}} dzēšanas reģistrā].", 'rev-suppressed-no-diff' => "Tu nevari aplūkot šīs izmaiņas, jo viena no versijām ir '''dzēsta'''.", 'rev-delundel' => 'rādīt/slēpt', 'rev-showdeleted' => 'parādīt', 'revisiondelete' => 'Dzēst / atjaunot versijas', 'revdelete-nooldid-title' => 'Nederīga mērķa versija', 'revdelete-nologtype-title' => 'Nav dots reģistra veids.', 'revdelete-nologid-title' => 'Nederīgs reģistra ieraksts', 'revdelete-no-file' => 'Norādītais fails neeksistē.', 'revdelete-show-file-submit' => 'Jā', 'revdelete-legend' => 'Uzstādīt redzamības ierobežojumus', 'revdelete-hide-text' => 'Paslēpt versijas tekstu', 'revdelete-hide-image' => 'Paslēpt faila saturu', 'revdelete-hide-name' => 'Paslēpt darbību un tās objektu', 'revdelete-hide-comment' => 'Paslēpt kopsavilkumu', 'revdelete-hide-user' => 'Paslēpt autora lietotājvārdu/IP adresi', 'revdelete-hide-restricted' => 'Paslēpt datus arī no administratoriem', 'revdelete-radio-same' => '(nemainīt)', 'revdelete-radio-set' => 'Jā', 'revdelete-radio-unset' => 'Nē', 'revdelete-suppress' => 'Paslēpt datus arī no administratoriem', 'revdelete-unsuppress' => 'Atcelt ierobežojumus atjaunotajām versijām', 'revdelete-log' => 'Iemesls:', 'revdelete-submit' => 'Piemērot {{PLURAL:$1|izvēlētajai versijai|izvēlētajām versijām}}', 'revdelete-success' => "'''Versiju redzamība veiksmīgi atjaunināta.'''", 'revdelete-failure' => "'''Versiju redzamību nav iespējams atjaunināt:''' $1", 'logdelete-success' => "'''Reģistra ierakstu redzamība veiksmīgi uzstādīta.'''", 'logdelete-failure' => "'''Reģistra redzamību nevar uzstādīt:''' $1", 'revdel-restore' => 'mainīt redzamību', 'revdel-restore-deleted' => 'dzēstās versijas', 'revdel-restore-visible' => 'redzamās versijas', 'pagehist' => 'Lapas vēsture', 'deletedhist' => 'Vēsture dzēsta', 'revdelete-modify-missing' => 'Kļūda, mainot vienumu ar ID $1: tas ir pazudis no datubāzes!', 'revdelete-reason-dropdown' => '*Biežākie dzēšanas iemesli ** autortiesību pārkāpums ** nepiemērota personīgā informācija ** potenciāli apmelojoša informācija', 'revdelete-otherreason' => 'Cits/papildu iemesls:', 'revdelete-reasonotherlist' => 'Cits iemesls', 'revdelete-edit-reasonlist' => 'Izmainīt dzēšanas iemeslus', 'revdelete-offender' => 'Versijas autors:', # History merging 'mergehistory' => 'Apvienot lapu vēstures', 'mergehistory-box' => 'Apvienot versijas no divām lapām:', 'mergehistory-from' => 'Avota lapa:', 'mergehistory-into' => 'Mērķa lapa:', 'mergehistory-list' => 'Apvienojama labojumu vēsture', 'mergehistory-go' => 'Rādīt apvienojamos labojumus', 'mergehistory-submit' => 'Apvienot versijas', 'mergehistory-empty' => 'Neviena versija nevar tikt apvienota', 'mergehistory-fail' => 'Nav iespējams apvienot hronoloģiju, lūdzu, pārbaudiet vēlreiz lapu un laika parametrus.', 'mergehistory-no-source' => 'Avota lapa $1 nepastāv.', 'mergehistory-no-destination' => 'Mērķa lapa $1 nepastāv.', 'mergehistory-invalid-source' => 'Avota lapas nosaukumam jābūt derīgam.', 'mergehistory-invalid-destination' => 'Mērķa lapas nosaukumam jābūt derīgam.', 'mergehistory-autocomment' => 'Apvienots [[:$1]] ar [[:$2]]', 'mergehistory-comment' => 'Apvienots [[:$1]] ar [[:$2]]: $3', 'mergehistory-same-destination' => 'Avota un mērķa lapas nevar būt tās pašas', 'mergehistory-reason' => 'Iemesls:', # Merge log 'mergelog' => 'Apvienošanas reģistrs', 'pagemerge-logentry' => 'apvienots [[$1]] ar [[$2]] (versijas līdz $3)', 'revertmerge' => 'Atsaukt apvienošanu', # Diffs 'history-title' => '"$1" versiju hronoloģija', 'difference' => '(Atšķirības starp versijām)', 'difference-multipage' => '(Atšķirības starp lapām)', 'lineno' => '$1. rindiņa:', 'compareselectedversions' => 'Salīdzināt izvēlētās versijas', 'showhideselectedversions' => 'Rādīt/slēpt izvēlētās versijas', 'editundo' => 'atcelt', 'diff-multi' => '({{PLURAL:$1|Viena starpversija|$1 starpversijas}} no {{PLURAL:$2|viena lietotāja|$2 lietotājiem}} nav parādīta)', # Search results 'searchresults' => 'Meklēšanas rezultāti', 'searchresults-title' => 'Meklēšanas rezultāti "$1"', 'searchresulttext' => 'Lai iegūtu vairāk informācijas par meklēšanu {{grammar:akuzatīvs|{{SITENAME}}}}, skat. [[{{MediaWiki:Helppage}}|{{grammar:ģenitīvs|{{SITENAME}}}} meklēšana]].', 'searchsubtitle' => 'Pieprasījums: \'\'\'[[:$1]]\'\'\' ([[Special:Prefixindex/$1|visas lapas, kas sākas ar "$1"]]{{int:pipe-separator}}[[Special:WhatLinksHere/$1|visas lapas, kurās ir saite uz "$1"]])', 'searchsubtitleinvalid' => 'Pieprasījums: $1', 'toomanymatches' => 'Tika atgriezti poārāk daudzi rezultāti, lūdzu pamēģini citādāku pieprasījumu', 'titlematches' => 'Rezultāti virsrakstos', 'notitlematches' => 'Neviena rezultāta, meklējot lapas virsrakstā', 'textmatches' => 'Rezultāti lapu tekstos', 'notextmatches' => 'Neviena rezultāta, meklējot lapas tekstā', 'prevn' => 'iepriekšējās {{PLURAL:$1|$1}}', 'nextn' => 'nākamās {{PLURAL:$1|$1}}', 'prevn-title' => '{{PLURAL:$1|Iepriekšējais|Iepriekšējie}} $1 {{PLURAL:$1|rezultāts|rezultāti}}', 'nextn-title' => '{{PLURAL:$1|Nākošais|INākošie}} $1 {{PLURAL:$1|rezultāts|rezultāti}}', 'shown-title' => 'Parādīt $1 {{PLURAL:$1|rezultātu|rezultātus}} vienā lapā', 'viewprevnext' => 'Skatīt ($1 {{int:pipe-separator}} $2) ($3 vienā lapā).', 'searchmenu-legend' => 'Meklēšanas iespējas', 'searchmenu-exists' => "'''Šajā projektā ir raksts ar nosaukumu \"[[:\$1]]\"'''", 'searchmenu-new' => "'''Izveido rakstu \"[[:\$1]]\" šajā projektā!'''", 'searchhelp-url' => 'Help:Saturs', 'searchprofile-articles' => 'Rakstos', 'searchprofile-project' => 'Palīdzības un projektu lapās', 'searchprofile-images' => 'Multivides failos', 'searchprofile-everything' => 'Visur', 'searchprofile-advanced' => 'Izvēlēties sīkāk', 'searchprofile-articles-tooltip' => 'Meklēt iekš $1', 'searchprofile-project-tooltip' => 'Meklēt iekš $1', 'searchprofile-images-tooltip' => 'Meklēt attēlus, audio un video failus', 'searchprofile-everything-tooltip' => 'Meklēt visur (ieskaitot diskusiju lapas)', 'searchprofile-advanced-tooltip' => 'Izvēlēties nosaukumvietas, kurās meklēt', 'search-result-size' => '$1 ({{PLURAL:$2|1 vārds|$2 vārdi}})', 'search-result-score' => 'Atbilstība: $1%', 'search-redirect' => '(pāradresēts no $1)', 'search-section' => '(sadaļa $1)', 'search-suggest' => 'Vai jūs domājāt: $1', 'search-interwiki-caption' => 'Citi projekti', 'search-interwiki-default' => 'Rezultāti no $1:', 'search-interwiki-more' => '(vairāk)', 'search-mwsuggest-enabled' => 'ar ieteikumiem', 'search-mwsuggest-disabled' => 'bez ieteikumiem', 'search-relatedarticle' => 'Saistītais', 'mwsuggest-disable' => 'Atslēgt AJAX ieteikumus', 'searcheverything-enable' => 'Meklēt visās nosaukumvietās', 'searchrelated' => 'saistītais', 'searchall' => 'viss', 'showingresults' => "Šobrīd ir {{PLURAL:$1|redzama|redzamas}} '''$1''' {{PLURAL:$1|lapa|lapas}}, sākot ar #'''$2'''.", 'showingresultsnum' => "Šobrīd ir {{PLURAL:$3|redzama|redzamas}} '''$3''' {{PLURAL:$3|lapa|lapas}}, sākot ar #'''$2'''.", 'showingresultsheader' => "{{PLURAL:$5|Šobrīd ir redzama '''$1''' lapa no '''$3'''|Šobrīd ir redzamas '''$1 — $2''' lapas no '''$3'''}}, kas satur '''$4'''", 'nonefound' => "'''Piezīme:''' bieži vien meklēšana ir neveiksmīga, meklējot plaši izplatītus vārdus, piemēram, \"un\" vai \"ir\", jo tie netiek iekļauti meklēšanas datubāzē, vai arī meklējot vairāk par vienu vārdu (jo rezultātos parādīsies tikai lapas, kurās ir visi meklētie vārdi). Vēl, pēc noklusējuma, pārmeklē tikai dažas ''namespaces''. Lai meklētu visās, meklēšanas pieprasījumam priekšā jāieliek ''all:'', vai arī analogā veidā jānorāda pārmeklējamo ''namespaci''.", 'search-nonefound' => 'Nav atrasti pieprasījumam atbilstoši rezultāti.', 'powersearch' => 'Izvērstā meklēšana', 'powersearch-legend' => 'Izvērstā meklēšana', 'powersearch-ns' => 'Meklēt šajās lapu grupās:', 'powersearch-redir' => 'Parādīt pāradresācijas', 'powersearch-field' => 'Meklēt', 'powersearch-togglelabel' => 'Pārbaudīt:', 'powersearch-toggleall' => 'Viss', 'powersearch-togglenone' => 'Neviena', 'search-external' => 'Ārējā meklēšana', 'searchdisabled' => 'Meklēšana {{grammar:lokatīvs|{{SITENAME}}}} šobrīd ir atslēgta darbības traucējumu dēļ. Pagaidām vari meklēt, izmantojot Google vai Yahoo. Ņem vērā, ka meklētāju indeksētais {{grammar:ģenitīvs|{{SITENAME}}}} saturs var būt novecojis.', # Quickbar 'qbsettings' => 'Rīku joslas stāvoklis', 'qbsettings-fixedleft' => 'Fiksēts pa kreisi', 'qbsettings-fixedright' => 'Fiksēts pa labi', 'qbsettings-floatingleft' => 'Peldošs pa kreisi', 'qbsettings-floatingright' => 'Peldošs pa labi', # Preferences page 'preferences' => 'Izvēles', 'mypreferences' => 'Iestatījumi', 'prefs-edits' => 'Izmaiņu skaits:', 'prefsnologin' => 'Neesi iegājis', 'prefsnologintext' => 'Tev jābūt <span class="plainlinks">[{{fullurl:{{#Special:UserLogin}}|returnto=$1}} iegājušam]</span>, lai mainītu lietotāja izvēles.', 'changepassword' => 'Mainīt paroli', 'prefs-skin' => 'Apdare', 'skin-preview' => 'Priekšskats', 'datedefault' => 'Vienalga', 'prefs-beta' => 'Beta funkcijas', 'prefs-datetime' => 'Datums un laiks', 'prefs-labs' => 'Laboratorijas funkcijas', 'prefs-personal' => 'Lietotāja dati', 'prefs-rc' => 'Pēdējās izmaiņas', 'prefs-watchlist' => 'Uzraugāmie raksti', 'prefs-watchlist-days' => 'Dienu skaits, kuras parādīt uzraugāmo rakstu sarakstā:', 'prefs-watchlist-days-max' => 'Ne vairāk kā $1 {{PLURAL:$1|dienu|dienas}}', 'prefs-watchlist-edits' => 'Izmaiņu skaits, kuras rādīt izvērstajā uzraugāmo rakstu sarakstā:', 'prefs-watchlist-edits-max' => 'Ne vairāk kā 1000', 'prefs-watchlist-token' => 'Uzraugāmo lapu saraksta marķieris:', 'prefs-misc' => 'Dažādi', 'prefs-resetpass' => 'Mainīt paroli', 'prefs-changeemail' => 'Mainīt e-pastu', 'prefs-setemail' => 'Uzstādīt e-pasta adresi', 'prefs-email' => 'E-pasta uzstādījumi', 'prefs-rendering' => 'Izskats', 'saveprefs' => 'Saglabāt', 'resetprefs' => 'Atcelt nesaglabātās izmaiņas', 'restoreprefs' => 'Atjaunot noklusētos uzstādījumus', 'prefs-editing' => 'Rediģēšana', 'prefs-edit-boxsize' => 'Labošanas loga izmērs.', 'rows' => 'Rindiņu skaits:', 'columns' => 'Simbolu skaits rindiņā:', 'searchresultshead' => 'Meklēšana', 'resultsperpage' => 'Lappusē parādāmo rezultātu skaits', 'stub-threshold-disabled' => 'Atslēgts', 'recentchangesdays' => 'Dienu skaits, kuru rādīt pēdējajās izmaiņās:', 'recentchangesdays-max' => 'Ne vairāk kā $1 {{PLURAL:$1|diena|dienas}}', 'recentchangescount' => 'Izmaiņu skaits, kuru rāda pēc noklusējuma:', 'prefs-help-recentchangescount' => 'Šis parametrs attiecas uz pēdējo izmaiņu un hronoloģijas lapām, kā arī uz sistēmas žurnāliem', 'prefs-help-watchlist-token' => 'Šajā laukā tu vari ievadīt slepenu kodu, lai izveidotu RSS barotni savam uzraugāmo lapu sarakstam. Izvēlies drošu kodu, jo katrs, kam ir zināms šis kods, varēs redzēt tavu uzraugāmo lapu sarakstu. Ja vēlies, tu vari izmantot šo nejauši uzģenerēto kodu: $1', 'savedprefs' => 'Tavas izvēles ir saglabātas.', 'timezonelegend' => 'Laika josla:', 'localtime' => 'Vietējais laiks:', 'timezoneuseserverdefault' => 'Lietot viki noklusēto ($1)', 'timezoneuseoffset' => 'Cita (norādi starpību)', 'timezoneoffset' => 'Starpība¹:', 'servertime' => 'Servera laiks šobrīd:', 'guesstimezone' => 'Izmantot datora sistēmas laiku', 'timezoneregion-africa' => 'Āfrika', 'timezoneregion-america' => 'Amerika', 'timezoneregion-antarctica' => 'Antarktīda', 'timezoneregion-arctic' => 'Arktika', 'timezoneregion-asia' => 'Āzija', 'timezoneregion-atlantic' => 'Atlantijas okeāns', 'timezoneregion-australia' => 'Austrālija', 'timezoneregion-europe' => 'Eiropa', 'timezoneregion-indian' => 'Indijas okeāns', 'timezoneregion-pacific' => 'Klusais okeāns', 'allowemail' => 'Atļaut saņemt e-pastus no citiem lietotājiem', 'prefs-searchoptions' => 'Meklēšana', 'prefs-namespaces' => 'Vārdtelpas', 'defaultns' => 'Meklēt šajās palīglapās pēc noklusējuma:', 'default' => 'pēc noklusējuma', 'prefs-files' => 'Attēli', 'prefs-custom-css' => 'Personīgais CSS', 'prefs-custom-js' => 'Personīgais JS', 'prefs-common-css-js' => 'Koplietojams CSS/JavaScript visās apdarēs:', 'prefs-emailconfirm-label' => 'E-pasta statuss:', 'prefs-textboxsize' => 'Rediģēšanas loga izmērs', 'youremail' => 'Tava e-pasta adrese:', 'username' => 'Lietotājvārds:', 'uid' => 'Lietotāja ID:', 'prefs-memberingroups' => 'Pieder {{PLURAL:$1|grupai|grupām}}:', 'prefs-registration' => 'Reģistrēšanās datums:', 'yourrealname' => 'Tavs īstais vārds:', 'yourlanguage' => 'Valoda:', 'yourvariant' => 'Satura valodas variants:', 'yournick' => 'Tava iesauka (parakstam):', 'prefs-help-signature' => 'Komentāri diskusiju lapās ir jāparaksta, pievienojot simbolu virkni "<nowiki>~~~~</nowiki>", kas tiek automātiski aizstāta ar tavu parakstu un parakstīšanās laiku.', 'badsig' => "Kļūdains ''paraksta'' kods; pārbaudi HTML (ja tāds ir lietots).", 'badsiglength' => 'Paraksts ir pārāk garš. Tam ir jābūt īsākam par $1 {{PLURAL:$1|simbolu|simboliem}}.', 'yourgender' => 'Dzimums:', 'gender-unknown' => 'Nav norādīts', 'gender-male' => 'Vīrietis', 'gender-female' => 'Sieviete', 'prefs-help-gender' => 'Dzimums nav obligāti jānorāda (šo parametru programmatūra izmanto, lai ģenerētu paziņojumus, kas atkarīgi no lietotāja dzimuma). Norādītā parametra vērtība būs publiski pieejama.', 'email' => 'E-pasts', 'prefs-help-realname' => 'Īstais vārds nav obligāti jānorāda. Ja tu izvēlies to norādīt, tas tiks izmantots, lai identificētu tavu darbu (ieguldījumu {{grammar:lokatīvs|{{SITENAME}}}}).', 'prefs-help-email' => 'E-pasta adrese nav obligāta, bet ir nepieciešama nozaudētas paroles atjaunošanai.', 'prefs-help-email-others' => 'Jus ari variet izvelties ka citi jus var kontaktēt uz jusu lietotajā sarunas lapu, neatklājot jus identitāti.', 'prefs-help-email-required' => 'E-pasta adrese ir obligāta.', 'prefs-info' => 'Pamatinformācija', 'prefs-i18n' => 'Internacionalizācija', 'prefs-signature' => 'Paraksts', 'prefs-dateformat' => 'Datuma formāts', 'prefs-timeoffset' => 'Laika nobīde', 'prefs-advancedediting' => 'Papildus uzstādījumi', 'prefs-advancedrc' => 'Papildus uzstādījumi', 'prefs-advancedrendering' => 'Papildus uzstādījumi', 'prefs-advancedsearchoptions' => 'Papildus uzstādījumi', 'prefs-advancedwatchlist' => 'Papildus uzstādījumi', 'prefs-displayrc' => 'Pamatuzstādījumi', 'prefs-displaysearchoptions' => 'Pamatuzstādījumi', 'prefs-displaywatchlist' => 'Pamatuzstādījumi', 'prefs-diffs' => 'Izmaiņas', # User preference: email validation using jQuery 'email-address-validity-valid' => 'E-pasta adrese šķiet derīga', 'email-address-validity-invalid' => 'Ievadiet derīgu e-pasta adresi', # User rights 'userrights' => 'Lietotāju tiesību pārvaldība', 'userrights-lookup-user' => 'Pārvaldīt lietotāja grupas', 'userrights-user-editname' => 'Ievadi lietotājvārdu:', 'editusergroup' => 'Izmainīt lietotāja grupas', 'editinguser' => "Izmainīt lietotāja '''[[User:$1|$1]]''' ([[User talk:$1|{{int:talkpagelinktext}}]]{{int:pipe-separator}}[[Special:Contributions/$1|{{int:contribslink}}]]) statusu", 'userrights-editusergroup' => 'Izmainīt lietotāja grupas', 'saveusergroups' => 'Saglabāt lietotāja grupas', 'userrights-groupsmember' => 'Šobrīd ietilpst grupās:', 'userrights-groupsmember-auto' => 'Netiešs dalībnieks:', 'userrights-groups-help' => 'Tu vari izmainīt kādās grupās šis lietotājs ir: * Ieķeksēts lauciņš noāda, ka lietotājs ir attiecīgajā grupā. * Neieķeksēts lauciņš norāda, ka lietotājs nav attiecīgajā grupā. * * norāda, ka šo grupu tu nevarēsi noņemt, pēc tam, kad to būsi pielicis, vai otrādāk (tu nevarēsi atcelt savas izmaiņas).', 'userrights-reason' => 'Iemesls:', 'userrights-no-interwiki' => 'Tev nav atļaujas izmainīt lietotāju tiesības citos wiki.', 'userrights-nodatabase' => 'Datubāze $1 neeksistē vai nav lokāla.', 'userrights-nologin' => 'Tev ir [[Special:UserLogin|jāieiet iekšā]] kā adminam, lai varētu izmainīt lietotāju grupas.', 'userrights-notallowed' => 'Jūsu lietotāja kontam nav atļaujas pievienot vai noņemt lietotāju tiesības.', 'userrights-changeable-col' => 'Grupas, kuras tu vari izmainīt', 'userrights-unchangeable-col' => 'Grupas, kuras tu nevari izmainīt', # Groups 'group' => 'Grupa:', 'group-user' => 'Lietotāji', 'group-autoconfirmed' => 'Automātiski apstiprinātie lietotāji', 'group-bot' => 'Boti', 'group-sysop' => 'Administratori', 'group-bureaucrat' => 'Birokrāti', 'group-suppress' => 'Novērotāji', 'group-all' => '(visi)', 'group-user-member' => '{{GENDER:$1|lietotājs}}', 'group-autoconfirmed-member' => '{{GENDER:$1|automātiski apstiprināts lietotājs|automātiski apstiprināta lietotāja}}', 'group-bot-member' => '{{GENDER:$1|bots}}', 'group-sysop-member' => '{{GENDER:$1|administrators|administratore}}', 'group-bureaucrat-member' => '{{GENDER:$1|birokrāts|birokrāte}}', 'group-suppress-member' => 'novērotājs', 'grouppage-user' => '{{ns:project}}:Lietotāji', 'grouppage-autoconfirmed' => '{{ns:project}}:Automātiski apstiprināti lietotāji', 'grouppage-bot' => '{{ns:project}}:Boti', 'grouppage-sysop' => '{{ns:project}}:Administratori', 'grouppage-bureaucrat' => '{{ns:project}}:Birokrāti', 'grouppage-suppress' => '{{ns:project}}:Novērotājs', # Rights 'right-read' => 'Lasīt lapas', 'right-edit' => 'Izmainīt lapas', 'right-createpage' => 'Izveidot lapas (kuras nav diskusiju lapas)', 'right-createtalk' => 'Izveidot diskusiju lapas', 'right-createaccount' => 'Izveidot jaunus lietotāja kontus', 'right-minoredit' => 'Atzīmēt izmaiņas kā maznozīmīgas', 'right-move' => 'Pārvietot lapas', 'right-move-subpages' => 'Pārvietot lapas kopā ar to apakšlapām', 'right-move-rootuserpages' => 'Pārvietot saknes lietotāja lapas', 'right-movefile' => 'Pārvietot failus', 'right-suppressredirect' => 'Neveidot pāradresāciju no vecā nosaukuma, pārvietojot lapu', 'right-upload' => 'Augšuplādēt failus', 'right-reupload' => 'Pārrakstīt esošu failu', 'right-reupload-own' => 'Pārrakstīt paša augšuplādētu esošu failu', 'right-upload_by_url' => 'Augšuplādēt failu no URL', 'right-autoconfirmed' => 'Izmainīt daļēji aizsargātas lapas', 'right-delete' => 'Dzēst lapas', 'right-bigdelete' => 'Dzēst lapas ar lielām hronoloģijām', 'right-deleterevision' => 'Dzēst un atjaunot lapu noteiktas versijas', 'right-deletedhistory' => 'Skatīt izdzēstos hronoloģijas ierakstus, bez tiem piesaistītā teksta', 'right-deletedtext' => 'Apskatīt izdzēsto tekstu un izmaiņas starp izdzēstām versijām', 'right-browsearchive' => 'Meklēt izdzēstās lapas', 'right-undelete' => 'Atjaunot lapu', 'right-suppressrevision' => 'Apskatīt un atjaunot versijas, kas paslēptas no adminiem', 'right-suppressionlog' => 'Skatīt personīgos reģistrus', 'right-block' => 'Bloķēt citus lietotājus (lapu izmainīšana)', 'right-blockemail' => 'Bloķēt citus lietotājus (iespēja sūtīt e-pastu)', 'right-hideuser' => 'Bloķēt lietotājvārdu, slēpjot to no citiem lietotājiem', 'right-ipblock-exempt' => 'Apiet IP bloķēšanu, automātisku bloķēšanu un IP apgabalu bloķēšanu', 'right-proxyunbannable' => "Apiet ''proxy'' automātiskos blokus", 'right-unblockself' => 'Atbloķēt sevi', 'right-protect' => 'Izmainīt aizsargātās lapas un to aizsardzības līmeni', 'right-editprotected' => 'Labot aizsargātās lapas (bez kaskādes aizsardzības)', 'right-editinterface' => 'Izmainīt lietotāja interfeisu', 'right-editusercssjs' => 'Izmainīt citu lietotāju CSS un JS failus', 'right-editusercss' => 'Izmainīt citu lietotāju CSS failus', 'right-edituserjs' => 'Izmainīt citu lietotāju JS failus', 'right-rollback' => 'Ātri veikt atriti pēdējā lietotāja labojumiem, kas veica izmaiņas kādā konkrētā lapā', 'right-markbotedits' => 'Atzīmēt labojumus, kam veikta atrite, kā bota labojumus', 'right-noratelimit' => 'Būt darbību ātruma ierobežojumu neietekmētiem', 'right-import' => 'Importēt lapas no citiem wiki', 'right-importupload' => 'Importēt lapas no failu augšuplādes', 'right-patrol' => 'Atzīmēt citu labojumus kā pārbaudītus', 'right-autopatrol' => 'Iespēja, ka ikviens paša veiktais labojums tiek automātiski atzīmēts kā pārbaudīts', 'right-patrolmarks' => 'Apskatīt pēdējo izmaiņu lapu pārbaužu atzīmes', 'right-unwatchedpages' => 'Apskatīt neuzraudzīto lapu sarakstu', 'right-mergehistory' => 'Apvienot lapu vēsturi', 'right-userrights' => 'Mainīt visu lietotāju tiesības', 'right-userrights-interwiki' => 'Mainīt lietotāju tiesības citās Vikipēdijās', 'right-siteadmin' => 'Bloķēt un atbloķēt datubāzi', 'right-sendemail' => 'Sūtīt e-pastu citiem lietotājiem', 'right-passwordreset' => 'Apskatīt paroles atiestatīšanas e-pasta ziņojumus', # User rights log 'rightslog' => 'Lietotāju tiesību reģistrs', 'rightslogtext' => 'Šis ir lietotāju tiesību izmaiņu reģistrs.', 'rightslogentry' => 'izmainīja $1 grupas no $2 uz $3', 'rightsnone' => '(nav)', # Associated actions - in the sentence "You do not have permission to X" 'action-read' => 'lasīt šo lapu', 'action-edit' => 'labot šo lapu', 'action-createpage' => 'izveidot lapas', 'action-createtalk' => 'izveidot diskusiju lapas', 'action-createaccount' => 'izveidot šo lietotāja kontu', 'action-minoredit' => 'atzīmēt šo labojumu kā maznozīmīgu', 'action-move' => 'pārvietot šo lapu', 'action-move-subpages' => 'pārvietot šo lapu un tās apakšlapas', 'action-move-rootuserpages' => 'pārvietot saknes lietotāja lapas', 'action-movefile' => 'pārvietot šo failu', 'action-upload' => 'augšupielādēt šo failu', 'action-reupload' => 'pārrakstīt esošo failu', 'action-upload_by_url' => 'augšupielādēt šo failu no URL', 'action-writeapi' => 'izmantot rakstīto lietojumprogrammu saskarni', 'action-delete' => 'izdzēst šo lapu', 'action-deleterevision' => 'izdzēst šo versiju', 'action-deletedhistory' => 'skatīt šīs lapas dzēsto hronoloģiju', 'action-browsearchive' => 'meklēt dzēstās lapas', 'action-undelete' => 'atjaunot šo lapu', 'action-suppressrevision' => 'pārskatīt un atjaunot šo slēpto versiju', 'action-suppressionlog' => 'apskatīt šo privāto reģistru', 'action-block' => 'bloķēt šo lietotāju pret rakstu turpmāku labošanu', 'action-protect' => 'izmainīt aizsardzības līmeņus šai lapai', 'action-import' => 'importēt šo lapu no citas viki', 'action-importupload' => 'importēt šo lapu no failu augšupielādes', 'action-patrol' => 'atzīmēt citu labojumus kā pārbaudītus', 'action-autopatrol' => 'iespēja savus labojumus atzīmēt kā pārbaudītus', 'action-unwatchedpages' => 'apskatīt neuzraudzīto lapu sarakstu', 'action-mergehistory' => 'apvienot šīs lapas vēsturi', 'action-userrights' => 'mainīt visu lietotāju tiesības', 'action-userrights-interwiki' => 'mainīt lietotāju tiesības citās Vikipēdijās', 'action-siteadmin' => 'bloķēt vai atbloķēt datubāzi', 'action-sendemail' => 'sūtīt e-pastus', # Recent changes 'nchanges' => '$1 {{PLURAL:$1|izmaiņa|izmaiņas}}', 'recentchanges' => 'Pēdējās izmaiņas', 'recentchanges-legend' => 'Pēdējo izmaiņu iespējas', 'recentchangestext' => 'Šajā lapā ir uzskaitītas pēdējās izdarītās izmaiņas.', 'recentchanges-feed-description' => 'Sekojiet līdzi jaunākajām izmaiņām vikijā izmantojot šo barotni.', 'recentchanges-label-newpage' => 'Šī ir jaunizveidota lapa', 'recentchanges-label-minor' => 'Šī ir maznozīmīga izmaiņa', 'recentchanges-label-bot' => 'Šī ir bota veikta izmaiņa', 'recentchanges-label-unpatrolled' => 'Šis labojums vēl nav pārbaudīts', 'rcnote' => 'Šobrīd ir {{PLURAL:$1|redzama pēdējā <strong>$1</strong> izmaiņa, kas izdarīta|redzamas pēdējās <strong>$1</strong> izmaiņas, kas izdarītas}} {{PLURAL:$2|pēdējā|pēdējās}} <strong>$2</strong> {{PLURAL:$2|dienā|dienās}} (līdz $4, $5).', 'rcnotefrom' => "Šobrīd redzamas izmaiņas kopš '''$2''' (parādītas ne vairāk par '''$1''').", 'rclistfrom' => 'Parādīt jaunas izmaiņas kopš $1', 'rcshowhideminor' => '$1 maznozīmīgos', 'rcshowhidebots' => '$1 botus', 'rcshowhideliu' => '$1 reģistrētos', 'rcshowhideanons' => '$1 anonīmos', 'rcshowhidepatr' => '$1 pārbaudītie labojumi', 'rcshowhidemine' => '$1 manus', 'rclinks' => 'Parādīt pēdējās $1 izmaiņas pēdējās $2 dienās.<br />$3', 'diff' => 'izmaiņas', 'hist' => 'hronoloģija', 'hide' => 'paslēpt', 'show' => 'parādīt', 'minoreditletter' => 'm', 'newpageletter' => 'J', 'boteditletter' => 'b', 'number_of_watching_users_pageview' => '[šo lapu uzrauga $1 {{PLURAL:$1|lietotājs|lietotāji}}]', 'rc_categories' => 'Ierobežot uz kategorijām (atdalīt ar "|")', 'rc_categories_any' => 'Jebkas', 'newsectionsummary' => '/* $1 */ jauna sadaļa', 'rc-enhanced-expand' => 'Rādīt informāciju (nepieciešams JavaScript)', 'rc-enhanced-hide' => 'Paslēpt detaļas', 'rc-old-title' => 'sākotnēji izveidota kā "$1 "', # Recent changes linked 'recentchangeslinked' => 'Saistītās izmaiņas', 'recentchangeslinked-feed' => 'Saistītās izmaiņas', 'recentchangeslinked-toolbox' => 'Saistītās izmaiņas', 'recentchangeslinked-title' => 'Izmaiņas, kas saistītas ar "$1"', 'recentchangeslinked-noresult' => 'Norādītajā laika periodā saistītajās lapās izmaiņu nebija.', 'recentchangeslinked-summary' => "Šiet ir nesen izdarītās izmaiņas lapās, uz kurām ir saites no norādītās lapas (vai norādītajā kategorijā ietilpstošās lapas). Lapas, kas ir tavā [[Special:Watchlist|uzraugāmo rakstu sarakstā]] ir '''treknas'''.", 'recentchangeslinked-page' => 'Lapas nosaukums:', 'recentchangeslinked-to' => 'Rādīt izmaiņas lapās, kurās ir saites uz šo lapu (nevis lapās uz kurām ir saites no šīs lapas)', # Upload 'upload' => 'Augšuplādēt failu', 'uploadbtn' => 'Augšuplādēt', 'reuploaddesc' => 'Atcelt augšupielādi un atgriezties pie augšupielādes veidnes.', 'upload-tryagain' => 'Iesniegt izmainīto faila aprakstu', 'uploadnologin' => 'Neesi iegājis', 'uploadnologintext' => 'Tev jābūt [[Special:UserLogin|iegājušam]], lai augšuplādētu failus.', 'upload_directory_missing' => 'Augšupielādes direktorijs ($1) ir pazudis, un to tīmekļa serveris nevar izveidot.', 'upload_directory_read_only' => 'Augšupielādes direktoriju ($1) tīmekļa serveris nevar labot.', 'uploaderror' => 'Augšupielādes kļūda', 'upload-recreate-warning' => "'''Brīdinājums: Fails ar šādu nosaukumu ir dzēsts vai pārvietots.''' Dzēšanas un pārvietošanas reģistri šai lapai ir uzskaitīti šeit:", 'uploadtext' => "Pirms tu kaut ko augšupielādē, noteikti izlasi un ievēro [[Project:Attēlu izmantošanas noteikumi|attēlu izmantošanas noteikumus]]. Lai aplūkotu vai meklētu agrāk augšuplādētus attēlus, dodies uz [[Special:FileList|augšupielādēto attēlu sarakstu]]. Augšupielādes un dzēšanas tiek reģistrētas [[Special:Log/upload|augšupielādes reģistrā]] un [[Special:Log/delete|dzēšanas reģistrā]]. Izmanto šo veidni, lai augšupielādētu jaunus attēlu failus, ar kuriem ilustrēt tevis izmainītās lapas. Gandrīz visos pārlūkos tev vajadzētu redzēt pogu '''\"Choose...\",''' kuru spiežot parādīsies faila atvēršanas dialogs. Izvēloties kādu failu, tā adrese parādīsies ailītē blakus šai pogai. Tev ir arī jāatzīmē ailīte, kas apstiprina, ka tu nepārkāp nekādas autortiesības, augšupielādējot šo failu. Spied pogu '''Augšuplādēt''', lai pabeigtu augšupielādi. Tas var ieilgt, ja tavs interneta pieslēgums ir lēns. Ieteicamie formāti ir: * JPEG - ja tā ir fotogrāfija, * PNG - ja tas ir zīmējums vai kāda ikona, un * OGG - ja tas ir skaņas fails. Lūdzu, pārliecinies, ka faila nosaukums ir pietiekami aprakstošs, lai izvairītos no neskaidrībām. Lai attēlu pēc tam ievietotu kādā lapā, izmanto šādi noformētu linkus: * '''<nowiki>[[</nowiki>{{ns:file}}<nowiki>:Fails.jpg|paskaidrojošs teksts]]</nowiki>''' * '''<nowiki>[[</nowiki>{{ns:file}}<nowiki>:Fails.png|paskaidrojošs teksts]]</nowiki>''' vai skaņām * '''<nowiki>[[</nowiki>{{ns:media}}<nowiki>:Fails.ogg]]</nowiki>''' Lūdzu, ņem vērā, ka tāpat kā citas wiki lapas arī tevis augšuplādētos failus citi var mainīt vai dzēst, ja uzskata, ka tas nāktu par labu šim projektam, kā arī atceries, ka tev var tikt liegta augšupielādes iespēja, ja tu šo sistēmu.", 'upload-permitted' => 'Atļautie failu tipi: $1.', 'upload-preferred' => 'Ieteicamie failu tipi: $1.', 'upload-prohibited' => 'Aizliegtie failu tipi: $1.', 'uploadlog' => 'augšupielādes reģistrs', 'uploadlogpage' => 'Augšupielādes reģistrs', 'uploadlogpagetext' => 'Zemāk ir redzams jaunāko augšuplādēto failu saraksts. Pārskatāmāka versija ir pieejama [[Special:NewFiles|jauno attēlu galerijā]].', 'filename' => 'Faila nosaukums', 'filedesc' => 'Kopsavilkums', 'fileuploadsummary' => 'Informācija par failu:', 'filereuploadsummary' => 'Faila izmaiņas:', 'filestatus' => 'Autortiesību statuss:', 'filesource' => 'Izejas kods:', 'uploadedfiles' => 'Augšupielādēja failus', 'ignorewarning' => 'Ignorēt brīdinājumu un saglabāt failu', 'ignorewarnings' => 'Ignorēt visus brīdinājumus', 'minlength1' => 'Failu vārdiem jābūt vismaz vienu simbolu gariem.', 'illegalfilename' => 'Faila nosaukumā "$1" ir simboli, kas nav atļauti virsrakstos. Lūdzu, pārdēvē failu un mēģini to vēlreiz augšuplādēt.', 'filename-toolong' => 'Failu nosaukumi nedrīkst pārsniegt 240 baitus.', 'badfilename' => 'Attēla nosaukums ir nomainīts, tagad tas ir "$1".', 'filetype-mime-mismatch' => 'Faila paplašinājums ".$1" neatbilst noteiktajam MIME tipam ($2).', 'filetype-badmime' => 'Šeit nav atļauts augšuplādēt failus ar MIME tipu "$1".', 'filetype-bad-ie-mime' => 'Nevar augšupielādēt šo failu, jo Internet Explorer to uzskatītu kā "$1", kas ir neatļauts un potenciāli bīstams faila tips.', 'filetype-unwanted-type' => "'''\".\$1\"''' ir nevēlams failu tips. {{PLURAL:\$3|Ieteicamais faila tips|Ieteicamie failu tipi}} ir \$2.", 'filetype-banned-type' => "'''\".\$1\"''' nav atļautais failu tips. {{PLURAL:\$3|Atļautais faila tips|Atļautie failu tipi}} ir \$2.", 'filetype-missing' => 'Failam nav paplašinājuma (piem. tāda kā ".jpg").', 'empty-file' => 'Fails, ko Tu iesniedzi, bija tukšs.', 'file-too-large' => 'Fails, ko Tu iesniedzi, bija pārāk liels.', 'filename-tooshort' => 'Faila nosaukums ir pārāk īss.', 'filetype-banned' => 'Šis failu tips ir aizliegts.', 'verification-error' => 'Šis fails neizturēja failu pārbaudi.', 'illegal-filename' => 'Faila nosaukums nav atļauts.', 'overwrite' => 'Pārrakstīt jau esošu failu nav atļauts.', 'unknown-error' => 'Nezināma kļūda.', 'tmp-create-error' => 'Neizdevās izveidot pagaidu failu.', 'tmp-write-error' => 'Kļūda veidojot pagaidu failu.', 'large-file' => 'Ieteicams, lai faili nebūtu lielāki par $1; šī faila izmērs ir $2.', 'largefileserver' => 'Šis fails ir lielāks nekā serveris ņem pretī.', 'emptyfile' => 'Šķiet, ka tu esi augšuplādējis tukšu failu. Iespējams, faila nosaukumā esi pieļāvis kļūdu. Lūdzu, pārbaudi, vai tiešām tu vēlies augšuplādēt tieši šo failu.', 'windows-nonascii-filename' => 'Šī viki neatbalsta failu nosaukumus ar īpašām rakstzīmēm.', 'fileexists' => 'Fails ar šādu nosaukumu jau pastāv, lūdzu, pārbaudi <strong>[[:$1]]</strong>, ja neesi drošs, ka vēlies to mainīt. [[$1|thumb]]', 'fileexists-extension' => 'Pastāv fails ar līdzīgu nosaukumu: [[$2|thumb]] * Augšupielādējamā faila nosaukums: <strong>[[:$1]]</strong> * Esošā faila nosaukums: <strong>[[:$2]]</strong> Lūdzu, izvēlieties citu nosaukumu.', 'file-thumbnail-no' => "Faila vārds sākas ar <strong>$1</strong>. Izskatās, ka šis ir samazināts attēls ''(thumbnail)''. Ja tev ir šis pats attēls pilnā izmērā, augšuplādē to, ja nav, tad nomaini faila vārdu.", 'fileexists-forbidden' => 'Fails ar šādu nosaukumu jau eksistē un to nevar aizvietot ar jaunu. Ja tu joprojām gribi augšuplādēt šo failu, tad mēģini vēlreiz, ar citu faila vārdu. [[File:$1|thumb|center|$1]]', 'file-exists-duplicate' => 'Fails ir kopija {{PLURAL:$1|šim failam|šiem failiem}}:', 'uploadwarning' => 'Augšupielādes brīdinājums', 'uploadwarning-text' => 'Lūdzu, pārveido zemāk esošo faila aprakstu un mēģini vēlreiz.', 'savefile' => 'Saglabāt failu', 'uploadedimage' => 'augšupielādēja "[[$1]]"', 'overwroteimage' => 'augšupielādēta jauna "[[$1]]" versija', 'uploaddisabled' => 'Augšupielāde atslēgta', 'copyuploaddisabled' => 'URL augšupielādes nav atļautas.', 'uploadfromurl-queued' => 'Tava augšupielāde tika pievienota rindā.', 'uploaddisabledtext' => 'Failu augšupielāde ir atslēgta.', 'php-uploaddisabledtext' => 'Failu augšupielāde ir atslēgta PHP. Lūdzu, pārbaudi file_uploads uzstādījumu.', 'uploadscripted' => 'Šis fails satur HTML vai skriptu kodu, kuru, interneta pārlūks, var kļūdas pēc, mēģināt interpretēt (ar potenciāli sliktām sekām).', 'uploadvirus' => 'Šis fails satur vīrusu! Sīkāk: $1', 'uploadjava' => 'Fails ir ZIP fails, kas satur Java .class failu. Java failu augšupielāde nav atļauta, jo tas var radīt iespējas apiet drošības ierobežojumus.', 'upload-source' => 'Augšuplādējamais fails', 'sourcefilename' => 'Faila adrese:', 'sourceurl' => 'Avota URL:', 'destfilename' => 'Mērķa faila nosaukums:', 'upload-maxfilesize' => 'Maksimālais faila izmērs: $1', 'upload-description' => 'Faila apraksts', 'upload-options' => 'Augšupielādes iestatījumi', 'watchthisupload' => 'Uzraudzīt šo failu', 'filewasdeleted' => 'Fails ar šādu nosaukumu jau ir bijis augšuplādēts un pēc tam izdzēsts. Apskaties $1 pirms turpini šo failu augšuplādēt atkārtoti.', 'filename-bad-prefix' => "Faila vārds failam, kuru tu mēģini augšpulādēt, sākas ar '''\"\$1\"''', kas ir neaprakstošs vārds, kādu parasti uzģenerē digitālais fotoaparāts. Lūdzu izvēlies aprakstošāku vārdu šim failam.", 'upload-success-subj' => 'Augšupielāde veiksmīga', 'upload-success-msg' => 'Jūsu augšupielādēt no [$2] bija veiksmīga. Tā ir pieejama šeit: [[:{{ns:file}}:$1]]', 'upload-failure-subj' => 'Augšupielādes problēma', 'upload-failure-msg' => 'Radās problēma ar jūsu augšupielādi no [$2]: $1', 'upload-warning-subj' => 'Augšupielādes brīdinājums', 'upload-warning-msg' => 'Radās problēma ar jūsu augšupielādi no [$2]. Lai labotu šo problēmu, jūs varat atgriezties uz [[Special:Upload/stash/$1|augšupielādes formu]].', 'upload-proto-error' => 'Nepareizs protokols', 'upload-proto-error-text' => 'Attālinātai augšupielādei URL ir jāsākas ar <code>http://</code> vai <code>ftp://</code>.', 'upload-file-error' => 'Iekšējā kļūda', 'upload-file-error-text' => 'Iekšējā kļūda, mēģinot izveidot pagaidu failu uz servera. Lūdzu, sazinieties ar [[Special:ListUsers/sysop|administratoru.]]', 'upload-misc-error' => 'Nezināma augšupielādes kļūda', 'upload-too-many-redirects' => 'URL sastāvēja pārāk daudz pāradresāciju', 'upload-unknown-size' => 'Nezināms izmērs', 'upload-http-error' => 'HTTP kļūda: $1', # File backend 'backend-fail-stream' => 'Nevar straumēt failu $1.', 'backend-fail-backup' => 'Nevar dublēt failu $1.', 'backend-fail-notexists' => 'Fails $1 nepastāv.', 'backend-fail-hashes' => 'Neizdevās iegūt failu kontrolsummas salīdzināšanai.', 'backend-fail-notsame' => 'Neidentisks fails jau pastāv $1.', 'backend-fail-delete' => 'Nevar izdzēst failu $1.', 'backend-fail-alreadyexists' => 'Fails $1 jau pastāv.', 'backend-fail-store' => 'Neizdevās saglabāt failu "$1" "$2".', 'backend-fail-copy' => 'Nevar kopēt failu $1 uz $2.', 'backend-fail-move' => 'Nevar pārvietot failu $1 uz $2.', 'backend-fail-opentemp' => 'Nevar atvērt pagaidu failu.', 'backend-fail-writetemp' => 'Nevar ierakstīt pagaidu failu.', 'backend-fail-closetemp' => 'Nevar aizvērt pagaidu failu.', 'backend-fail-read' => 'Nevar lasīt failu $1.', 'backend-fail-create' => 'Nevar izveidot failu $1.', # ZipDirectoryReader 'zip-wrong-format' => 'Norādītais fails nebija ZIP fails.', # Special:UploadStash 'uploadstash-errclear' => 'Failu tīrīšana bija neveiksmīga.', 'uploadstash-refresh' => 'Atsvaidzināt failu sarakstu', # img_auth script messages 'img-auth-accessdenied' => 'Pieeja liegta', 'img-auth-nopathinfo' => 'Trūkst PATH_INFO. Jūsu serveris nav konfigurēts nodot šo informāciju. Tas var būt bāzēts uz CGI un neatbalstīt img_auth. Skatīt https://www.mediawiki.org/wiki/Manual:Image_Authorization.', 'img-auth-nologinnWL' => 'Jūs neesat iegājis un "$1" nav baltajā sarakstā.', 'img-auth-nofile' => 'Fails "$1" nepastāv.', 'img-auth-isdir' => 'Jūs mēģinājāt piekļūt direktorijai "$1". Atļauta ir tikai failu piekļuve.', 'img-auth-streaming' => 'Straumē "$1".', # HTTP errors 'http-invalid-url' => 'Nederīgs URL: $1', 'http-read-error' => 'HTTP nolasīšanas kļūda.', 'http-host-unreachable' => 'URL nevarēja sasniegt.', # Some likely curl errors. More could be added from <http://curl.haxx.se/libcurl/c/libcurl-errors.html> 'upload-curl-error6' => 'URL nevarēja sasniegt', 'upload-curl-error28' => 'Augšupielādes noildze', 'license' => 'Licence:', 'license-header' => 'Licence', 'nolicense' => 'Neviena licence nav izvēlēta', 'license-nopreview' => '(Priekšskatījums nav pieejams)', 'upload_source_url' => '(derīgs, publiski pieejams URL)', 'upload_source_file' => '(fails datorā)', # Special:ListFiles 'listfiles-summary' => 'Šajā īpašajā lapā ir redzami visi augšuplādētie faili. Filtrējot pēc lietotāja, tiek rādītas tikai pēdējās lietotāja augšupielādētās faila versijas.', 'listfiles_search_for' => 'Meklēt failu pēc vārda:', 'imgfile' => 'fails', 'listfiles' => 'Attēlu uzskaitījums', 'listfiles_thumb' => 'Sīktēls', 'listfiles_date' => 'Datums', 'listfiles_name' => 'Nosaukums', 'listfiles_user' => 'Lietotājs', 'listfiles_size' => 'Izmērs', 'listfiles_description' => 'Apraksts', 'listfiles_count' => 'Versijas', # File description page 'file-anchor-link' => 'Attēls', 'filehist' => 'Faila hronoloģija', 'filehist-help' => 'Uzklikšķini uz datums/laiks kolonnā esošās saites, lai apskatītos, kā šis fails izskatījās tad.', 'filehist-deleteall' => 'dzēst visus', 'filehist-deleteone' => 'dzēst', 'filehist-revert' => 'atjaunot', 'filehist-current' => 'tagadējais', 'filehist-datetime' => 'Datums/Laiks', 'filehist-thumb' => 'Attēls', 'filehist-thumbtext' => '$1 versijas sīktēls', 'filehist-nothumb' => 'Nav sīktēla', 'filehist-user' => 'Lietotājs', 'filehist-dimensions' => 'Izmēri', 'filehist-filesize' => 'Faila izmērs', 'filehist-comment' => 'Komentārs', 'filehist-missing' => 'Fails pazudis', 'imagelinks' => 'Faila lietojums', 'linkstoimage' => '{{PLURAL:$1|Šajā lapā ir saite|Šajās $1 lapās ir saites}} uz šo failu:', 'nolinkstoimage' => 'Nevienā lapā nav norāžu uz šo attēlu.', 'morelinkstoimage' => 'Skatīt [[Special:WhatLinksHere/$1|vairāk saites]] uz šo failu.', 'linkstoimage-redirect' => '$1 (faila pāradresācija) $2', 'sharedupload' => 'Šis fails ir augšupielādēts no $1 un ir koplietojams citos projektos.', 'sharedupload-desc-there' => 'Fails ir no $1, tāpēc tas var tikt izmantots citos projektos. Lūdzu, skatīt [$2 faila apraksta lapu] papildu informācijai.', 'sharedupload-desc-here' => 'Fails ir no $1, tāpēc tas var tikt izmantots citos projektos. Apraksts ir [$2 faila apraksta lapā], kas ir parādīta zemāk.', 'filepage-nofile' => 'Ar šādu nosaukumu nav neviena faila.', 'filepage-nofile-link' => 'Ar šādu nosaukumu nav neviena faila, bet Jūs varat tādu [$1 augšupielādēt].', 'uploadnewversion-linktext' => 'Augšupielādēt jaunu šī faila versiju', 'shared-repo-from' => 'no $1', 'shared-repo' => 'kopējā krātuve', # File reversion 'filerevert' => 'Atjaunot $1', 'filerevert-legend' => 'Atjaunot failu', 'filerevert-intro' => "Tu atjauno failu '''[[Media:$1|$1]]''' uz [$4 versiju kāda bija $3, $2].", 'filerevert-comment' => 'Iemesls:', 'filerevert-defaultcomment' => 'Atjaunots uz $2, $1 versiju', 'filerevert-submit' => 'Atjaunot', 'filerevert-success' => "Fails '''[[Media:$1|$1]]''' tika atjaunots uz [$4 versiju, kāda tā bija $3, $2].", 'filerevert-badversion' => 'Šajam failam nav iepriekšējās versijas, kas atbilstu norādītajam datumam un laikam.', # File deletion 'filedelete' => 'Dzēst $1', 'filedelete-legend' => 'Dzēst failu', 'filedelete-intro' => "Tu taisies izdzēst '''[[Media:$1|$1]]''', kopā ar visu tā hronoloģiju.", 'filedelete-intro-old' => "Tu tagad taisies izdzēst faila '''[[Media:$1|$1]]''' versiju, kas tika augšuplādēta [$4 $3, $2].", 'filedelete-comment' => 'Iemesls:', 'filedelete-submit' => 'Izdzēst', 'filedelete-success' => "'''$1''' tika veiksmīgi izdzēsts.", 'filedelete-success-old' => "Faila '''[[Media:$1|$1]]''' versija $3, $2 tika izdzēsta.", 'filedelete-nofile' => "'''$1''' nav atrodams.", 'filedelete-nofile-old' => "Failam '''$1''' nav vecas versijas ar norādītajiem parametriem.", 'filedelete-otherreason' => 'Cits/papildu iemesls:', 'filedelete-reason-otherlist' => 'Cits iemesls', 'filedelete-reason-dropdown' => '*Izplatīti dzēšanas iemesli ** Autortiesību pārkāpums ** Viens tāds jau ir', 'filedelete-edit-reasonlist' => 'Izmainīt dzēšanas iemeslus', 'filedelete-maintenance' => 'Failu dzēšana un atjaunošana uzturēšanas laikā ir atslēgta.', 'filedelete-maintenance-title' => 'Nevar izdzēst failu', # MIME search 'mimesearch' => 'MIME meklēšana', 'mimetype' => 'MIME tips:', 'download' => 'lejupielādēt', # Unwatched pages 'unwatchedpages' => 'Neuzraudzītās lapas', # List redirects 'listredirects' => 'Pāradresāciju uzskaitījums', # Unused templates 'unusedtemplates' => 'Neizmantotās veidnes', 'unusedtemplatestext' => 'Šajā lapā ir uzskaitītas visas veidnes, kas nav iekļautas nevienā citā lapā. Ja tās paredzēts dzēst, pirms dzēšanas jāpārbauda citu veidu saites uz dzēšamajām veidnēm.', 'unusedtemplateswlh' => 'citas saites', # Random page 'randompage' => 'Nejauša lapa', # Random redirect 'randomredirect' => 'Nejauša pāradresācijas lapa', # Statistics 'statistics' => 'Statistika', 'statistics-header-pages' => 'Lapu statistika', 'statistics-header-edits' => 'Izmaiņu statistika', 'statistics-header-views' => 'Apskatīt statistiku', 'statistics-header-users' => 'Statistika par lietotājiem', 'statistics-header-hooks' => 'Cita statistika', 'statistics-articles' => 'Satura lapas', 'statistics-pages' => 'Lapas', 'statistics-pages-desc' => 'Visas šajā wiki esošās lapas, ieskaitot diskusiju lapas, pāradresācijas, utt.', 'statistics-files' => 'Augšuplādētie faili', 'statistics-edits' => 'Lapu izmaiņas kopš {{grammar:ģenitīvs{{SITENAME}}}} izveidošanas', 'statistics-edits-average' => 'Vidējais izmaiņu skaits uz lapu', 'statistics-views-total' => 'Skatījumi kopā', 'statistics-views-peredit' => 'Skatījumu skaits uz labojumu', 'statistics-users' => 'Reģistrēti lietotāji', 'statistics-users-active' => 'Aktīvi lietotāji', 'statistics-users-active-desc' => 'Lietotāji, kas ir veikuši jebkādu darbību {{PLURAL:$1|iepriekšējā dienā|iepriekšējās $1 dienās}}', 'statistics-mostpopular' => 'Visvairāk skatītās lapas', 'disambiguations' => 'Lapas, kuras norāda uz nozīmju atdalīšanas lapām', 'disambiguationspage' => 'Template:Disambig', 'disambiguations-text' => "Šeit esošajās lapās ir saite uz '''nozīmju atdalīšanas lapu'''. Šīs saites vajadzētu izlabot, lai tās vestu tieši uz attiecīgo lapu.<br /> Lapu uzskata par nozīmju atdalīšanas lapu, ja tā satur veidni, uz kuru ir saite no [[MediaWiki:Disambiguationspage]].", 'doubleredirects' => 'Divkāršas pāradresācijas lapas', 'doubleredirectstext' => 'Šajā lapā ir uzskaitītas pāradresācijas lapas, kuras pāradresē uz citām pāradresācijas lapām. Katrā rindiņā ir saites uz pirmo un otro pāradresācijas lapu, kā arī pirmā rindiņa no otrās pāradresācijas lapas teksta, kas parasti ir faktiskā "gala" lapa, uz kuru vajadzētu būt saitei pirmajā lapā. <del>Nosvītrotie</del> ieraksti jau ir tikuši salaboti.', 'double-redirect-fixed-move' => '[[$1]] bija ticis pārvietots, tas tagad ir pāradresācija uz [[$2]]', 'double-redirect-fixed-maintenance' => 'Labota dubultā pāradresācija no [[$1]] uz [[$2]].', 'double-redirect-fixer' => 'Pāradresāciju labotājs', 'brokenredirects' => 'Kļūdainas pāradresācijas', 'brokenredirectstext' => 'Šīs ir pāradresācijas lapas uz neesošām lapām:', 'brokenredirects-edit' => 'labot', 'brokenredirects-delete' => 'dzēst', 'withoutinterwiki' => 'Lapas bez starpviki saitēm', 'withoutinterwiki-summary' => "Šajās lapās nav saišu uz citu valodu projektiem (''interwiki''):", 'withoutinterwiki-legend' => 'Prefikss', 'withoutinterwiki-submit' => 'Rādīt', 'fewestrevisions' => 'Lapas, kurām ir vismazāk veco versiju', # Miscellaneous special pages 'nbytes' => '$1 {{PLURAL:$1|baits|baitu}}', 'ncategories' => '$1 {{PLURAL:$1|kategorija|kategorijas}}', 'nlinks' => '$1 {{PLURAL:$1|saite|saites}}', 'nmembers' => '$1 {{PLURAL:$1|lapa|lapas}}', 'nrevisions' => '$1 {{PLURAL:$1|versija|versijas}}', 'nviews' => 'skatīta $1 {{PLURAL:$1|reizi|reizes}}', 'nimagelinks' => 'Izmantots $1 {{PLURAL:$1|lapā|lapās}}', 'ntransclusions' => 'izmantots $1 {{PLURAL:$1|lapā|lapās}}', 'specialpage-empty' => 'Šim ziņojumam nav rezultātu.', 'lonelypages' => 'Lapas bez saitēm uz tām', 'uncategorizedpages' => 'Nekategorizētās lapas', 'uncategorizedcategories' => 'Nekategorizētās kategorijas', 'uncategorizedimages' => 'Nekategorizētie attēli', 'uncategorizedtemplates' => 'Nekategorizētās veidnes', 'unusedcategories' => 'Neizmantotas kategorijas', 'unusedimages' => 'Neizmantoti attēli', 'popularpages' => 'Populārākās lapas', 'wantedcategories' => 'Sarkanas kategorijas', 'wantedpages' => 'Pieprasītās lapas', 'wantedfiles' => 'Vajadzīgie faili', 'wantedtemplates' => 'Vajadzīgās veidnes', 'mostlinked' => 'Lapas, uz kurām ir visvairāk norāžu', 'mostlinkedcategories' => 'Kategorijas, uz kurām ir visvairāk saišu', 'mostlinkedtemplates' => 'Visvairāk izmantotās veidnes', 'mostcategories' => 'Raksti ar visvairāk kategorijām', 'mostimages' => 'Attēli, uz kuriem ir visvairāk saišu', 'mostrevisions' => 'Raksti, kuriem ir visvairāk iepriekšēju versiju', 'prefixindex' => 'Meklēt pēc virsraksta pirmajiem burtiem', 'prefixindex-namespace' => 'Visas lapas ar prefiksu ($1 vārdtelpa)', 'shortpages' => 'Īsākās lapas', 'longpages' => 'Garākās lapas', 'deadendpages' => 'Lapas bez izejošām saitēm', 'protectedpages' => 'Aizsargātās lapas', 'protectedpages-indef' => 'Tikai bezgalīgas aizsardzības', 'protectedpages-cascade' => 'Tikai kaskādes aizsardzības', 'protectedtitles' => 'Aizsargātie nosaukumi', 'protectedtitlestext' => 'Lapas ar šādiem nosaukumiem ir aizsargātas pret lapas izveidošanu', 'protectedtitlesempty' => 'Pagaidām nevienas lapas nosaukums nav aizsargāts ar šiem paraametriem.', 'listusers' => 'Lietotāju uzskaitījums', 'listusers-editsonly' => 'Rādīt tikai lietotājus, kas ir izdarījuši kādas izmaiņas', 'listusers-creationsort' => 'Kārtot pēc izveidošanas datuma', 'usereditcount' => '$1 {{PLURAL:$1|izmaiņa|izmaiņas}}', 'usercreated' => '{{GENDER:$3|Izveidoja}} $1 plkst. $2', 'newpages' => 'Jaunas lapas', 'newpages-username' => 'Lietotājs:', 'ancientpages' => 'Vecākās lapas', 'move' => 'Pārvietot', 'movethispage' => 'Pārvietot šo lapu', 'unusedcategoriestext' => 'Šīs kategorijas eksistē, tomēr nevienā rakstā vai kategorijās tās nav izmantotas.', 'notargettitle' => 'Bez mērķa', 'nopagetitle' => 'Nav tādas mērķa lapas', 'nopagetext' => 'Mērķa lapa, ko Jūs norādījāt, nepastāv.', 'pager-newer-n' => '{{PLURAL:$1|1 jaunāku|$1 jaunākas}}', 'pager-older-n' => '{{PLURAL:$1|1 vecāku|$1 vecākas}}', 'querypage-disabled' => 'Šī īpašā lapā ir atspējota veiktspējas iemeslu dēļ.', # Book sources 'booksources' => 'Grāmatu avoti', 'booksources-search-legend' => 'Meklēt grāmatu avotus', 'booksources-go' => 'Meklēt', # Special:Log 'specialloguserlabel' => 'Izpildītājs:', 'speciallogtitlelabel' => 'Mērķis (nosaukums vai lietotājs):', 'log' => 'Reģistri', 'all-logs-page' => 'Visi publiski pieejamie reģistri', 'alllogstext' => 'Visi pieejamie {{grammar:akuzatīvs{{SITENAME}}}} reģistri. Tu vari sašaurināt aplūkojamo reģistru, izvēloties reģistra veidu, lietotāja vārdu vai reģistrēto lapu. Visi teksta lauki izšķir lielos un mazos burtus.', 'logempty' => 'Reģistrā nav atbilstošu ierakstu.', 'log-title-wildcard' => 'Meklēt virsrakstus, kas sākas ar šo tekstu', # Special:AllPages 'allpages' => 'Visas lapas', 'alphaindexline' => 'no $1 līdz $2', 'nextpage' => 'Nākamā lapa ($1)', 'prevpage' => 'Iepriekšējā lapa ($1)', 'allpagesfrom' => 'Parādīt lapas sākot ar:', 'allpagesto' => 'Parādīt lapas līdz:', 'allarticles' => 'Visi raksti', 'allinnamespace' => 'Visas lapas ($1 vārdtelpa)', 'allnotinnamespace' => 'Visas lapas (nav $1 vārdtelpa)', 'allpagesprev' => 'Iepriekšējās', 'allpagesnext' => 'Nākamās', 'allpagessubmit' => 'Aiziet!', 'allpagesprefix' => 'Parādīt lapas ar šādu virsraksta sākumu:', 'allpages-bad-ns' => '{{SITENAME}} nav vārdkopas "$1".', # Special:Categories 'categories' => 'Kategorijas', 'categoriespagetext' => "{{PLURAL:$1|Šī kategorija|Šīs kategorijas}} satur lapas vai failus. Šeit nav parādītas [[Special:UnusedCategories|neizmantotās kategorijas]]. Skatīt arī [[Special:WantedCategories|''sarkanās'' kategorijas]].", 'categoriesfrom' => 'Parādīt kategorijas sākot ar:', 'special-categories-sort-count' => 'kārtot pēc skaita', 'special-categories-sort-abc' => 'kārtot alfabētiskā secībā', # Special:DeletedContributions 'deletedcontributions' => 'Izdzēstais lietotāju devums', 'deletedcontributions-title' => 'Izdzēstais lietotāju devums', 'sp-deletedcontributions-contribs' => 'devums', # Special:LinkSearch 'linksearch' => 'Ārējo saišu meklēšana', 'linksearch-pat' => 'Meklēt:', 'linksearch-ns' => 'Vārdtelpas:', 'linksearch-ok' => 'Meklēt', 'linksearch-text' => 'Atbalstītie protokoli: <code>$1</code>', 'linksearch-line' => '$1 ir izveidota saite no $2', # Special:ListUsers 'listusersfrom' => 'Parādīt lietotājus sākot ar:', 'listusers-submit' => 'Parādīt', 'listusers-noresult' => 'Neviens lietotājs nav atrasts.', 'listusers-blocked' => '(bloķēts)', # Special:ActiveUsers 'activeusers' => 'Aktīvo lietotāju saraksts', 'activeusers-intro' => 'Šis ir lietotāju saraksts, kas veikuši kādu darbību {{PLURAL:daudzskaitlī:$1|pēdējā|pēdējās}} $1 {{PLURAL:daudzskaitlī:$1|dienā|dienās}}.', 'activeusers-from' => 'Parādīt lietotājus sākot ar:', 'activeusers-hidebots' => 'Paslēpt botus', 'activeusers-hidesysops' => 'Paslēpt administratorus', 'activeusers-noresult' => 'Neviens lietotājs nav atrasts.', # Special:Log/newusers 'newuserlogpage' => 'Jauno lietotāju reģistrs', 'newuserlogpagetext' => 'Jauno lietotājvārdu reģistrs.', # Special:ListGroupRights 'listgrouprights' => 'Lietotāju grupu tiesības', 'listgrouprights-summary' => 'Šis ir šajā wiki definēto lietotāju grupu uskaitījums, kopā ar tām atbilstošajām piekļuves tiesībām. Papildu informāciju par katru individuālu piekļuves tiesību veidu, iespējams, var atrast [[{{MediaWiki:Listgrouprights-helppage}}|šeit]].', 'listgrouprights-group' => 'Grupa', 'listgrouprights-rights' => 'Tiesības', 'listgrouprights-helppage' => 'Help:Grupu tiesības', 'listgrouprights-members' => '(dalībnieku saraksts)', 'listgrouprights-addgroup' => 'Pievienot {{PLURAL:$2|grupu|grupas}}: $1', 'listgrouprights-removegroup' => 'Noņemt {{PLURAL:$2|grupu|grupas}}: $1', 'listgrouprights-addgroup-all' => 'Pievienot visas grupas', 'listgrouprights-removegroup-all' => 'Noņemt visas grupas', 'listgrouprights-addgroup-self-all' => 'Pievienot visas grupas savam kontam', 'listgrouprights-removegroup-self-all' => 'Noņemt visas grupas no sava konta', # Email user 'mailnologin' => 'Nav adreses, uz kuru sūtīt', 'mailnologintext' => 'Tev jābūt [[Special:UserLogin|iegājušam]], kā arī tev jābūt [[Special:Preferences|norādītai]] derīgai e-pasta adresei, lai sūtītu e-pastu citiem lietotājiem.', 'emailuser' => 'Sūtīt e-pastu šim lietotājam', 'emailpage' => 'Sūtīt e-pastu lietotājam', 'emailpagetext' => 'Ar šo veidni ir iespējams nosūtīt e-pastu šim lietotājam. Tā e-pasta adrese, kuru tu esi norādījis [[Special:Preferences|savā izvēļu lapā]], parādīsies e-pasta "From" lauciņā, tādejādi saņēmējs varēs tev atbildēt.', 'usermailererror' => 'Pasta objekts atgrieza kļūdu:', 'defemailsubject' => '{{SITENAME}} e-pasts no lietotāja "$1"', 'usermaildisabled' => 'Lietotāja e-pasts atslēgts', 'usermaildisabledtext' => 'Jūs nevarat sūtīt e-pastu citiem lietotājiem šajā viki', 'noemailtitle' => 'Nav e-pasta adreses', 'noemailtext' => 'Šis lietotājs nav norādījis derīgu e-pasta adresi.', 'nowikiemailtitle' => 'E-pasts nav atļauts', 'nowikiemailtext' => 'Šis lietotājs ir vēlējies nesaņemt e-pastu no citiem lietotājiem.', 'emailnotarget' => 'Neeksistējošs vai nederīgs saņēmēja lietotājvārds.', 'emailtarget' => 'Ievadiet saņēmēja lietotājvārdu', 'emailusername' => 'Lietotājvārds:', 'emailusernamesubmit' => 'Iesniegt', 'email-legend' => 'Sūtīt e-pastu citam {{SITENAME}} lietotājam', 'emailfrom' => 'No:', 'emailto' => 'Kam:', 'emailsubject' => 'Temats:', 'emailmessage' => 'Vēstījums:', 'emailsend' => 'Nosūtīt', 'emailccme' => 'Atsūtīt man uz e-pastu mana ziņojuma kopiju.', 'emailsent' => 'E-pasts nosūtīts', 'emailsenttext' => 'Tavs e-pasts ir nosūtīts.', 'emailuserfooter' => 'Šis e-pasts ir lietotāja $1 sūtīts lietotājam $2, izmantojot "Sūtīt e-pastu šim lietotājam" funkciju {{SITENAME}}.', # User Messenger 'usermessage-summary' => 'Atstāt sistēmas ziņojumu.', 'usermessage-editor' => 'Sistēmas ziņotājs', # Watchlist 'watchlist' => 'Mani uzraugāmie raksti', 'mywatchlist' => 'Uzraugāmie raksti', 'watchlistfor2' => 'Priekš $1 ($2)', 'nowatchlist' => 'Tavā uzraugāmo rakstu sarakstā nav neviena raksta.', 'watchlistanontext' => 'Lūdzu $1, lai apskatītu vai labotu savu uzraugāmo rakstu saraksta saturu.', 'watchnologin' => 'Neesi iegājis', 'watchnologintext' => 'Tev ir [[Special:UserLogin|jāieiet]], lai mainītu uzraugāmo lapu sarakstu.', 'addwatch' => 'Pievienot uzraugāmo lapu sarakstam', 'addedwatchtext' => "Lapa \"[[:\$1]]\" ir pievienota [[Special:Watchlist|tevis uzraudzītajām lapām]], kur tiks parādītas izmaiņas, kas izdarītas šajā lapā vai šīs lapas diskusiju lapā, kā arī šī lapa tiks iezīmēta '''pustrekna''' [[Special:RecentChanges|pēdējo izmaiņu lapā]], lai to būtu vieglāk pamanīt. Ja vēlāk pārdomāsi un nevēlēsies vairs uzraudzīt šo lapu, klikšķini uz saites '''neuzraudzīt''' rīku joslā.", 'removewatch' => 'Izņemt no uzraugāmo lapu saraksta', 'removedwatchtext' => 'Lapa "[[:$1]]" ir izņemta no tava [[Special:Watchlist|uzraugāmo lapu saraksta]].', 'watch' => 'Uzraudzīt', 'watchthispage' => 'Uzraudzīt šo lapu', 'unwatch' => 'Neuzraudzīt', 'unwatchthispage' => 'Pārtraukt uzraudzīšanu', 'notanarticle' => 'Nav satura lapa', 'notvisiblerev' => 'Cita lietotāja pēdējā versija ir izdzēsta', 'watchnochange' => 'Neviena no tevis uzraudzītajām lapām nav mainīta parādītajā laika posmā.', 'watchlist-details' => '(Tu uzraugi $1 {{PLURAL:$1|lapu|lapas}}, neieskaitot diskusiju lapas.)', 'wlheader-enotif' => 'E-pasta paziņojumi ir ieslēgti.', 'wlheader-showupdated' => "* Lapas, kuras ir tikušas izmainītas, kopš tu tās pēdējoreiz apskatījies, te rādās ar '''pustrekniem''' burtiem", 'watchlistcontains' => 'Tavā uzraugāmo lapu sarakstā ir $1 {{PLURAL:$1|lapa|lapas}}.', 'iteminvalidname' => "Problēma ar '$1' vienību, nederīgs nosaukums...", 'wlshowlast' => 'Parādīt izmaiņas pēdējo $1 stundu laikā vai $2 dienu laikā, vai arī $3.', 'watchlist-options' => 'Uzraugāmo rakstu saraksta opcijas', # Displayed when you click the "watch" button and it is in the process of watching 'watching' => 'Uzrauga...', 'unwatching' => 'Neuzrauga...', 'enotif_mailer' => '{{SITENAME}} paziņojumu izsūtīšana', 'enotif_reset' => 'Atzīmēt visas lapas kā apskatītas', 'enotif_newpagetext' => 'Šī ir jauna lapa.', 'enotif_impersonal_salutation' => '{{SITENAME}} lietotājs', 'changed' => 'izmainīja', 'created' => 'izveidoja', 'enotif_subject' => '{{grammar:ģenitīvs|{{SITENAME}}}} lapu $PAGETITLE $CHANGEDORCREATED lietotājs $PAGEEDITOR', 'enotif_lastvisited' => '$1 lai apskatītos visas izmaiņas kopš tava pēdējā apmeklējuma.', 'enotif_lastdiff' => '$1 lai apskatītos šo izmaiņu.', 'enotif_anon_editor' => 'anonīms lietotājs $1', 'enotif_body' => '$WATCHINGUSERNAME, {{grammar:ģenitīvs|{{SITENAME}}}} lapu $PAGETITLE $CHANGEDORCREATED $PAGEEDITOR, $PAGEEDITDATE, pašreizējā versja ir $PAGETITLE_URL. $NEWPAGE Izmaiņu kopsavilkums bija: $PAGESUMMARY $PAGEMINOREDIT Sazināties ar attiecīgo lietotāju: e-pasts: $PAGEEDITOR_EMAIL wiki: $PAGEEDITOR_WIKI Ja šo uzraugāmo lapu izmainīs vēl, turpmāku paziņojumu par to nebūs, kamēr tu to neatvērsi. Tu arī vari atstatīt visu uzraugāmo lapu paziņojumu statusus uzraugāmo lapu sarakstā. {{grammar:ģenitīvs|{{SITENAME}}}} paziņojumu sistēma -- Lai izmainītu uzraugāmo lapu saraksta uzstādījumus: {{canonicalurl:{{#special:EditWatchlist}}}} Lai dzēstu lapu no uzraugāmo lapu saraksta: $UNWATCHURL Papildinformācija: {{canonicalurl:{{MediaWiki:Helppage}}}}', # Delete 'deletepage' => 'Dzēst lapu', 'confirm' => 'Apstiprināt', 'excontent' => "lapas saturs bija: '$1'", 'excontentauthor' => 'saturs bija: "$1" (vienīgais autors: [[Special:Contributions/$2|$2]])', 'exbeforeblank' => "lapas saturs pirms satura dzēšanas bija šāds: '$1'", 'exblank' => 'lapa bija tukša', 'delete-confirm' => 'Dzēst "$1"', 'delete-legend' => 'Dzēšana', 'historywarning' => "'''Brīdinājums:''' Lapai, ko tu gatavojies dzēst, ir vēsture ar aptuveni $1 {{PLURAL:$1|versiju|versijām}}:", 'confirmdeletetext' => 'Tu tūlīt no datubāzes dzēsīsi lapu vai attēlu, kā arī to iepriekšējās versijas. Lūdzu, apstiprini, ka tu tiešām to vēlies darīt, ka tu apzinies sekas un ka tu to dari saskaņā ar [[{{MediaWiki:Policy-url}}|vadlīnijām]].', 'actioncomplete' => 'Darbība pabeigta', 'actionfailed' => 'Darbība neizdevās', 'deletedtext' => 'Lapa "$1" ir izdzēsta. Šeit var apskatīties pēdējos izdzēstos: "$2".', 'dellogpage' => 'Dzēšanas reģistrs', 'dellogpagetext' => 'Šajā lapā ir pēdējo dzēsto lapu saraksts.', 'deletionlog' => 'dzēšanas reģistrs', 'reverted' => 'Atjaunots uz iepriekšējo versiju', 'deletecomment' => 'Iemesls:', 'deleteotherreason' => 'Cits/papildu iemesls:', 'deletereasonotherlist' => 'Cits iemesls', 'deletereason-dropdown' => '*Izplatīti dzēšanas iemesli ** Autora pieprsījums ** Autortiesību pārkāpums ** Vandālisms', 'delete-edit-reasonlist' => 'Izmainīt dzēšanas iemeslus', 'delete-toobig' => 'Šai lapai ir liela izmaiņu hronoloģija, vairāk nekā $1 {{PLURAL:$1|versija|versijas}}. Šādu lapu dzēšana ir atslēgta, lai novērstu nejaušus traucējumus {{grammar:lokatīvs|{{SITENAME}}}}.', # Rollback 'rollback' => 'Novērst labojumus', 'rollback_short' => 'Novērst', 'rollbacklink' => 'novērst', 'rollbackfailed' => 'Novēršana neizdevās', 'cantrollback' => 'Nav iespējams novērst labojumu; iepriekšējais labotājs ir vienīgais lapas autors.', 'alreadyrolled' => 'Nav iespējams novērst pēdējās izmaiņas, ko lapā [[:$1]] saglabāja [[User:$2|$2]] ([[User talk:$2|Diskusija]]{{int:pipe-separator}}[[Special:Contributions/$2|{{int:contribslink}}]]). Kāds cits jau ir rediģējis šo lapu vai novērsis izmaiņas. Pēdējās izmaiņas saglabāja [[User:$3|$3]] ([[User talk:$3|diskusija]]{{int:pipe-separator}}[[Special:Contributions/$3|{{int:contribslink}}]]).', 'editcomment' => "Attiecīgās izmaiņas kopsavilkums bija: \"''\$1''\".", 'revertpage' => 'Novērsu izmaiņas, ko izdarīja [[Special:Contributions/$2|$2]] ([[User talk:$2|Diskusija]]), atjaunoju versiju, ko saglabāja [[User:$1|$1]]', 'revertpage-nouser' => 'Novērsu (lietotājvārds slēpts) izmaiņas, atjaunoju [[User:$1|$1]] versiju.', 'rollback-success' => 'Tika novērstas $1 izdarītās izmaiņas; un tika atjaunota iepriekšējā versija, kuru bija izveidojis $2.', # Edit tokens 'sessionfailure-title' => 'sesijas kļūda', 'sessionfailure' => "Ir radusies problēma ar sesijas autentifikāciju; šī darbība ir atcelta, lai novērstu lietotājvārda iespējami ļaunprātīgu izmantošanu. Lūdzu, spied \"''back''\" un atjaunini iepriekšējo lapu. Tad mēģini vēlreiz.", # Protect 'protectlogpage' => 'Aizsargāšanas reģistrs', 'protectedarticle' => 'aizsargāja "[[$1]]"', 'modifiedarticleprotection' => 'izmainīja aizsardzības līmeni "[[$1]]"', 'unprotectedarticle' => 'atcēla "[[$1]]" aizsardzību', 'movedarticleprotection' => 'pārcēla aizsardzību no "[[$2]]" uz "[[$1]]"', 'protect-title' => 'Izmainīt "$1" aizsargāšanas līmeni?', 'protect-title-notallowed' => 'Apskatīt "$1" aizsrdzības līmeni', 'prot_1movedto2' => '"[[$1]]" pārdēvēju par "[[$2]]"', 'protect-legend' => 'Apstiprināt aizsargāšanu', 'protectcomment' => 'Iemesls:', 'protectexpiry' => 'Beidzas:', 'protect_expiry_invalid' => 'Beigu termiņš ir nederīgs.', 'protect_expiry_old' => 'Beigu termiņs ir pagātnē.', 'protect-text' => "Šeit var apskatīties un izmainīt lapas '''$1''' aizsardzības līmeni.", 'protect-locked-access' => "Jūsu kontam nav atļaujas mainīt lapas aizsardzības pakāpi. Pašreizējie lapas '''$1''' iestatījumi ir:", 'protect-cascadeon' => 'Šī lapa pašlaik ir aizsargāta, jo tā ir iekļauta {{PLURAL:$1|sekojošā lapā|sekojošās lapās}} (mainot šīs lapas aizsardzības līmeni aizsardzība netiks noņemta):', 'protect-default' => 'Atļaut visiem lietotājiem', 'protect-fallback' => 'Nepieciešama atļauja "$1"', 'protect-level-autoconfirmed' => 'Bloķēt jauniem un nereģistrētiem lietotājiem', 'protect-level-sysop' => 'Tikai administratoriem', 'protect-summary-cascade' => 'kaskāde', 'protect-expiring' => 'līdz $1 (UTC)', 'protect-expiring-local' => 'beidzas $1', 'protect-expiry-indefinite' => 'bezgalīgs', 'protect-cascade' => "Aizsargāt šajā lapā iekļautās lapas (veidnes) ''(cascading protection)''", 'protect-cantedit' => 'Tu nevari izmainīt šīs lapas aizsardzības līmeņus, tāpēc, ka tur nevari izmainīt šo lapu.', 'protect-othertime' => 'Cits laiks:', 'protect-othertime-op' => 'cits laiks', 'protect-existing-expiry' => 'Esošais beigu termiņš: $3, $2', 'protect-otherreason' => 'Cits/papildu iemesls:', 'protect-otherreason-op' => 'Cits iemesls', 'protect-dropdown' => '*Izplatīti aizsargāšanas iemesli ** Pārmērīgs vandālisms ** Pārmērīgs spams ** Neproduktīvi izmaiņu kari ** Bieži apskatīta lapa', 'protect-edit-reasonlist' => 'Izmainīt aizsargāšanas iemeslus', 'protect-expiry-options' => '1 stunda:1 hour,1 diena:1 day,1 nedēļa:1 week,2 nedēļas:2 weeks,1 mēnesis:1 month,3 mēneši:3 months,6 mēneši:6 months,1 gads:1 year,uz nenoteiktu laiku:infinite', 'restriction-type' => 'Atļauja:', 'restriction-level' => 'Aizsardzības līmenis:', 'minimum-size' => 'Mazākais izmērs', 'maximum-size' => 'Lielākais izmērs:', 'pagesize' => '(baiti)', # Restrictions (nouns) 'restriction-edit' => 'Izmainīt', 'restriction-move' => 'Pārvietot', 'restriction-create' => 'Izveidot', 'restriction-upload' => 'Augšuplādēt', # Restriction levels 'restriction-level-sysop' => 'pilnā aizsardzība', 'restriction-level-autoconfirmed' => 'daļējā aizsardzība', 'restriction-level-all' => 'jebkurš līmenis', # Undelete 'undelete' => 'Atjaunot dzēstu lapu', 'undeletepage' => 'Skatīt un atjaunot dzēstās lapas', 'undeletepagetitle' => "'''Šeit ir [[:$1|$1]] izdzēstās versijas'''.", 'viewdeletedpage' => 'Skatīt izdzēstās lapas', 'undeletepagetext' => '{{PLURAL:$1|Šī lapa ir dzēsta, bet ir saglabāta arhīvā. To ir iespējams atjaunot|Šīs $1 lapas ir dzēstas, bet ir saglabātas arhīvā. Tās ir iespējams atjaunot}}, bet ņemiet vērā, ka arhīvs reizēm tiek tīrīts.', 'undelete-fieldset-title' => 'Atjaunot versijas', 'undeleteextrahelp' => "Lai atjaunotu visu lapu, atstāj visus ķekšus (pie \"Lapas hronoloģija\") neieķeksētus uz uzspied uz '''''Atjaunot!'''''. Lai atjaunotu tikai noteiktas versijas, ieķeksē vajadzīgās versijas un spied uz '''''Atjaunot!'''''. Uzspiešana uz '''''Notīrīt''''' notīrīs komentāru lauku un visus keķšus.", 'undeleterevisions' => '$1 {{PLURAL:$1|versija|versijas}} {{PLURAL:$1|arhivēta|arhivētas}}', 'undeletehistory' => 'Ja tu atjauno lapu, visas versijas tiks atjaunotas tās hronoloģijā. Ja pēc dzēšanas ir izveidota jauna lapa ar tādu pašu nosaukumu, atjaunotās versijas tiks ievietotas lapas hronoloģijā attiecīgā secībā un konkrētās lapas pašreizējā versija netiks automātiski nomainīta.', 'undeleterevdel' => 'Atjaunošana nenotiks, ja tas izraisīs jaunākās versijas izdzēšanu. Šādos gadījumos ir vai nu jāizņem ķeksis no jaunākās versijas, vai arī jāatslēpj jaunākā versija.', 'undeletehistorynoadmin' => 'Šī lapa ir tikusi izdzēsta. Dzēšanas iemesls ir redzams apakšā, kopsavilkumā, kopā ar informāciju par lietotājiem, kas bija rediģējuši šo lapu pirs tās izdzēšanas. Šo izdzēsto versiju teksts ir pieejams tikai administratoriem.', 'undelete-revision' => 'Lapas $1 izdzēstā versija (kāda tā bija $4, $5) (autors $3):', 'undeleterevision-missing' => 'Nederīga vai neeksistējoša versija. Vai nu tu šeit esi nonācis lietojot kļūdainu saiti, vai arī šī versija jau ir tikusi atjaunota, vai arī tā ir izdzēsta pavisam.', 'undelete-nodiff' => 'Netika atrastas iepriekšējās versijas.', 'undeletebtn' => 'Atjaunot!', 'undeletelink' => 'apskatīt/atjaunot', 'undeleteviewlink' => 'skatīt', 'undeletereset' => 'Notīrīt', 'undeleteinvert' => 'Izvēlēties pretēji', 'undeletecomment' => 'Iemesls:', 'undeletedrevisions' => '$1 {{PLURAL:$1|versija|versijas}} {{PLURAL:$1|atjaunota|atjaunotas}}', 'undeletedrevisions-files' => '{{PLURAL:$1|1 versija|$1 versijas}} un {{PLURAL:$2|1 fails|$2 faili}} atjaunoti', 'undeletedfiles' => '{{PLURAL:$1|1 fails atjaunots|$1 faili atjaunoti}}', 'cannotundelete' => 'Atjaunošana neizdevās; kāds cits iespējams to ir atjaunojis ātrāk.', 'undeletedpage' => "'''$1 tika atjaunots''' [[Special:Log/delete|Dzēšanas reģistrā]] ir informācija par pēdējām dzēšanām un atjaunošanām.", 'undelete-header' => 'Nesen dzēstajām lapām skatīt [[Special:Log/delete|dzēšanas reģistru]].', 'undelete-search-title' => 'Meklēt izdzēstās lapas', 'undelete-search-box' => 'Meklēt izdzēstās lapas', 'undelete-search-prefix' => 'Rādīt lapas sākot ar:', 'undelete-search-submit' => 'Meklēt', 'undelete-no-results' => 'Dzēšanas arhīvā netika atrasta neviena atbilstoša lapa.', 'undelete-cleanup-error' => 'Kļūda dzēšot neizmantotu arhīva failu "$1".', 'undelete-error-short' => 'Kļūda dzēšot failu: $1', 'undelete-error-long' => 'Dzēšot failu radās kļūdas: $1', 'undelete-show-file-submit' => 'Jā', # Namespace form on various pages 'namespace' => 'Vārdtelpa:', 'invert' => 'Izvēlēties pretēji', 'blanknamespace' => '(Pamatlapa)', # Contributions 'contributions' => 'Lietotāja devums', 'contributions-title' => 'Lietotāja $1 devums', 'mycontris' => 'Devums', 'contribsub2' => 'Lietotājs: $1 ($2)', 'nocontribs' => 'Netika atrastas izmaiņas, kas atbilstu šiem kritērijiem.', 'uctop' => '(pēdējā izmaiņa)', 'month' => 'No mēneša (un senāki):', 'year' => 'No gada (un senāki):', 'sp-contributions-newbies' => 'Rādīt jauno lietotāju devumu', 'sp-contributions-newbies-sub' => 'Jaunie lietotāji', 'sp-contributions-blocklog' => 'Bloķēšanas reģistrs', 'sp-contributions-deleted' => 'Izdzēstais lietotāju devums', 'sp-contributions-uploads' => 'augšupielādes', 'sp-contributions-logs' => 'reģistri', 'sp-contributions-talk' => 'diskusija', 'sp-contributions-userrights' => 'Lietotāju tiesību pārvaldība', 'sp-contributions-blocked-notice' => 'Šis lietotājs pašlaik ir nobloķēts. Pēdējais bloķēšanas reģistra ieraksts ir apskatāms zemāk:', 'sp-contributions-blocked-notice-anon' => 'Šī IP adrese pašlaik ir nobloķēta. Pēdējais bloķēšanas reģistra ieraksts ir apskatāms zemāk:', 'sp-contributions-search' => 'Meklēt lietotāju veiktās izmaiņas', 'sp-contributions-username' => 'IP adrese vai lietotāja vārds:', 'sp-contributions-toponly' => 'Rādīt tikai labojumus, kuri ir jaunākās versijas', 'sp-contributions-submit' => 'Meklēt', # What links here 'whatlinkshere' => 'Norādes uz šo rakstu', 'whatlinkshere-title' => 'Lapas, kurās ir saites uz lapu "$1"', 'whatlinkshere-page' => 'Lapa:', 'linkshere' => "Šajās lapās ir norādes uz lapu '''[[:$1]]''':", 'nolinkshere' => "Nevienā lapā nav norāžu uz lapu '''[[:$1]]'''.", 'nolinkshere-ns' => "Neviena lapa nenorāda uz '''[[:$1]]''' izvēlētajā vārdtelpā.", 'isredirect' => 'pāradresācijas lapa', 'istemplate' => 'izsaukts', 'isimage' => 'faila saite', 'whatlinkshere-prev' => '{{PLURAL:$1|iepriekšējo|iepriekšējos $1}}', 'whatlinkshere-next' => '{{PLURAL:$1|nākamo|nākamos $1}}', 'whatlinkshere-links' => '← saites', 'whatlinkshere-hideredirs' => '$1 pāradresācijas', 'whatlinkshere-hidetrans' => '$1 lapas, kurās šī lapa izmantota kā veidne', 'whatlinkshere-hidelinks' => '$1 saites', 'whatlinkshere-hideimages' => '$1 failu saites', 'whatlinkshere-filters' => 'Filtri', # Block/unblock 'autoblockid' => 'Autobloķēšana #$1', 'block' => 'Bloķēt lietotāju', 'unblock' => 'Atbloķēt lietotāju', 'blockip' => 'Bloķēt lietotāju', 'blockip-title' => 'Bloķēt lietotāju', 'blockip-legend' => 'Bloķēt lietotāju', 'blockiptext' => 'Šo veidni izmanto, lai bloķētu kādas IP adreses vai lietotājvārda piekļuvi wiki lapu saglabāšanai. Dari to tikai, lai novērstu vandālismu atbilstoši [[{{MediaWiki:Policy-url}}|noteikumiem]]. Norādi konkrētu iemeslu (piemēram, linkus uz vandalizētajām lapām).', 'ipadressorusername' => 'IP adrese vai lietotājvārds', 'ipbexpiry' => 'Termiņš', 'ipbreason' => 'Iemesls:', 'ipbreasonotherlist' => 'Cits iemesls', 'ipbreason-dropdown' => '*Biežākie bloķēšanas iemesli ** Ievieto nepatiesu informāciju ** Dzēš lapu saturu ** Spamo ārējās saitēs ** Ievieto nesakarīgus simbolus sakopojumus ** Nepieņemama uzvedība un apvainojumi ** Vairāku kontu ļaunprātīga izmantošana ** Nepieņemams lietotājvārds', 'ipbcreateaccount' => 'Neļaut izveidot lietotājvārdu', 'ipbemailban' => 'Neļaut lietotājam sūtīt e-pastu', 'ipbenableautoblock' => 'Automātiski bloķēt lietotāja pēdējo IP adresi un jebkuru IP adresi, no kuras šis lietotājs piekļūst šim wiki', 'ipbsubmit' => 'Bloķēt šo lietotāju', 'ipbother' => 'Cits laiks', 'ipboptions' => '2 stundas:2 hours,1 diena:1 day,3 dienas:3 days,1 nedēļa:1 week,2 nedēļas:2 weeks,1 mēnesis:1 month,3 mēneši:3 months,6 mēneši:6 months,1 gads:1 year,uz nenoteiktu laiku:infinite', 'ipbotheroption' => 'cits', 'ipbotherreason' => 'Cits/papildu iemesls:', 'ipbhidename' => "Slēpt lietot'javārdu no labojumiem un sarakstiem", 'ipbwatchuser' => 'Uzraudzīt šī lietotāja lietotāja un lietotāja diskusijas lapas', 'ipb-change-block' => 'Pārbloķēt ar šiem uzstādījumiem', 'ipb-confirm' => 'Apstiprināt bloķēšanu', 'badipaddress' => 'Nederīga IP adrese', 'blockipsuccesssub' => 'Nobloķēts veiksmīgi', 'blockipsuccesstext' => '[[Special:Contributions/$1|$1]] tika nobloķēts.<br /> Visus blokus var apskatīties [[Special:BlockList|IP bloku sarakstā]].', 'ipb-edit-dropdown' => 'Izmainīt bloķēšanas iemeslus', 'ipb-unblock-addr' => 'Atbloķēt $1', 'ipb-unblock' => 'Atbloķēt lietotāju vai IP adresi', 'ipb-blocklist' => 'Apskatīties esošos blokus', 'ipb-blocklist-contribs' => '$1 devums', 'unblockip' => 'Atbloķēt lietotāju', 'unblockiptext' => 'Šeit var atbloķēt iepriekš nobloķētu IP adresi vai lietotāja vārdu (atjaunot viņiem rakstīšanas piekļuvi).', 'ipusubmit' => 'Noņemt šo bloku', 'unblocked' => '[[User:$1|$1]] tika atbloķēts', 'unblocked-range' => '$1 tika atbloķēts', 'unblocked-id' => 'Bloks $1 tika noņemts', 'blocklist' => 'Bloķētie lietotāji', 'ipblocklist' => 'Bloķētie lietotāji', 'ipblocklist-legend' => 'Meklēt bloķētu lietotāju', 'blocklist-userblocks' => 'Paslēpt kontu bloķējumus', 'blocklist-tempblocks' => 'Paslēpt pagaidu bloķējumus', 'blocklist-addressblocks' => 'Paslēpt vienas IP adreses bloķējumus', 'blocklist-timestamp' => 'Laiks', 'blocklist-target' => 'Mērķis', 'blocklist-params' => 'Bloķēšanas parametri', 'blocklist-reason' => 'Iemesls', 'ipblocklist-submit' => 'Meklēt', 'ipblocklist-localblock' => 'Vietējais bloks', 'ipblocklist-otherblocks' => ' {{PLURAL:$1|Cita|Citas}} {{PLURAL:$1|bloķēšana|bloķēšanas}}', 'infiniteblock' => 'bezgalīgs', 'expiringblock' => 'beidzas $1 $2', 'anononlyblock' => 'tikai anon.', 'noautoblockblock' => 'automātiskā bloķēšana atslēgta', 'createaccountblock' => 'kontu veidošana atslēgta', 'emailblock' => 'e-pasts bloķēts', 'blocklist-nousertalk' => 'nevar izmainīt savu diskusiju lapu', 'ipblocklist-empty' => 'Bloķēšanas saraksts ir tukšs.', 'ipblocklist-no-results' => 'Norādītā IP adrese vai lietotājs nav bloķēts.', 'blocklink' => 'bloķēt', 'unblocklink' => 'atbloķēt', 'change-blocklink' => 'izmainīt bloku', 'contribslink' => 'devums', 'emaillink' => 'nosūtīt e-pastu', 'autoblocker' => 'Tava IP ir nobloķēta automātiski, tāpēc, ka to nesen lietojis "[[User:$1|$1]]". Viņa bloķēšanas iemesls bija: "$2"', 'blocklogpage' => 'Bloķēšanas reģistrs', 'blocklog-showlog' => 'Šis lietotājs ir bijis bloķēts jau agrāk. Te apakšā var apskatīties bloķēšanas reģistru:', 'blocklogentry' => 'nobloķēja [[$1]] uz $2 $3', 'reblock-logentry' => 'izmainīja bloķēšanas iestatījumus [[$1]] ar beigu termiņu $2 $3', 'blocklogtext' => 'Šajā lapā ir pēdējo nobloķēto un atbloķēto lietotāju saraksts. Te neparādās automātiski nobloķētās IP adreses. Šobrīd aktīvos blokus var apskatīties bloķēto lietotāju [[Special:BlockList|IP adrešu sarakstā]].', 'unblocklogentry' => 'atbloķēja $1', 'block-log-flags-anononly' => 'tikai anonīmiem lietotājiem', 'block-log-flags-nocreate' => 'kontu veidošana atslēgta', 'block-log-flags-noautoblock' => 'automātiskā bloķēšana atslēgta', 'block-log-flags-noemail' => 'e-pasts bloķēts', 'block-log-flags-nousertalk' => 'nevar izmainīt savu diskusiju lapu', 'block-log-flags-hiddenname' => 'lietotājvārds slēpts', 'ipb_expiry_invalid' => 'Nederīgs beigu termiņš', 'ipb_expiry_temp' => 'Slēpto lietotājvārdu bloķēšanai jābūt beztermiņa.', 'ipb_already_blocked' => '"$1" jau ir bloķēts', 'ipb-needreblock' => '$1 jau ir bloķēts. Vai tu gribi izmainīt bloka uzstādījumus?', 'ipb-otherblocks-header' => '{{PLURAL:$1|Cits bloks|Citi bloki}}', 'unblock-hideuser' => 'Šo lietotāju nevar atbloķēt, jo tā lietotājvārds ir paslēpts.', 'ipb_cant_unblock' => 'Kļūda: Bloka ID $1 nav atrasts. Tas, iespējams, jau ir atbloķēts.', 'ipb_blocked_as_range' => 'Kļūda: IP $1 nav bloķēta tieši, tāpēc to nevar atbloķēt. Tā ir bloķēta kā daļa no IP adrešu diapazona $2, kuru var atbloķēt.', 'ip_range_invalid' => 'Nederīgs IP diapazons', 'blockme' => 'Bloķēt mani', 'proxyblocker' => 'Starpniekservera bloķētājs', 'proxyblocker-disabled' => 'Šī funkcija ir atspējota.', 'proxyblocksuccess' => 'Darīts.', 'cant-block-while-blocked' => 'Tu nevari bloķēt citus lietotājus, kamēr pats esi bloķēts.', 'ipbblocked' => 'Tu nevar bloķēt vai atbloķēt lietotājus, jo Tu pats esi bloķēts', 'ipbnounblockself' => 'Tev nav atļauts sevi atbloķēt', # Developer tools 'lockdb' => 'Bloķēt datubāzi', 'unlockdb' => 'Atbloķēt datubāzi', 'lockconfirm' => 'Jā, es tiešām vēlos bloķēt datubāzi.', 'unlockconfirm' => 'Jā, es tiešām vēlos atbloķēt datubāzi.', 'lockbtn' => 'Bloķēt datubāzi', 'unlockbtn' => 'Atbloķēt datubāzi', 'lockdbsuccesssub' => 'Datubāzes bloķēšana pabeigta', 'unlockdbsuccesssub' => 'Datubāze atbloķēta', 'unlockdbsuccesstext' => 'Datubāze ir atbloķēta.', 'databasenotlocked' => 'Datubāzē nav bloķēta.', # Move page 'move-page' => 'Pārvietot $1', 'move-page-legend' => 'Pārvietot lapu', 'movepagetext' => "Šajā lapā tu vari pārdēvēt vai pārvietot lapu, kopā tās izmaiņu hronoloģiju pārvietojot to uz citu nosaukumu. Iepriekšējā lapa kļūs par lapu, kas pāradresēs uz jauno lapu. Šeit var automātiski izmainīt visas pāradresācijas (redirektus) uz šo lapu (2. ķeksis apakšā). Saites pārējās lapās uz iepriekšējo lapu netiks mainītas. Ja izvēlies neizmainīt pāradresācijas automātiski, noteikti pārbaudi un izlabo, izskaužot [[Special:DoubleRedirects|dubultu pāradresāciju]] vai [[Special:BrokenRedirects|pāradresāciju uz neesošu lapu]]. Tev ir jāpārliecinās, vai saites vēl aizvien ved tur, kur tās ir paredzētas. Ņem vērā, ka lapa '''netiks''' pārvietota, ja jau eksistē kāda cita lapa ar vēlamo nosaukumu (izņemot gadījumus, kad tā ir tukša vai kad tā ir pāradresācijas lapa, kā arī tad, ja tai nav izmaiņu hronoloģijas). Tas nozīmē, ka tu vari pārvietot lapu atpakaļ, no kurienes tu jau reiz to esi pārvietojis, ja būsi kļūdījies, bet tu nevari pārrakstīt jau esošu lapu. '''BRĪDINĀJUMS!''' Populārām lapām tā var būt krasa un negaidīta pārmaiņa; pirms turpināšanas vēlreiz pārdomā, vai tu izproti visas iespējamās sekas.", 'movepagetalktext' => "Saistītā diskusiju lapa, ja tāda eksistē, tiks automātiski pārvietota, '''izņemot gadījumus, kad''': *tu pārvieto lapu uz citu palīglapu, *ar jauno nosaukumu jau eksistē diskusiju lapa, vai arī *atzīmēsi zemāk atrodamo lauciņu. Ja tomēr vēlēsies, tad tev šī diskusiju lapa būs jāpārvieto vai jāapvieno pašam.", 'movearticle' => 'Pārvietot lapu', 'movenologin' => 'Neesi iegājis kā reģistrēts lietotājs', 'movenologintext' => 'Tev ir jābūt reģistrētam lietotājam un jābūt [[Special:UserLogin|iegājušam]] {{grammar:lokatīvs|{{SITENAME}}}}, lai pārvietotu lapu.', 'movenotallowed' => 'Tev nav atļaujas pārvietot lapas.', 'movenotallowedfile' => 'Tev nav atļaujas pārvietot failus.', 'cant-move-user-page' => 'Tev nav atļaujas pārvietot lietotāju lapas (neskaitot apakšlapas).', 'cant-move-to-user-page' => 'Tev nav atļaujas pārvietot lapu uz lietotāja lapu (neskaitot lietotāja lapas apakšlapu).', 'newtitle' => 'Uz šādu lapu', 'move-watch' => 'Uzraudzīt šo lapu', 'movepagebtn' => 'Pārvietot lapu', 'pagemovedsub' => 'Pārvietošana notikusi veiksmīgi', 'movepage-moved' => '\'\'\'"$1" tika pārvietots uz "$2"\'\'\'', 'movepage-moved-redirect' => 'Tika izveidota pāradresācija.', 'articleexists' => 'Lapa ar tādu nosaukumu jau pastāv vai arī tevis izvēlētais nosaukums ir nederīgs. Lūdzu, izvēlies citu nosaukumu.', 'cantmove-titleprotected' => 'Tu nevari pārvietot lapu uz šo nosaukumu, tāpēc, ka jaunais nosaukums (lapa) ir aizsargāta pret izveidošanu', 'talkexists' => "'''Šī lapa pati tika pārvietota veiksmīgi, bet tās diskusiju lapu nevarēja pārvietot, tapēc, ka jaunā nosaukuma lapai jau ir diskusiju lapa. Lūdzu apvieno šīs diskusiju lapas manuāli.'''", 'movedto' => 'pārvietota uz', 'movetalk' => 'Pārvietot arī diskusiju lapu, ja tāda ir.', 'move-subpages' => 'Pārvietot apakšlapas (līdz $1 gab.)', 'move-talk-subpages' => 'Pārvietot diskusiju lapas apakšlapas (līdz $1 gab.)', 'movepage-page-exists' => 'Lapa $1 jau eksistē un to nevar pārrakstīt automātiski.', 'movepage-page-moved' => 'Lapa $1 tika pārvietota uz $2.', 'movepage-page-unmoved' => 'Lapu $1 nevarēja pārvietot uz $2.', 'movelogpage' => 'Pārvietošanas reģistrs', 'movelogpagetext' => 'Lapu pārvietošanas (pārdēvēšanas) reģistrs.', 'movesubpage' => '{{PLURAL:$1|Apakšlapa|Apakšlapas}}', 'movesubpagetext' => 'Šai lapai ir $1 {{PLURAL:$1|apakšlapa|apakšlapas}}, kas redzamas zemāk.', 'movenosubpage' => 'Šai lapai nav apakšlapu.', 'movereason' => 'Iemesls:', 'revertmove' => 'atcelt', 'delete_and_move' => 'Dzēst un pārvietot', 'delete_and_move_text' => '==Nepieciešama dzēšana== Mērķa lapa "[[:$1]]" jau eksistē. Vai tu to gribi izdzēst, lai atbrīvotu vietu pārvietošanai?', 'delete_and_move_confirm' => 'Jā, dzēst lapu', 'delete_and_move_reason' => 'Izdzēsts, lai atbrīvotu vietu pārvietošanai no "[[$1]]"', 'selfmove' => 'Izejas un mērķa lapu nosaukumi ir vienādi; nevar pārvietot lapu uz sevi.', 'immobile-source-namespace' => 'Nevar pārvietot lapas vārdtelpā "$1"', 'immobile-target-namespace' => 'Nevar pārvietot lapas uz vārdtelpu "$1"', 'immobile-source-page' => 'Šī lapa nav pārvietojama.', 'immobile-target-page' => 'Nevar pārvietot uz mērķa nosaukumu.', 'imagenocrossnamespace' => 'Nevar pārvietot failu uz vārtelpu, kas nav paredzēta failiem.', 'nonfile-cannot-move-to-file' => 'Nevar pārvietot to, kas nav fails, uz failu vārdtelpu.', 'imagetypemismatch' => 'Jaunais faila paplašinājums neatbilst tā tipam', 'imageinvalidfilename' => 'Mērķa faila nosaukums ir nederīgs', 'fix-double-redirects' => 'Automātiski izmainīt visas pāradresācijas, kas ved uz sākotnējo nosaukumu', 'move-leave-redirect' => 'Atstāt pāradresāciju', 'protectedpagemovewarning' => "'''Brīdinājums:''' Šī lapa ir aizsargāta, tikai lietotāji ar administratora privilēģijām var to pārvietot. Pēdējais reģistra ieraksts ir apskatāms zemāk:", 'semiprotectedpagemovewarning' => "'''Piezīme:''' Šī lapa ir aizsargāta, tikai reģistrētie lietotāji var to pārvietot. Pēdējais reģistra ieraksts ir apskatāms zemāk:", 'move-over-sharedrepo' => '== Fails jau pastāv == [[:$1]] jau pastāv koplietotā repozitorijā. Pārvietošana uz šo nosaukumu aizstās koplietoto failu.', # Export 'export' => 'Eksportēt lapas', 'exporttext' => 'Šeit var eksportēt kādas noteiktas lapas vai lapu kopas tekstus un rediģēšanas hronoloģijas, XML formātā. Šādus datus pēc tam varēs ieimportēt citā MediaWiki wiki lietojot [[Special:Import|Importēt lapas]] Lai eksportētu lapas, šajā laukā ievadi to nosaukumus, katrā rindiņā pa vienam, un izvēlies vai gribi tikai pašreizējo versiju ar informāciju par pēdējo izmaiņu, vai arī pašreizējo versiju kopā ar visām vecajām versijām un hronoloģiju Pirmajā gadījumā var arī lietot šādu metodi, piem., [[{{#Special:Export}}/{{MediaWiki:Mainpage}}]] lapai "[[{{MediaWiki:Mainpage}}]]".', 'exportall' => 'Eksportēt visas lapas', 'exportcuronly' => 'Iekļaut tikai esošo versiju (bez pilnās hronoloģijas)', 'exportnohistory' => "---- '''Piezīme:''' Lapu eksportēšana kopā ar visu hronoloģiju šobrīd ir atslēgta, jo tas bremzē serveri.", 'export-submit' => 'Eksportēt', 'export-addcattext' => 'Pievienot lapas no kategorijas:', 'export-addcat' => 'Pievienot', 'export-addnstext' => 'Pievienot lapas no vārdtelpas:', 'export-addns' => 'Pievienot', 'export-download' => 'Saglabāt kā failu', 'export-templates' => 'Iekļaut veidnes', # Namespace 8 related 'allmessages' => 'Visi sistēmas paziņojumi', 'allmessagesname' => 'Nosaukums', 'allmessagesdefault' => 'Noklusētais ziņojuma teksts', 'allmessagescurrent' => 'Pašreizējais teksts', 'allmessagestext' => "Šajā lapā ir visu \"'''MediaWiki:'''\" lapās atrodamo sistēmas paziņojumu uzskaitījums. Šos paziņojumus var izmainīt tikai admini. Izmainot tos šeit, tie tiks izmainīti tikai šajā mediawiki instalācijā. Lai tos izmainītu visām pārējām, apskatieties [//www.mediawiki.org/wiki/Localisation MediaWiki Localisation] un [//translatewiki.net translatewiki.net].", 'allmessagesnotsupportedDB' => "Šī lapa nedarbojas, tāpēc, ka '''wgUseDatabaseMessages''' nedarbojas.", 'allmessages-filter-legend' => 'Filtrs', 'allmessages-filter' => 'Filtrēt pēc izmainīšanas statusa:', 'allmessages-filter-unmodified' => 'Nemodificēti', 'allmessages-filter-all' => 'Visi', 'allmessages-filter-modified' => 'Modificēti', 'allmessages-prefix' => 'Filtrēt pēc prefiksa:', 'allmessages-language' => 'Valoda:', 'allmessages-filter-submit' => 'Parādīt', # Thumbnails 'thumbnail-more' => 'Palielināt', 'filemissing' => 'Trūkst faila', 'thumbnail_error' => 'Kļūda, veidojot sīktēlu: $1', 'djvu_page_error' => 'DjVu lapa ir ārpus diapazona', 'djvu_no_xml' => 'Neizdevās ielādēt XML DjVu failam', 'thumbnail_invalid_params' => 'Nederīgi sīktēlu parametri', 'thumbnail_dest_directory' => 'Nevar izveidot mērķa direktoriju', 'thumbnail_image-type' => 'Attēla tips nav atbalstīts', 'thumbnail_gd-library' => 'Nepilnīga GD bibliotēkas konfigurācija: trūkst $1 funkcijas', 'thumbnail_image-missing' => 'Šķiet, ka fails ir pazudis: $1', # Special:Import 'import' => 'Importēt lapas', 'importinterwiki' => 'Starpviki importēšana', 'import-interwiki-source' => 'Avota viki/lapa:', 'import-interwiki-history' => 'Nokopēt visas šīs lapas hronoloģijā atrodamās versijas', 'import-interwiki-templates' => 'Iekļaut visas veidnes', 'import-interwiki-submit' => 'Importēt', 'import-interwiki-namespace' => 'Mērķa vārdtelpa:', 'import-upload-filename' => 'Faila nosaukums:', 'import-comment' => 'Komentārs:', 'importstart' => 'Importē lapas...', 'import-revision-count' => '$1 {{PLURAL:$1|versija|versijas}}', 'importnopages' => 'Nav lapu, ko importēt.', 'imported-log-entries' => '{{PLURAL:$1|Importētais|Importētie}} $1 {{PLURAL:$1|reģistra ieraksts|reģistra ieraksti}}.', 'importfailed' => 'Importēšana neizdevās: <nowiki>$1</nowiki>', 'importunknownsource' => 'Nezināms importēšanas avota veids', 'importcantopen' => 'Nevarēja atvērt importējamo failu', 'importbadinterwiki' => 'Slikta starpviki saite', 'importnotext' => 'Tukšs vai nav teksta', 'importsuccess' => 'Importēšana pabeigta!', 'importnosources' => "Tiešā hronoloģijas augšuplāde ir atslēgta. Nav definēts neviens ''Transwiki'' importa avots (''source'').", 'importnofile' => 'Neviens importējamais fails netika augšupielādēts.', 'importuploaderrorsize' => 'Augšupielādēt importējamo failu neizdevās. Šis fails ir lielāks par atļauto augšupielādes lielumu.', 'importuploaderrorpartial' => 'Importējamā faila augšupielāde neizdevās. Fails tika tikai daļēji importēts.', 'importuploaderrortemp' => 'Importētā faila augšupielāde neizdevās. Pagaidu mape ir pazudusi.', 'import-parse-failure' => 'XML importēšanas parsēšanas kļūme', 'import-noarticle' => 'Nav lapas, ko importēt.', 'import-nonewrevisions' => 'Visas versijas bija pirms tam importētas.', 'xml-error-string' => '$1 $2. rindā, $3. kolonnā ($4. baits): $5', 'import-upload' => 'Augšupielādēt XML datus', 'import-token-mismatch' => 'Zaudēti sesijas dati. Lūdzu, mēģiniet vēlreiz.', 'import-invalid-interwiki' => 'Nevar importēt no norādītās viki.', # Import log 'importlogpage' => 'Importēšanas reģistrs', 'importlogpagetext' => 'Administratīvās lapu importēšanas no citām Vikipēdijām ar lapas hronoloģiju.', 'import-logentry-upload' => 'importēts [[$1]], izmantojot failu augšupielādi', 'import-logentry-upload-detail' => '$1 {{PLURAL:$1|versija|versijas}}', 'import-logentry-interwiki' => 'starpvikizēts $1', 'import-logentry-interwiki-detail' => '$1 {{PLURAL:$1|versija|versijas}} no $2', # JavaScriptTest 'javascripttest' => 'JavaScript testēšana', 'javascripttest-title' => 'Darbina $1 testus', # Tooltip help for the actions 'tooltip-pt-userpage' => 'Tava lietotāja lapa', 'tooltip-pt-anonuserpage' => 'Manas IP adreses lietotāja lapa', 'tooltip-pt-mytalk' => 'Tava diskusiju lapa', 'tooltip-pt-anontalk' => 'Diskusija par labojumiem, kas izdarīti no šīs IP adreses', 'tooltip-pt-preferences' => 'Mani uzstādījumi', 'tooltip-pt-watchlist' => 'Manis uzraudzītās lapas.', 'tooltip-pt-mycontris' => 'Tavi ieguldījumi', 'tooltip-pt-login' => 'Aicinām tevi ieiet {{grammar:lokatīvs|{{SITENAME}}}}, tomēr tas nav obligāti.', 'tooltip-pt-anonlogin' => 'Aicinām tevi ieiet {{grammar:lokatīvs|{{SITENAME}}}}, tomēr tas nav obligāti.', 'tooltip-pt-logout' => 'Iziet', 'tooltip-ca-talk' => 'Diskusija par šī raksta lapu', 'tooltip-ca-edit' => 'Izmainīt šo lapu. Lūdzam izmantot pirmskatu pirms lapas saglabāšanas.', 'tooltip-ca-addsection' => 'Sākt jaunu sadaļu', 'tooltip-ca-viewsource' => 'Šī lapa ir aizsargāta. Tu vari apskatīties tās izejas kodu.', 'tooltip-ca-history' => 'Šīs lapas iepriekšējās versijas.', 'tooltip-ca-protect' => 'Aizsargāt šo lapu', 'tooltip-ca-unprotect' => 'Mainīt šīs lapas aizsardzību', 'tooltip-ca-delete' => 'Dzēst šo lapu', 'tooltip-ca-undelete' => 'Atjaunot labojumus, kas izdarīti šajā lapā pirms lapas dzēšanas.', 'tooltip-ca-move' => 'Pārvietot šo lapu', 'tooltip-ca-watch' => 'Pievienot šo lapu uzraugāmo lapu sarakstam', 'tooltip-ca-unwatch' => 'Izņemt šo lapu no uzraudzītajām lapām', 'tooltip-search' => 'Meklēt šajā wiki', 'tooltip-search-go' => 'Aiziet uz lapu ar precīzi šādu nosaukumu, ja tāda pastāv', 'tooltip-search-fulltext' => 'Meklēt lapās šo tekstu', 'tooltip-p-logo' => 'Sākumlapa', 'tooltip-n-mainpage' => 'Iet uz sākumlapu', 'tooltip-n-mainpage-description' => 'Šī projekta sākumlapa', 'tooltip-n-portal' => 'Par šo projektu, par to, ko tu vari šeit darīt un kur ko atrast', 'tooltip-n-currentevents' => 'Uzzini papildinformāciju par šobrīd aktuālajiem notikumiem', 'tooltip-n-recentchanges' => 'Izmaiņas, kas nesen izdarītas šajā wiki.', 'tooltip-n-randompage' => 'Iet uz nejauši izvēlētu lapu', 'tooltip-n-help' => 'Vieta, kur uzzināt.', 'tooltip-t-whatlinkshere' => 'Visas wiki lapas, kurās ir saites uz šejieni', 'tooltip-t-recentchangeslinked' => 'Izmaiņas, kas nesen izdarītas lapās, kurās ir saites uz šo lapu', 'tooltip-feed-rss' => 'Šīs lapas RSS barotne', 'tooltip-feed-atom' => 'Šīs lapas Atom barotne', 'tooltip-t-contributions' => 'Apskatīt šā lietotāja ieguldījumu uzskaitījumu.', 'tooltip-t-emailuser' => 'Sūtīt e-pastu šim lietotājam', 'tooltip-t-upload' => 'Augšuplādēt attēlus vai multimēdiju failus', 'tooltip-t-specialpages' => 'Visu īpašo lapu uzskaitījums', 'tooltip-t-print' => 'Drukājama lapas versija', 'tooltip-t-permalink' => 'Paliekoša saite uz šo lapas versiju', 'tooltip-ca-nstab-main' => 'Apskatīt rakstu', 'tooltip-ca-nstab-user' => 'Apskatīt lietotāja lapu', 'tooltip-ca-nstab-media' => 'Apskatīt multimēdiju lapu', 'tooltip-ca-nstab-special' => 'Šī ir īpašā lapa, tu nevari izmainīt pašu lapu.', 'tooltip-ca-nstab-project' => 'Apskatīt projekta lapu', 'tooltip-ca-nstab-image' => 'Apskatīt attēla lapu', 'tooltip-ca-nstab-mediawiki' => 'Apskatīt sistēmas paziņojumu', 'tooltip-ca-nstab-template' => 'Apskatīt veidni', 'tooltip-ca-nstab-help' => 'Apskatīt palīdzības lapu', 'tooltip-ca-nstab-category' => 'Apskatīt kategorijas lapu', 'tooltip-minoredit' => 'Atzīmēt šo par maznozīmīgu labojumu', 'tooltip-save' => 'Saglabāt veiktās izmaiņas', 'tooltip-preview' => 'Parādīt izmaiņu priekšskatījumu. Lūdzam izmantot šo iespēju pirms saglabāšanas.', 'tooltip-diff' => 'Parādīt, kā esi izmainījis tekstu.', 'tooltip-compareselectedversions' => 'Aplūkot atšķirības starp divām izvēlētajām lapas versijām.', 'tooltip-watch' => 'Pievienot šo lapu uzraugāmo lapu sarakstam', 'tooltip-recreate' => 'Atjaunot lapu, lai arī tā ir bijusi izdzēsta', 'tooltip-upload' => 'Sākt augšuplādi', 'tooltip-rollback' => '"Novērst" atceļ visas šī lietotāja izmaiņas vienā piegājienā', 'tooltip-undo' => '"Atgriezt" atgriež šīs izmaiņas un atver labošanas formu priekšskatījuma veidā. Tas atļauj pievienot iemeslu kopsavilkumā.', 'tooltip-preferences-save' => 'Saglabāt iestatījumus', 'tooltip-summary' => 'Ievadiet īsu kopsavilkumu', # Metadata 'notacceptable' => 'Vikipēdijas serveris nevar sniegt datus Jūsu klientam nolasāmā formātā.', # Attribution 'anonymous' => '{{PLURAL:$1|Anonīmais {{grammar:ģenitīvs|{{SITENAME}}}} lietotājs|Anonīmie {{grammar:ģenitīvs|{{SITENAME}}}} lietotāji}}', 'siteuser' => '{{grammar:ģenitīvs|{{SITENAME}}}} lietotājs $1', 'anonuser' => '{{SITENAME}} anonīms lietotājs $1', 'lastmodifiedatby' => 'Šo lapu pēdējoreiz izmainīja $3, $2, $1.', 'othercontribs' => 'Balstototies uz $1 darbu.', 'others' => 'citi', 'siteusers' => '{{SITENAME}} {{PLURAL:$2|lietotāja|lietotāju}} $1', 'anonusers' => '{{SITENAME}} anonīma {{PLURAL:$2|lietotāja|lietotāju}} $1', 'creditspage' => 'Lapas autori', 'nocredits' => 'Šai lapa nav pieejama informācija par autoriem.', # Spam protection 'spamprotectiontitle' => 'Spama filtrs', 'spamprotectiontext' => 'Lapu, kuru tu gribēji saglabāt, nobloķēja spama filtrs. To visticamāk izraisīja ārēja saite uz melnajā sarakstā esošu interneta vietni.', 'spamprotectionmatch' => 'Spama filtram radās iebildumi pret šo tekstu: $1', 'spambot_username' => 'MediaWiki surogātpasta tīrīšana', 'spam_reverting' => 'Atjauno iepriekšējo versiju, kas nesatur saiti uz $1', # Info page 'pageinfo-title' => 'Informācija par "$1"', 'pageinfo-header-edits' => 'Labojumu vēsture', 'pageinfo-header-watchlist' => 'Uzraugāmie raksti', 'pageinfo-header-views' => 'Skatījumi', 'pageinfo-subjectpage' => 'Lapa', 'pageinfo-talkpage' => 'Diskusiju lapa', 'pageinfo-watchers' => 'Uzraudzītāju skaits', 'pageinfo-edits' => 'Izmaiņu skaits', 'pageinfo-authors' => 'Atsevišķu autoru skaits', 'pageinfo-views' => 'Skatījumu skaits', 'pageinfo-viewsperedit' => 'Skatījumi uz labojumu', # Patrolling 'markaspatrolleddiff' => 'Atzīmēt kā pārbaudītu', 'markaspatrolledtext' => 'Atzīmēt šo lapu kā pārbaudītu', 'markedaspatrolled' => 'Atzīmēta kā pārbaudīta', 'rcpatroldisabled' => 'Pēdējo izmaiņu pārbaude atslēgta', 'rcpatroldisabledtext' => 'Pēdējo izmaiņu pārbaudes iespēja šobrīd ir atslēgta.', 'markedaspatrollederror' => 'Nevar atzīmēt kā pārbaudītu', 'markedaspatrollederrortext' => 'Jums jānorāda versija, ko atzīmēt kā pārbaudītu.', 'markedaspatrollederror-noautopatrol' => 'Jums nav atļaujas atzīmēt savas izmaiņas kā pārbaudītas.', # Patrol log 'patrol-log-page' => 'Pārbaudes reģistrs', 'patrol-log-header' => 'Šis ir pārbaudīto versiju reģistrs.', 'log-show-hide-patrol' => '$1 pārbaudes reģistrs', # Image deletion 'deletedrevision' => 'Izdzēstā vecā versija $1', 'filedeleteerror-short' => 'Kļūda dzēšot failu: $1', 'filedeleteerror-long' => 'Kļūdas, kas radās failu dzēšanas laikā: $1', 'filedelete-missing' => 'Failu "$1" nevar izdzēst, jo tas nepastāv.', 'filedelete-old-unregistered' => 'Izvēlētā faila versija "$1" nav datubāzē.', 'filedelete-current-unregistered' => 'Izvēlētais fails "$1" nav datubāzē.', # Browsing diffs 'previousdiff' => '← Vecāka versija', 'nextdiff' => 'Jaunāka versija →', # Media information 'mediawarning' => "'''Brīdinājums''': Šis faila tips var saturēt ļaunprātīgu kodu, kuru izpildot, tava datora darbība var tikt traucēta.", 'imagemaxsize' => 'Attēlu apraksta lapās parādāmo attēlu maksimālais izmērs:', 'thumbsize' => 'Sīkbildes izmērs:', 'widthheightpage' => '$1 × $2, $3 {{PLURAL:$3|lapa|lapas}}', 'file-info' => 'faila izmērs: $1, MIME tips: $2', 'file-info-size' => '$1 × $2 pikseļi, faila izmērs: $3, MIME tips: $4', 'file-info-size-pages' => '$1 × $2 pikseļi, faila izmērs: $3, MIME tips: $4, $5 {{PLURAL:$5|lapa|lapas}}', 'file-nohires' => 'Augstāka izšķirtspēja nav pieejama.', 'svg-long-desc' => 'SVG fails, definētais izmērs $1 × $2 pikseļi, faila izmērs: $3', 'show-big-image' => 'Pilnā izmērā', 'show-big-image-preview' => 'Šī priekšskata izmērs: $1.', 'show-big-image-other' => '{{PLURAL:$2|Cits izmērs|Citi izmēri}}: $1.', 'show-big-image-size' => '$1 × $2 pikseļi', 'file-info-gif-frames' => '$1 {{PLURAL:$1|kadrs|kadri}}', 'file-info-png-repeat' => 'spēlēts $1 {{PLURAL:$1|reizi|reizes}}', 'file-info-png-frames' => '$1 {{PLURAL:$1|kadrs|kadri}}', # Special:NewFiles 'newimages' => 'Jauno attēlu galerija', 'imagelisttext' => 'Šobrīd redzams $1 {{PLURAL:$1|attēla|attēlu}} uzskaitījums, kas sakārtots $2.', 'newimages-summary' => 'Šeit var apskatīties pēdējos šeit augšuplādētos failus.', 'newimages-legend' => 'Filtrs', 'newimages-label' => 'Faila nosaukums (vai tā daļa):', 'showhidebots' => '($1 botus)', 'noimages' => 'Nav nekā ko redzēt.', 'ilsubmit' => 'Meklēt', 'bydate' => '<b>pēc datuma</b>', 'sp-newimages-showfrom' => 'Rādīt jaunos attēlus sākot no $1, $2', # Video information, used by Language::formatTimePeriod() to format lengths in the above messages 'seconds' => '{{PLURAL:$1|$1 sekunde|$1 sekundes}}', 'minutes' => '{{PLURAL:$1|$1 minūte|$1 minūtes}}', 'hours' => '{{PLURAL:$1|$1 stunda|$1 stundas}}', 'days' => '{{PLURAL:$1|$1 diena|$1 dienas}}', 'ago' => 'pirms $1', # Bad image list 'bad_image_list' => 'Formāts: Tiek ņemti vērā tikai ieraksti rindiņā kas sākas ar * Pirmajai saitei rindiņā ir jābūt uz attiecīgo failu Jebkuras sekojošas saites tiks uzskatītas par izņēmumiem t.i. lapām kurās fails drīkt tikt izmantots', # Metadata 'metadata' => 'Metadati', 'metadata-help' => 'Šis fails satur papildu informāciju, kuru visticamk ir pievienojis digitālais fotoaparāts vai skeneris, kas šo failu izveidoja. Ja šis fails pēc tam ir ticis modificēts, šie dati var neatbilst izmaiņām (var būt novecojuši).', 'metadata-expand' => 'Parādīt papildu detaļas', 'metadata-collapse' => 'Paslēpt papildu detaļas', 'metadata-fields' => 'Šajā paziņojumā esošie metadatu lauki būs redzami attēla lapā arī tad, kad metadatu tabula būs sakļauta. Pārējie lauki, pēc noklusējuma, būs paslēpti. * make * model * datetimeoriginal * exposuretime * fnumber * isospeedratings * focallength * artist * copyright * imagedescription * gpslatitude * gpslongitude * gpsaltitude', # EXIF tags 'exif-imagewidth' => 'platums', 'exif-imagelength' => 'augstums', 'exif-bitspersample' => 'biti komponentē', 'exif-compression' => 'Saspiešanas veids', 'exif-orientation' => 'Orientācija', 'exif-samplesperpixel' => 'Komponentu skaits', 'exif-planarconfiguration' => 'Datu izkārtojums', 'exif-xresolution' => 'Horizontālā izšķirtspēja', 'exif-yresolution' => 'Vertikālā izšķirtspēja', 'exif-jpeginterchangeformatlength' => 'JPEG datu baiti', 'exif-datetime' => 'Attēla pēdējās izmainīšanas datums un laiks', 'exif-imagedescription' => 'Attēla nosaukums', 'exif-make' => 'Fotoaparāta ražotājs', 'exif-model' => 'Fotoaparāta modelis', 'exif-software' => 'Lietotā programma', 'exif-artist' => 'Autors', 'exif-copyright' => 'Autortiesību īpašnieks', 'exif-exifversion' => 'EXIF versija', 'exif-flashpixversion' => 'Atbalstīta Flashpix versija', 'exif-colorspace' => 'Krāsu telpa', 'exif-componentsconfiguration' => 'Katras sastāvdaļas nozīme', 'exif-compressedbitsperpixel' => 'Attēla kompresijas pakāpe', 'exif-pixelydimension' => 'Attēla platums', 'exif-pixelxdimension' => 'Attēla augstums', 'exif-usercomment' => 'Lietotāja komentāri', 'exif-relatedsoundfile' => 'Saistītais skaņas fails', 'exif-datetimeoriginal' => 'Izveidošanas datums un laiks', 'exif-datetimedigitized' => 'Attēla izveidošanas datums un laiks', 'exif-subsectime' => 'DateTime milisekundes', 'exif-subsectimeoriginal' => 'DateTimeOriginal milisekundes', 'exif-subsectimedigitized' => 'DateTimeDigitized milisekundes', 'exif-exposuretime' => 'Ekspozīcijas laiks', 'exif-exposuretime-format' => '$1 s ($2)', 'exif-fnumber' => 'Diafragmas atvērums', 'exif-exposureprogram' => 'Ekspozīcijas programma', 'exif-spectralsensitivity' => 'Spektrālā jutība', 'exif-isospeedratings' => 'ISO jutība', 'exif-shutterspeedvalue' => 'APEX slēdža ātrums', 'exif-aperturevalue' => 'APEX apertūra', 'exif-brightnessvalue' => 'APEX spilgtums', 'exif-exposurebiasvalue' => 'Ekspozīcijas nobīde', 'exif-subjectdistance' => 'Objekta attālums', 'exif-meteringmode' => 'Mērīšanas režīms', 'exif-lightsource' => 'Gaismas avots', 'exif-flash' => 'Zibspuldze', 'exif-focallength' => 'Fokusa attālums', 'exif-subjectarea' => 'Objekta laukums', 'exif-flashenergy' => 'Zibspuldzes stiprums', 'exif-focalplanexresolution' => 'Fokusa plaknes X izšķirtspēja', 'exif-focalplaneyresolution' => 'Fokusa plaknes Y izšķirtspēja', 'exif-focalplaneresolutionunit' => 'Fokusa plaknes izšķirtspējas vienības', 'exif-subjectlocation' => 'Objekta atrašanās vieta', 'exif-exposureindex' => 'Ekspozīcijas rādītājs', 'exif-sensingmethod' => 'Jutības metode', 'exif-filesource' => 'Faila avots', 'exif-scenetype' => 'Ainas veids', 'exif-customrendered' => 'Individuālā attēlu apstrāde', 'exif-exposuremode' => 'Ekspozīcijas režīms', 'exif-whitebalance' => 'Baltā balanss', 'exif-digitalzoomratio' => 'Digitālās tālummaiņas koeficients', 'exif-focallengthin35mmfilm' => 'Fokusa attālums 35 mm filmā', 'exif-scenecapturetype' => 'Ainas uzņemšanas veids', 'exif-gaincontrol' => 'Ainas kontrole', 'exif-contrast' => 'Kontrasts', 'exif-saturation' => 'Piesātinājums', 'exif-sharpness' => 'Asums', 'exif-devicesettingdescription' => 'Ierīces uzstādījumu apraksts', 'exif-subjectdistancerange' => 'Objekta attāluma diapazons', 'exif-imageuniqueid' => 'Unikālais attēla ID', 'exif-gpsversionid' => 'GPS taga versija', 'exif-gpslatituderef' => 'Ziemeļu vai dienvidu platums', 'exif-gpslatitude' => 'Platums', 'exif-gpslongituderef' => 'Austrumu vai rietumu garums', 'exif-gpslongitude' => 'Garums', 'exif-gpsaltituderef' => 'Augstuma atsauce', 'exif-gpsaltitude' => 'Augstums', 'exif-gpstimestamp' => 'GPS laiks (atompulkstenis)', 'exif-gpssatellites' => 'Mērīšanai izmantotie satelīti', 'exif-gpsstatus' => 'Uztvērēja statuss', 'exif-gpsmeasuremode' => 'Mērīšanas režīms', 'exif-gpsdop' => 'Mērīšanas precizitāte', 'exif-gpsspeedref' => 'Ātruma vienība', 'exif-gpsspeed' => 'GPS uztvērēja ātrums', 'exif-gpstrackref' => 'Kustības virziena atsauce', 'exif-gpstrack' => 'Kustības virziens', 'exif-gpsimgdirectionref' => 'Attēla virziena atsauce', 'exif-gpsimgdirection' => 'Attēla virziens', 'exif-gpsmapdatum' => 'Izmantoti ģeodēziskās mērīšanas dati', 'exif-gpsprocessingmethod' => 'GPS apstrādes metodes nosaukums', 'exif-gpsareainformation' => 'GPS zonas nosaukums', 'exif-gpsdatestamp' => 'GPS datums', 'exif-jpegfilecomment' => 'JPEG faila komentārs', 'exif-keywords' => 'Atslēgas vārdi', 'exif-worldregiondest' => 'Parādītais pasaules reģions', 'exif-countrydest' => 'Parādītā valsts', 'exif-countrycodedest' => 'Parādītās valsts kods', 'exif-provinceorstatedest' => 'Parādītās valsts province', 'exif-citydest' => 'Parādītā pilsēta', 'exif-sublocationdest' => 'Parādītā pilsētas daļa', 'exif-objectname' => 'Īsais nosaukums', 'exif-specialinstructions' => 'Īpašas norādes', 'exif-headline' => 'Virsraksts', 'exif-source' => 'Avots', 'exif-contact' => 'Kontaktinformācija', 'exif-languagecode' => 'Valoda', 'exif-iimversion' => 'IIM versija', 'exif-iimcategory' => 'Kategorija', 'exif-datetimeexpires' => 'Neizmantot pēc', 'exif-identifier' => 'Identifikators', 'exif-lens' => 'Izmantotais objektīvs', 'exif-serialnumber' => 'Fotoaparāta sērijas numurs', 'exif-cameraownername' => 'Fotoaparāta īpašnieks', 'exif-nickname' => 'Neformāls attēla nosaukums', 'exif-rating' => 'Vērtējums (no 5)', 'exif-copyrighted' => 'Autortiesību statuss', 'exif-copyrightowner' => 'Autortiesību īpašnieks', 'exif-usageterms' => 'Izmantošanas noteikumi', 'exif-originaldocumentid' => 'Sākotnējā dokumenta unikālais ID', 'exif-licenseurl' => 'Autortiesību licences URL', 'exif-morepermissionsurl' => 'Alternatīvas licencēšanas informācija', 'exif-attributionurl' => 'Izmantojot šo darbu, lūdzu pievienojiet saiti uz', 'exif-preferredattributionname' => 'Izmantojot šo darbu, lūdzu norādiet autoru', 'exif-pngfilecomment' => 'PNG faila komentārs', 'exif-disclaimer' => 'Atruna', 'exif-contentwarning' => 'Brīdinājums par saturu', 'exif-giffilecomment' => 'GIF faila komentārs', 'exif-event' => 'Attēlotais notikums', 'exif-organisationinimage' => 'Attēlotā organizācija', 'exif-personinimage' => 'Attēlotā persona', # EXIF attributes 'exif-compression-1' => 'Nekompresēts', 'exif-copyrighted-true' => 'Ar autortiesībām', 'exif-copyrighted-false' => 'Publiski pieejams', 'exif-unknowndate' => 'Nezināms datums', 'exif-orientation-1' => 'Normāls', 'exif-orientation-2' => 'Pagriezts horizontāli', 'exif-orientation-3' => 'Pagriezts par 180°', 'exif-orientation-4' => 'Pagriezts vertikāli', 'exif-orientation-5' => 'Pagriezta 90° CCW un apgriezta vertikāli', 'exif-orientation-6' => 'Pagriezta 90° pretēji pulksteņa rādītājam', 'exif-orientation-7' => 'Pagriezta 90° CW un apgriezta vertikāli', 'exif-orientation-8' => 'Pagriezta 90° pulksteņa rādītāja virzienā', 'exif-colorspace-65535' => 'Nekalibrēts', 'exif-componentsconfiguration-0' => 'neeksistē', 'exif-exposureprogram-0' => 'Nav noteikta', 'exif-exposureprogram-1' => 'Manuāla', 'exif-exposureprogram-2' => 'Normāla programma', 'exif-exposureprogram-3' => 'Diafragmas prioritāte', 'exif-exposureprogram-4' => 'Slēdža prioritāte', 'exif-exposureprogram-8' => 'Ainavu režīms (ainavu fotogrāfijām ar fokusu uz fonu)', 'exif-subjectdistance-value' => '$1 metri', 'exif-meteringmode-0' => 'Nav zināms', 'exif-meteringmode-255' => 'Cits', 'exif-lightsource-0' => 'Nav zināms', 'exif-lightsource-1' => 'Dienas gaisma', 'exif-lightsource-2' => 'Dienasgaismas lampa', 'exif-lightsource-3' => 'Kvēlspuldze', 'exif-lightsource-4' => 'Zibspuldze', 'exif-lightsource-9' => 'Labi laika apstākļi', 'exif-lightsource-10' => 'Mākoņains laiks', 'exif-lightsource-12' => 'Dienasgaismas lampa (D 5700 - 7100K)', 'exif-lightsource-13' => 'Dienasgaismas lampa (N 4600 – 5400K)', 'exif-lightsource-14' => 'Dienasgaismas lampa (W 3900 – 4500K)', 'exif-lightsource-15' => 'Dienasgaismas lampa (WW 3200 – 3700K)', 'exif-lightsource-17' => 'Standarta gaisma A', 'exif-lightsource-18' => 'Standarta gaisma B', 'exif-lightsource-19' => 'Standarta gaisma C', 'exif-lightsource-24' => 'ISO studijas kvēlspuldze', 'exif-lightsource-255' => 'Cits gaismas avots', # Flash modes 'exif-flash-fired-0' => 'Zibspuldze netika izmantota', 'exif-flash-fired-1' => 'Zibspuldze tika izmantota', 'exif-flash-mode-3' => 'automātiskais režīms', 'exif-flash-redeye-1' => 'sarkano acu efekta samazināšanas režīms', 'exif-focalplaneresolutionunit-2' => 'collas', 'exif-sensingmethod-1' => 'Nav definēts', 'exif-sensingmethod-2' => 'Vienas mikroshēmas krāsu zonas sensors', 'exif-sensingmethod-3' => 'Divu mikroshēmu krāsu zonas sensors', 'exif-sensingmethod-4' => 'Trīs mikroshēmu krāsu zonas sensors', 'exif-customrendered-0' => 'Normāls process', 'exif-customrendered-1' => 'Dažādots process', 'exif-exposuremode-0' => 'Automātiskā ekspozīcija', 'exif-exposuremode-1' => 'Manuālā ekspozīcija', 'exif-whitebalance-0' => 'Automātisks baltā balanss', 'exif-whitebalance-1' => 'Manuāls baltā balanss', 'exif-scenecapturetype-0' => 'Standarta', 'exif-scenecapturetype-1' => 'Ainava', 'exif-scenecapturetype-2' => 'Portrets', 'exif-scenecapturetype-3' => 'Nakts aina', 'exif-contrast-0' => 'Normāls', 'exif-contrast-1' => 'Viegls', 'exif-contrast-2' => 'Pārmērīgs', 'exif-saturation-0' => 'Normāls', 'exif-saturation-1' => 'Zems piesātinājums', 'exif-saturation-2' => 'Augsts piesātinājums', 'exif-sharpness-0' => 'Normāls', 'exif-sharpness-1' => 'Viegls', 'exif-sharpness-2' => 'Pārmērīgs', 'exif-subjectdistancerange-0' => 'Nav zināma', 'exif-subjectdistancerange-1' => 'Makro', 'exif-subjectdistancerange-2' => 'Tuvs skats', 'exif-subjectdistancerange-3' => 'Tāls skats', # Pseudotags used for GPSLatitudeRef and GPSDestLatitudeRef 'exif-gpslatitude-n' => 'Ziemeļu platums', 'exif-gpslatitude-s' => 'Dienvidu platums', # Pseudotags used for GPSLongitudeRef and GPSDestLongitudeRef 'exif-gpslongitude-e' => 'Austrumu garums', 'exif-gpslongitude-w' => 'Rietumu garums', # Pseudotags used for GPSAltitudeRef 'exif-gpsaltitude-above-sealevel' => '$1 {{PLURAL:$1|metrs|metri}} virs jūras līmeņa', 'exif-gpsaltitude-below-sealevel' => '$1 {{PLURAL:$1|metrs|metri}} zem jūras līmeņa', 'exif-gpsmeasuremode-2' => 'Divdimensionāls mērījums', 'exif-gpsmeasuremode-3' => 'Trīsdimensionāls mērījums', # Pseudotags used for GPSSpeedRef 'exif-gpsspeed-k' => 'Kilometri stundā', 'exif-gpsspeed-m' => 'Jūdzes stundā', 'exif-gpsspeed-n' => 'Mezgli', # Pseudotags used for GPSDestDistanceRef 'exif-gpsdestdistance-k' => 'Kilometri', 'exif-gpsdestdistance-m' => 'Jūdzes', 'exif-gpsdestdistance-n' => 'Jūras jūdzes', 'exif-gpsdop-excellent' => 'Lielisks ($1)', 'exif-gpsdop-good' => 'Labs ($1)', 'exif-gpsdop-moderate' => 'Mērens ($1)', 'exif-gpsdop-fair' => 'Pieņemams ($1)', 'exif-gpsdop-poor' => 'Slikts ($1)', # Pseudotags used for GPSTrackRef, GPSImgDirectionRef and GPSDestBearingRef 'exif-gpsdirection-t' => 'Patiesais virziens', 'exif-gpsdirection-m' => 'Magnētiskais virziens', 'exif-dc-date' => 'Datums (-i)', 'exif-dc-publisher' => 'Izdevējs', 'exif-dc-rights' => 'Tiesības', 'exif-rating-rejected' => 'Noraidīts', 'exif-isospeedratings-overflow' => 'Lielāks kā 65535', 'exif-iimcategory-ace' => 'Māksla, kultūra un izklaide', 'exif-iimcategory-clj' => 'Noziedzība un likums', 'exif-iimcategory-dis' => 'Katastrofas un negadījumi', 'exif-iimcategory-fin' => 'Ekonomika un komercdarbība', 'exif-iimcategory-edu' => 'Izglītība', 'exif-iimcategory-evn' => 'Vide', 'exif-iimcategory-hth' => 'Veselība', 'exif-iimcategory-hum' => 'Cilvēku intereses', 'exif-iimcategory-lab' => 'Darbs', 'exif-iimcategory-lif' => 'Dzīvesveids un brīvā laika pavadīšana', 'exif-iimcategory-pol' => 'Politika', 'exif-iimcategory-rel' => 'Reliģija un ticība', 'exif-iimcategory-sci' => 'Zinātne un tehnoloģijas', 'exif-iimcategory-soi' => 'Sociālie jautājumi', 'exif-iimcategory-spo' => 'Sports', 'exif-iimcategory-war' => 'Karš, konflikti un nemieri', 'exif-iimcategory-wea' => 'Laika apstākļi', 'exif-urgency-normal' => 'Normāla ($1)', 'exif-urgency-low' => 'Zema ($1)', 'exif-urgency-high' => 'Augsta ($1)', 'exif-urgency-other' => 'Lietotāja definēta prioritāte ($1)', # External editor support 'edit-externally' => 'Izmainīt šo failu ar ārēju programmu', 'edit-externally-help' => '(Skat. [//www.mediawiki.org/wiki/Manual:External_editors instrukcijas] Mediawiki.org, lai iegūtu vairāk informācijas).', # 'all' in various places, this might be different for inflected languages 'watchlistall2' => 'visas', 'namespacesall' => 'visas', 'monthsall' => 'visi', 'limitall' => 'visas', # Email address confirmation 'confirmemail' => 'Apstiprini e-pasta adresi', 'confirmemail_noemail' => '[[Special:Preferences|Tavās izvēlēs]] nav norādīta derīga e-pasta adrese.', 'confirmemail_text' => 'Šajā wiki ir nepieciešams apstiprināt savu e-pasta adresi, lai izmantotu e-pasta funkcijas. Spied uz zemāk esošās pogas, lai uz tavu e-pasta adresi nosūtītu apstiprināšanas e-pastu. Tajā būs saite ar kodu; spied uz tās saites vai atver to savā interneta pārlūkā, lai apstiprinātu tavas e-pasta adreses derīgumu.', 'confirmemail_pending' => 'Apstiprināšanas kods jau tev tika nosūtīts pa e-pastu; ja tu nupat izveidoji savu kontu, varētu drusku pagaidīt, kamēr tas kods pienāk, pirms mēģināt dabūt jaunu.', 'confirmemail_send' => 'Nosūtīt apstiprināšanas kodu', 'confirmemail_sent' => 'Apstiprināšanas e-pasts nosūtīts.', 'confirmemail_oncreate' => 'Apstiprinājuma kods tika nosūtīts uz tavu e-pasta adresi. Šīs kods nav nepieciešams, lai varētu ielogoties, bet tas būs vajadzīgs lai pieslēgtu visas e-pasta bāzētās funkcijas šajā wiki.', 'confirmemail_sendfailed' => '{{SITENAME}} nevarēja nosūtīt apstiprināšanas e-pastu. Pārbaudi, vai adresē nav kāds nepareizs simbols. Nosūtīšanas programma atmeta atpakaļ: $1', 'confirmemail_invalid' => 'Nederīgs apstiprināšanas kods. Iespējams, beidzies tā termiņš.', 'confirmemail_needlogin' => 'Lai apstiprinātu e-pasta adresi, tev vispirms jāielogojas ($1).', 'confirmemail_success' => 'Tava e-pasta adrese ir apstiprināta. Tagad vari [[Special:UserLogin|doties iekšā]] ar savu lietotājvārdu un pilnvērtīgi izmantot wiki iespējas.', 'confirmemail_loggedin' => 'Tava e-pasta adrese tagad ir apstiprināta.', 'confirmemail_error' => 'Notikusi kāda kļūme ar tava apstiprinājuma saglabāšanu.', 'confirmemail_subject' => 'E-pasta adreses apstiprinajums no {{grammar:ģenitīvs|{{SITENAME}}}}', 'confirmemail_body' => 'Kads, iespejams, tu pats, no IP adreses $1 ir registrejis {{grammar:ģenitīvs|{{SITENAME}}}} lietotaja vardu "$2" ar so e-pasta adresi. Lai apstiprinatu, ka so lietotaja vardu esi izveidojis tu pats, un aktivizetu e-pasta izmantosanu {{SITENAME}}, atver so saiti sava interneta parluka: $3 Ja tu *neesi* registrejis sadu lietotaja vardu, atver sho saiti savaa interneta browserii, lai atceltu shiis e-pasta adreses apstiprinaashanu: $5 Si apstiprinajuma koda deriguma termins ir $4.', 'confirmemail_invalidated' => 'E-pasta adreses apstiprināšana atcelta', 'invalidateemail' => 'Atcelt e-pasta adreses apstiprināšanu', # Scary transclusion 'scarytranscludedisabled' => '[Starpviki saišu iekļaušana ir atspējota.]', 'scarytranscludefailed' => '[Neizdevās ienest veidni $1.]', 'scarytranscludetoolong' => '[URL adrese ir pārāk gara.]', # Delete conflict 'deletedwhileediting' => "'''Brīdinājums:''' Šī lapa tika izdzēsta, pēc tam, kad tu to sāki izmainīt!", 'confirmrecreate' => "Lietotājs [[User:$1|$1]] ([[User talk:$1|diskusija]]) izdzēsa šo lapu, pēc tam, kad tu to biji sācis rediģēt, ar iemeslu: : ''$2'' Lūdzu apstiprini, ka tiešām gribi izveidot šo lapu no jauna.", 'recreate' => 'Izveidot no jauna', # action=purge 'confirm_purge_button' => 'Labi', 'confirm-purge-top' => "Iztīrīt šīs lapas kešu (''cache'')?", # action=watch/unwatch 'confirm-watch-button' => 'Labi', 'confirm-watch-top' => 'Pievienot šo lapu uzraugāmo lapu sarakstam?', 'confirm-unwatch-button' => 'Labi', # Multipage image navigation 'imgmultipageprev' => '← iepriekšējā lapa', 'imgmultipagenext' => 'nākamā lapa →', 'imgmultigo' => 'Aiziet!', 'imgmultigoto' => 'Iet uz lapu $1', # Table pager 'ascending_abbrev' => 'pieaug.', 'descending_abbrev' => 'dilst.', 'table_pager_next' => 'Nākamā lapa', 'table_pager_prev' => 'Iepriekšējā lapa', 'table_pager_first' => 'Pirmā lapa', 'table_pager_last' => 'Pēdējā lapa', 'table_pager_limit' => 'Rādīt $1 ierakstus vienā lapā', 'table_pager_limit_label' => 'Skaits vienā lapā:', 'table_pager_limit_submit' => 'Parādīt', 'table_pager_empty' => 'Neko neatrada', # Auto-summaries 'autosumm-blank' => 'Nodzēsa lapu', 'autosumm-replace' => "Aizvieto lapas saturu ar '$1'", 'autoredircomment' => 'Pāradresē uz [[$1]]', 'autosumm-new' => 'Jauna lapa: $1', # Live preview 'livepreview-loading' => 'Ielādē…', 'livepreview-ready' => 'Ielādējas… Gatavs!', 'livepreview-failed' => 'Tūlītējais pirmskats nobruka! Pamēģini parasto pirmskatu.', 'livepreview-error' => 'Neizdevās pievienoties: $1 "$2". Pamēģini parasto pirmskatu.', # Friendlier slave lag warnings 'lag-warn-normal' => 'Izmaiņas, kas ir jaunākas par $1 {{PLURAL:$1|sekundi|sekundēm}}, var neparādīties šajā sarakstā.', 'lag-warn-high' => 'Sakarā ar lielu datubāzes servera lagu, izmaiņas, kas svaigākas par $1 {{PLURAL:$1|sekundi|sekundēm}}, šajā sarakstā var neparādīties.', # Watchlist editor 'watchlistedit-numitems' => 'Tavs uzraugāmo lapu saraksts satur {{PLURAL:$1|1 lapu|$1 lapas}}, neieskaitot diskusiju lapas.', 'watchlistedit-noitems' => 'Tavs uzraugāmo rakstu saraksts ir tukšs.', 'watchlistedit-normal-title' => 'Izmainīt uzraugāmo rakstu sarakstu', 'watchlistedit-normal-legend' => 'Noņemt lapas (virsrakstus) no uzraugāmo rakstu saraksta', 'watchlistedit-normal-explain' => 'Tavā uzraugāmo rakstu sarakstā esošās lapas ir redzamas zemāk. Lai noņemtu lapu, ieķeksē lodziņā pretī lapai un uzspied Noņemt lapas. Var arī izmainīt [[Special:EditWatchlist/raw|neapstrādātu sarakstu]] (viens liels teksta lauks).', 'watchlistedit-normal-submit' => 'Noņemt lapas', 'watchlistedit-normal-done' => '{{PLURAL:$1|1 lapa tika noņemta|$1 lapas tika noņemtas}} no uzraugāmo rakstu saraksta:', 'watchlistedit-raw-title' => 'Izmainīt uzraugāmo rakstu saraksta kodu', 'watchlistedit-raw-legend' => 'Izmainīt uzraugāmo rakstu saraksta kodu', 'watchlistedit-raw-explain' => 'Uzraugāmo rakstu sarakstā esošās lapas ir redzamas zemāk, un šo sarakstu var izmainīt lapas pievienojot vai izdzēšot no saraksta; katrai rindai te atbilst viena lapa. Tad, kad pabeigts, uzspied Atjaunot sarakstu. Var arī lietot [[Special:EditWatchlist|standarta izmainīšanas lapu]].', 'watchlistedit-raw-titles' => 'Lapas:', 'watchlistedit-raw-submit' => 'Atjaunot sarakstu', 'watchlistedit-raw-done' => 'Tavs uzraugāmo rakstu saraksts tika atjaunots.', 'watchlistedit-raw-added' => '{{PLURAL:$1|1 lapa tika pievienota|$1 lapas tika pievienotas}}:', 'watchlistedit-raw-removed' => '{{PLURAL:$1|1 lapa tika noņemta|$1 lapas tika noņemtas}}:', # Watchlist editing tools 'watchlisttools-view' => 'Skatīt atbilstošās izmaiņas', 'watchlisttools-edit' => 'Apskatīt un izmainīt uzraugāmo rakstu sarakstu', 'watchlisttools-raw' => 'Izmainīt uzraugāmo rakstu saraksta kodu', # Core parser functions 'unknown_extension_tag' => 'Nezināma paplašinājuma iezīme "$1"', 'duplicate-defaultsort' => '\'\'\'Brīdinājums:\'\'\' Noklusējuma kārtošanas atslēga "$2" ignorē kārtošanas atslēga "$1".', # Special:Version 'version' => 'Versija', 'version-extensions' => 'Ieinstalētie paplašinājumi', 'version-specialpages' => 'Īpašās lapas', 'version-variables' => 'Mainīgie', 'version-antispam' => 'Spama aizsardzība', 'version-skins' => 'Apdares', 'version-other' => 'Cita', 'version-hooks' => 'Aizķeres', 'version-hook-name' => 'Aizķeres nosaukums', 'version-version' => '(Versija $1)', 'version-license' => 'Licence', 'version-poweredby-credits' => "Šis viki darbojas ar '''[//www.mediawiki.org/ MediaWiki]''' programmatūru, autortiesības © 2001-$1 $2.", 'version-poweredby-others' => 'citi', 'version-software' => 'Instalētā programmatūra', 'version-software-product' => 'Produkts', 'version-software-version' => 'Versija', # Special:FilePath 'filepath' => 'Failu adreses', 'filepath-page' => 'Fails:', 'filepath-submit' => 'Atrast', # Special:FileDuplicateSearch 'fileduplicatesearch' => 'Meklēt failu kopijas', 'fileduplicatesearch-summary' => 'Meklē dublējošos failus, izmantojot uz jaucējfunkcijas vērtības.', 'fileduplicatesearch-legend' => 'Meklēt kopiju', 'fileduplicatesearch-filename' => 'Faila vārds:', 'fileduplicatesearch-submit' => 'Meklēt', 'fileduplicatesearch-info' => '$1 × $2 pikseļi<br />Faila izmērs: $3<br />MIME tips: $4', 'fileduplicatesearch-result-1' => 'Failam "$1" nav identiskas kopijas.', 'fileduplicatesearch-result-n' => 'Failam "$1" ir {{PLURAL:$2|1 identiska kopija|$2 identiskas kopijas}}.', # Special:SpecialPages 'specialpages' => 'Īpašās lapas', 'specialpages-note' => '---- * Normālas īpašās lapas. * <span class="mw-specialpagerestricted">Ierobežotas pieejas īpašās lapas.</span> * <span class="mw-specialpagecached">Iekešotās īpašās lapas.</span>', 'specialpages-group-maintenance' => 'Uzturēšanas atskaites', 'specialpages-group-other' => 'Citas īpašās lapas', 'specialpages-group-login' => 'Ieiet / piereģistrēties', 'specialpages-group-changes' => 'Pēdējās izmaiņas un reģistri', 'specialpages-group-media' => 'Failu atskaites un augšuplāde', 'specialpages-group-users' => 'Lietotāji un piekļuves tiesības', 'specialpages-group-highuse' => 'Bieži izmantotās lapas', 'specialpages-group-pages' => 'Lapu saraksti', 'specialpages-group-pagetools' => 'Lapu rīki', 'specialpages-group-wiki' => 'Wiki dati un rīki', 'specialpages-group-redirects' => 'Pāradresējošas īpašās lapas', 'specialpages-group-spam' => 'Spama rīki', # Special:BlankPage 'blankpage' => 'Tukša lapa', 'intentionallyblankpage' => 'Šī lapa ar nodomu ir atstāta tukša.', # Special:Tags 'tags' => 'Derīgi izmaiņu tagi', 'tag-filter' => '[[Special:Tags|Tagu]] filtrs:', 'tag-filter-submit' => 'Filtrs', 'tags-title' => 'Tagi', 'tags-tag' => 'Taga nosaukums', 'tags-display-header' => 'Izmainīto sarakstu izskats', 'tags-description-header' => 'Nozīmes pilns apraksts', 'tags-hitcount-header' => 'Iezīmētās izmaiņas', 'tags-edit' => 'labot', 'tags-hitcount' => '$1 {{PLURAL:$1|izmaiņa|izmaiņas}}', # Special:ComparePages 'comparepages' => 'Salīdzināt lapas', 'compare-selector' => 'Salīdzināt lapu versijas', 'compare-page1' => '1. lapa', 'compare-page2' => '2. lapa', 'compare-rev1' => '1. versija', 'compare-rev2' => '2. versija', 'compare-submit' => 'Salīdzināt', 'compare-invalid-title' => 'Norādītais nosaukums nav derīgs.', 'compare-title-not-exists' => 'Norādītais nosaukums neeksistē.', 'compare-revision-not-exists' => 'Norādītā versija neeksistē.', # Database error messages 'dberr-header' => 'Šim viki ir problēma', 'dberr-problems' => 'Atvainojiet! Šai vietnei ir radušās tehniskas problēmas.', 'dberr-again' => 'Uzgaidiet dažas minūtes un pārlādējiet šo lapu.', 'dberr-info' => '(Nevar sazināties ar datubāzes serveri: $1)', 'dberr-usegoogle' => 'Pa to laiku Jūs varat izmantot Google meklēšanu.', 'dberr-outofdate' => 'Ņemiet vērā, ka mūsu satura indeksācija var būt novecojusi.', 'dberr-cachederror' => 'Šī ir lapas agrāk saglabātā kopija, tā var nebūt atjaunināta.', # HTML forms 'htmlform-invalid-input' => 'Ar dažiem datiem no Jūsu ievades ir problēmas', 'htmlform-select-badoption' => 'Vērtība, ko Jūs norādījāt, nav derīga.', 'htmlform-int-invalid' => 'Vērtība, ko Jūs norādījāt, nav vesels skaitlis.', 'htmlform-float-invalid' => 'Vērtība, ko Jūs norādījāt, nav skaitlis.', 'htmlform-int-toolow' => 'Vērtība, ko Jūs norādījāt, ir mazāka par $1 minimumu', 'htmlform-int-toohigh' => 'Vērtība, ko Jūs norādījāt, ir lielāka par $1 maksimumu', 'htmlform-required' => 'Šī vērtība ir obligāta', 'htmlform-submit' => 'Iesniegt', 'htmlform-reset' => 'Atcelt izmaiņas', 'htmlform-selectorother-other' => 'Citi', # SQLite database support 'sqlite-has-fts' => '$1 ar pilnteksta meklēšanas atbalstu', 'sqlite-no-fts' => '$1 bez pilnteksta meklēšanas atbalsta', # New logging system 'logentry-delete-delete' => '$1 izdzēsa lapu $3', 'logentry-delete-restore' => '$1 atjaunoja lapu $3', 'revdelete-content-hid' => 'saturs slēpts', 'revdelete-summary-hid' => 'labojuma kopsavilkums slēpts', 'revdelete-uname-hid' => 'lietotājvārds slēpts', 'revdelete-content-unhid' => 'satura slēpšana atcelta', 'revdelete-summary-unhid' => 'labojuma kopsavilkuma slēpšana atcelta', 'revdelete-uname-unhid' => 'lietotājvārda slēpšana atcelta', 'revdelete-restricted' => 'piemērot administratoriem ierobežojumus', 'revdelete-unrestricted' => 'noņemt administratoriem ierobežojumus', 'logentry-move-move' => '$1 pārvietoja lapu $3 uz $4', 'logentry-move-move-noredirect' => '$1 pārvietoja lapu $3 uz $4, neatstājot pāradresāciju', 'logentry-move-move_redir' => '$1 pārvietoja lapu $3 uz $4, atstājot pāradresāciju', 'logentry-move-move_redir-noredirect' => '$1 pārvietoja lapu $3 uz $4 ar pāradresāciju, neatstājot pāradresāciju', 'logentry-newusers-newusers' => 'Lietotāja konts $1 tika izveidots', 'logentry-newusers-create' => 'Lietotāja konts $1 tika izveidots', 'logentry-newusers-create2' => 'Lietotāja kontu $3 izveidoja $1', 'logentry-newusers-autocreate' => 'Konts $1 tika izveidots automātiski', 'newuserlog-byemail' => 'parole nosūtīta pa e-pastu', # Feedback 'feedback-subject' => 'Temats:', 'feedback-message' => 'Ziņojums:', 'feedback-cancel' => 'Atcelt', 'feedback-submit' => 'Iesniegt atsauksmes', 'feedback-adding' => 'Atsauksmes tiek pievienotas lapai...', 'feedback-error1' => 'Kļūda: API neatpazīts rezultāts', 'feedback-error2' => 'Kļūda: Labojums neizdevās', 'feedback-error3' => 'Kļūda: Nav atbildes no API', 'feedback-thanks' => 'Paldies! Jūsu atsauksmes ir ievietotas lapā "[$2 $1]".', 'feedback-close' => 'Gatavs', 'feedback-bugnew' => 'Es pārbaudīju. Ziņot par jaunu kļūdu', # API errors 'api-error-copyuploaddisabled' => 'Augšupielāde no URL šajā serverī ir atspējota.', 'api-error-filename-tooshort' => 'Faila nosaukums ir pārāk īss.', 'api-error-http' => 'Iekšēja kļūda: Nevar izveidot savienojumu ar serveri.', 'api-error-ok-but-empty' => 'Iekšēja kļūda: Nav atbildes no servera.', 'api-error-timeout' => 'Serveris neatbildēja paredzētajā laikā.', 'api-error-unclassified' => 'Nezināma kļūda.', 'api-error-unknown-code' => 'Nezināma kļūda: " $1 "', 'api-error-unknown-warning' => 'Nezināms brīdinājums: $1', 'api-error-uploaddisabled' => 'Augšupielāde šajā wiki ir atslēgta.', );
kimberli/5327A-notebook
languages/messages/MessagesLv.php
PHP
gpl-2.0
194,685
<?php namespace qtismtest\common\datatypes; use qtism\common\datatypes\Utils; use qtismtest\QtiSmTestCase; /** * Class DatatypeUtilsTest */ class DatatypeUtilsTest extends QtiSmTestCase { /** * @dataProvider isQtiIntegerValidProvider * @param int $value */ public function testIsQtiIntegerValid($value) { $this::assertTrue(Utils::isQtiInteger($value)); } /** * @dataProvider isQtiIntegerInvalidProvider * @param int $value */ public function testIsQtiIntegerInvalid($value) { $this::assertFalse(Utils::isQtiInteger($value)); } /** * @return array */ public function isQtiIntegerValidProvider() { return [ [0], [-0], [250], [-250], [2147483647], [-2147483647], ]; } /** * @return array */ public function isQtiIntegerInvalidProvider() { return [ [null], [''], ['bla'], [25.5], [true], [2147483648], [-2147483649], ]; } }
oat-sa/qti-sdk
test/qtismtest/common/datatypes/DatatypeUtilsTest.php
PHP
gpl-2.0
1,146
<?php /** * @version $Id: move.php 1812 2013-01-14 18:45:06Z lefteris.kavadas $ * @package K2 * @author JoomlaWorks http://www.joomlaworks.net * @copyright Copyright (c) 2006 - 2013 JoomlaWorks Ltd. All rights reserved. * @license GNU/GPL license: http://www.gnu.org/copyleft/gpl.html */ // no direct access defined('_JEXEC') or die; ?> <form action="index.php" method="post" name="adminForm" id="adminForm"> <fieldset style="float:left;"> <legend><?php echo JText::_('K2_TARGET_JOOMLA_USER_GROUP'); ?></legend> <?php echo $this->lists['group']; ?> </fieldset> <fieldset style="float:left;"> <legend><?php echo JText::_('K2_TARGET_K2_USER_GROUP'); ?></legend> <?php echo $this->lists['k2group']; ?> </fieldset> <fieldset style="clear:both;"> <legend><?php echo JText::_('K2_USERS_BEING_MOVED'); ?></legend> <ol> <?php foreach ($this->rows as $row): ?> <li> <?php echo $row->name; ?> <input type="hidden" name="cid[]" value="<?php echo $row->id; ?>" /> </li> <?php endforeach; ?> </ol> </fieldset> <input type="hidden" name="option" value="com_k2" /> <input type="hidden" name="view" value="<?php echo JRequest::getVar('view'); ?>" /> <input type="hidden" name="task" value="<?php echo JRequest::getVar('task'); ?>" /> <?php echo JHTML::_( 'form.token' ); ?> </form>
the-dani/kunnandidagen
administrator/components/com_k2/views/users/tmpl/move.php
PHP
gpl-2.0
1,323
// // System.Security.Permissions.DataProtectionPermission class // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Globalization; namespace System.Security.Permissions { [Serializable] public sealed class DataProtectionPermission : CodeAccessPermission, IUnrestrictedPermission { private const int version = 1; private DataProtectionPermissionFlags _flags; public DataProtectionPermission (PermissionState state) { if (PermissionHelper.CheckPermissionState (state, true) == PermissionState.Unrestricted) _flags = DataProtectionPermissionFlags.AllFlags; } public DataProtectionPermission (DataProtectionPermissionFlags flags) { // reuse validation by the Flags property Flags = flags; } public DataProtectionPermissionFlags Flags { get { return _flags; } set { if ((value & ~DataProtectionPermissionFlags.AllFlags) != 0) { string msg = String.Format (Locale.GetText ("Invalid enum {0}"), value); throw new ArgumentException (msg, "DataProtectionPermissionFlags"); } _flags = value; } } public bool IsUnrestricted () { return (_flags == DataProtectionPermissionFlags.AllFlags); } public override IPermission Copy () { return new DataProtectionPermission (_flags); } public override IPermission Intersect (IPermission target) { DataProtectionPermission dp = Cast (target); if (dp == null) return null; if (this.IsUnrestricted () && dp.IsUnrestricted ()) return new DataProtectionPermission (PermissionState.Unrestricted); if (this.IsUnrestricted ()) return dp.Copy (); if (dp.IsUnrestricted ()) return this.Copy (); return new DataProtectionPermission (_flags & dp._flags); } public override IPermission Union (IPermission target) { DataProtectionPermission dp = Cast (target); if (dp == null) return this.Copy (); if (this.IsUnrestricted () || dp.IsUnrestricted ()) return new SecurityPermission (PermissionState.Unrestricted); return new DataProtectionPermission (_flags | dp._flags); } public override bool IsSubsetOf (IPermission target) { DataProtectionPermission dp = Cast (target); if (dp == null) return (_flags == DataProtectionPermissionFlags.NoFlags); if (dp.IsUnrestricted ()) return true; if (this.IsUnrestricted ()) return false; return ((_flags & ~dp._flags) == 0); } public override void FromXml (SecurityElement e) { // General validation in CodeAccessPermission PermissionHelper.CheckSecurityElement (e, "e", version, version); // Note: we do not (yet) care about the return value // as we only accept version 1 (min/max values) _flags = (DataProtectionPermissionFlags) Enum.Parse ( typeof (DataProtectionPermissionFlags), e.Attribute ("Flags")); } public override SecurityElement ToXml () { SecurityElement e = PermissionHelper.Element (typeof (DataProtectionPermission), version); e.AddAttribute ("Flags", _flags.ToString ()); return e; } // helpers private DataProtectionPermission Cast (IPermission target) { if (target == null) return null; DataProtectionPermission dp = (target as DataProtectionPermission); if (dp == null) { PermissionHelper.ThrowInvalidPermission (target, typeof (DataProtectionPermission)); } return dp; } } }
hardvain/mono-compiler
class/System.Security/System.Security.Permissions/DataProtectionPermission.cs
C#
gpl-2.0
4,520
<?php class wpmlHistoriesList extends wpMailPlugin { var $model = 'HistoriesList'; var $controller = 'historieslists'; var $table = ''; var $errors = array(); var $data = array(); var $fields = array( 'id' => "INT(11) NOT NULL AUTO_INCREMENT", 'history_id' => "INT(11) NOT NULL DEFAULT '0'", 'list_id' => "INT(11) NOT NULL DEFAULT '0'", 'created' => "DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00'", 'modified' => "DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00'", 'key' => "PRIMARY KEY (`id`), INDEX(`history_id`), INDEX(`list_id`)", ); var $tv_fields = array( 'id' => array("INT(11)", "NOT NULL AUTO_INCREMENT"), 'history_id' => array("INT(11)", "NOT NULL DEFAULT '0'"), 'list_id' => array("INT(11)", "NOT NULL DEFAULT '0'"), 'created' => array("DATETIME", "NOT NULL DEFAULT '0000-00-00 00:00:00'"), 'modified' => array("DATETIME", "NOT NULL DEFAULT '0000-00-00 00:00:00'"), 'key' => "PRIMARY KEY (`id`), INDEX(`history_id`), INDEX(`list_id`)" ); var $indexes = array('history_id', 'list_id'); function wpmlHistoriesList($data = array()) { global $Db; $this -> table = $this -> pre . $this -> controller; if (!empty($data)) { foreach ($data as $dkey => $dval) { $this -> {$dkey} = $dval; } } $Db -> model = $this -> model; } function defaults() { global $Html; $defaults = array( 'created' => $Html -> gen_date(), 'modified' => $Html -> gen_date(), ); return $defaults; } function validate($data = array()) { $this -> errors = array(); $data = (empty($data[$this -> model])) ? $data : $data[$this -> model]; extract($data, EXTR_SKIP); if (empty($history_id)) { $this -> errors['history_id'] = __('No history record was specified', $this -> plugin_name); } if (empty($list_id)) { $this -> errors['list_id'] = __('No mailing list was specified', $this -> plugin_name); } return $this -> errors; } } ?>
GaMaker/web-wordpress
wp-content/plugins/newsletters-lite/models/histories_list.php
PHP
gpl-2.0
2,033
package com.example.jmtransfers.jmtransfer; import android.content.SharedPreferences; import android.support.v7.app.ActionBar; import android.widget.TextView; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import android.widget.LinearLayout; public class MainActivity extends AppCompatActivity { ProgressDialog progress ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setDisplayShowTitleEnabled(false); progress = new ProgressDialog(this); progress.setTitle("Loading"); progress.setMessage("Wait while loading..."); progress.show(); new CountDownTimer(2000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { progress.dismiss(); Intent intent = new Intent(MainActivity.this, Dashboard.class); startActivity(intent); } }.start(); ImageView logo = (ImageView) findViewById(R.id.logo); logo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, Dashboard.class); startActivity(intent); } }); } }
unifieddigitalmedia/Just-Money-Transfers-Android
app/src/main/java/com/example/jmtransfers/jmtransfer/MainActivity.java
Java
gpl-2.0
2,118
<?php /** * @class FLPostGridModule */ class FLPostGridModule extends FLBuilderModule { /** * @method __construct */ public function __construct() { parent::__construct(array( 'name' => __('Posts', 'fl-builder'), 'description' => __('Display a grid of your WordPress posts.', 'fl-builder'), 'category' => __('Advanced Modules', 'fl-builder'), 'editor_export' => false, 'enabled' => true )); } /** * @method enqueue_scripts */ public function enqueue_scripts() { if(FLBuilderModel::is_builder_active() || $this->settings->layout == 'grid') { $this->add_js('jquery-masonry'); } if(FLBuilderModel::is_builder_active() || $this->settings->layout == 'gallery') { $this->add_js('fl-gallery-grid'); } if(FLBuilderModel::is_builder_active() || $this->settings->pagination == 'scroll') { $this->add_js('jquery-infinitescroll'); } } } /** * Register the module and its form settings. */ FLBuilder::register_module('FLPostGridModule', array( 'layout' => array( 'title' => __('Layout', 'fl-builder'), 'sections' => array( 'general' => array( 'title' => '', 'fields' => array( 'layout' => array( 'type' => 'select', 'label' => __('Layout Style', 'fl-builder'), 'default' => 'grid', 'options' => array( 'grid' => __('Grid', 'fl-builder'), 'gallery' => __('Gallery', 'fl-builder'), 'feed' => __('Feed', 'fl-builder'), ), 'toggle' => array( 'grid' => array( 'sections' => array('grid', 'image', 'content'), 'fields' => array('show_author') ), 'feed' => array( 'sections' => array('image', 'content'), 'fields' => array('image_position', 'show_author', 'show_comments', 'content_type') ), 'gallery' => array( 'tabs' => array( 'style' ) ) ) ), 'pagination' => array( 'type' => 'select', 'label' => __('Pagination Style', 'fl-builder'), 'default' => 'numbers', 'options' => array( 'numbers' => __('Numbers', 'fl-builder'), 'scroll' => __('Scroll', 'fl-builder'), 'none' => _x( 'None', 'Pagination style.', 'fl-builder' ), ) ), 'posts_per_page' => array( 'type' => 'text', 'label' => __('Posts Per Page', 'fl-builder'), 'default' => '10', 'size' => '4' ), ) ), 'grid' => array( 'title' => __('Grid', 'fl-builder'), 'fields' => array( 'post_width' => array( 'type' => 'text', 'label' => __('Post Width', 'fl-builder'), 'default' => '300', 'maxlength' => '3', 'size' => '4', 'description' => 'px' ), 'post_spacing' => array( 'type' => 'text', 'label' => __('Post Spacing', 'fl-builder'), 'default' => '60', 'maxlength' => '3', 'size' => '4', 'description' => 'px' ), ) ), 'image' => array( 'title' => __( 'Featured Image', 'fl-builder' ), 'fields' => array( 'show_image' => array( 'type' => 'select', 'label' => __('Image', 'fl-builder'), 'default' => '1', 'options' => array( '1' => __('Show', 'fl-builder'), '0' => __('Hide', 'fl-builder') ), 'toggle' => array( '1' => array( 'fields' => array('image_size') ) ) ), 'image_position' => array( 'type' => 'select', 'label' => __('Position', 'fl-builder'), 'default' => 'above', 'options' => array( 'above' => __('Above Text', 'fl-builder'), 'beside' => __('Beside Text', 'fl-builder') ) ), 'image_size' => array( 'type' => 'photo-sizes', 'label' => __('Size', 'fl-builder'), 'default' => 'medium' ), ) ), 'info' => array( 'title' => __( 'Post Info', 'fl-builder' ), 'fields' => array( 'show_author' => array( 'type' => 'select', 'label' => __('Author', 'fl-builder'), 'default' => '1', 'options' => array( '1' => __('Show', 'fl-builder'), '0' => __('Hide', 'fl-builder') ) ), 'show_date' => array( 'type' => 'select', 'label' => __('Date', 'fl-builder'), 'default' => '1', 'options' => array( '1' => __('Show', 'fl-builder'), '0' => __('Hide', 'fl-builder') ), 'toggle' => array( '1' => array( 'fields' => array('date_format') ) ) ), 'date_format' => array( 'type' => 'select', 'label' => __('Date Format', 'fl-builder'), 'default' => 'M j, Y', 'options' => array( // Note for developer: I would personally add this as a text field with a default value of get_option( 'date_format' ) 'M j, Y' => date('M j, Y'), 'F j, Y' => date('F j, Y'), 'm/d/Y' => date('m/d/Y'), 'm-d-Y' => date('m-d-Y'), 'd M Y' => date('d M Y'), 'd F Y' => date('d F Y'), 'Y-m-d' => date('Y-m-d'), 'Y/m/d' => date('Y/m/d'), ) ), 'show_comments' => array( 'type' => 'select', 'label' => __('Comments', 'fl-builder'), 'default' => '1', 'options' => array( '1' => __('Show', 'fl-builder'), '0' => __('Hide', 'fl-builder') ) ), ) ), 'content' => array( 'title' => __( 'Content', 'fl-builder' ), 'fields' => array( 'show_content' => array( 'type' => 'select', 'label' => __('Content', 'fl-builder'), 'default' => '1', 'options' => array( '1' => __('Show', 'fl-builder'), '0' => __('Hide', 'fl-builder') ) ), 'content_type' => array( 'type' => 'select', 'label' => __('Content Type', 'fl-builder'), 'default' => 'excerpt', 'options' => array( 'excerpt' => __('Excerpt', 'fl-builder'), 'full' => __('Full Text', 'fl-builder') ) ), 'show_more_link' => array( 'type' => 'select', 'label' => __('More Link', 'fl-builder'), 'default' => '0', 'options' => array( '1' => __('Show', 'fl-builder'), '0' => __('Hide', 'fl-builder') ) ), 'more_link_text' => array( 'type' => 'text', 'label' => __('More Link Text', 'fl-builder'), 'default' => __('Read More', 'fl-builder'), ), ) ) ) ), 'style' => array( // Tab 'title' => __('Style', 'fl-builder'), // Tab title 'sections' => array( // Tab Sections 'gallery_general' => array( 'title' => '', 'fields' => array( 'hover_transition' => array( 'type' => 'select', 'label' => __('Hover Transition', 'fl-builder'), 'default' => 'fade', 'options' => array( 'fade' => __('Fade', 'fl-builder'), 'slide-up' => __('Slide Up', 'fl-builder'), 'slide-down' => __('Slide Down', 'fl-builder'), 'scale-up' => __('Scale Up', 'fl-builder'), 'scale-down' => __('Scale Down', 'fl-builder'), ) ), ) ), 'icons' => array( 'title' => __('Icons', 'fl-builder'), 'fields' => array( 'has_icon' => array( 'type' => 'select', 'label' => __('Use Icon for Posts', 'fl-builder'), 'default' => 'no', 'options' => array( 'yes' => __('Yes', 'fl-builder'), 'no' => __('No', 'fl-builder'), ), 'toggle' => array( 'yes' => array( 'fields' => array( 'icon', 'icon_position', 'icon_color', 'icon_size' ) ) ), ), 'icon' => array( 'type' => 'icon', 'label' => __('Post Icon', 'fl-builder'), ), 'icon_position' => array( 'type' => 'select', 'label' => __('Post Icon Position', 'fl-builder'), 'default' => 'above', 'options' => array( 'above' => __('Above Text', 'fl-builder'), 'below' => __('Below Text', 'fl-builder'), ) ), 'icon_size' => array( 'type' => 'text', 'label' => __('Post Icon Size', 'fl-builder'), 'default' => '24', 'maxlength' => '3', 'size' => '4', 'description' => 'px' ), ) ), 'text_style' => array( 'title' => __('Colors', 'fl-builder'), 'fields' => array( 'text_color' => array( 'type' => 'color', 'label' => __('Text Color', 'fl-builder'), 'default' => 'ffffff', 'show_reset' => true ), 'icon_color' => array( 'type' => 'color', 'label' => __('Post Icon Color', 'fl-builder'), 'show_reset' => true ), 'text_bg_color' => array( 'type' => 'color', 'label' => __('Text Background Color', 'fl-builder'), 'default' => '333333', 'help' => __('The color applies to the overlay behind text over the background selections.', 'fl-builder'), 'show_reset' => true ), 'text_bg_opacity' => array( 'type' => 'text', 'label' => __('Text Background Opacity', 'fl-builder'), 'default' => '50', 'maxlength' => '3', 'size' => '4', 'description' => '%' ), ) ), ) ), 'content' => array( 'title' => __('Content', 'fl-builder'), 'file' => FL_BUILDER_DIR . 'includes/loop-settings.php', ) ));
faithmade/beaver-builder
modules/post-grid/post-grid.php
PHP
gpl-2.0
10,603
package me.yugy.app.common.utils; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.os.Environment; import android.os.StatFs; import java.io.File; import java.io.IOException; import static android.os.Environment.MEDIA_MOUNTED; /** * Created by yugy on 2014/7/4. */ public class StorageUtils { @SuppressWarnings("deprecation") @TargetApi(18) public static long getAvailableStorage() { String storageDirectory; storageDirectory = Environment.getExternalStorageDirectory().toString(); try { StatFs stat = new StatFs(storageDirectory); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { return ((long) stat.getAvailableBlocks() * (long) stat.getBlockSize()); }else{ return (stat.getAvailableBlocksLong() * stat.getBlockSizeLong()); } } catch (RuntimeException ex) { return 0; } } public static boolean isSDCardPresent() { return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); } public static boolean isSdCardWrittable() { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { return true; } return false; } public static File getCacheDirectory(Context context, boolean preferExternal) { File appCacheDir = null; if (preferExternal && MEDIA_MOUNTED .equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) { appCacheDir = getExternalCacheDir(context); } if (appCacheDir == null) { appCacheDir = context.getCacheDir(); } if (appCacheDir == null) { String cacheDirPath = context.getFilesDir().getPath() + "/cache/"; DebugUtils.log("Can't define system cache directory! " + cacheDirPath + " will be used."); appCacheDir = new File(cacheDirPath); } return appCacheDir; } private static boolean hasExternalStoragePermission(Context context) { int perm = context.checkCallingOrSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE"); return perm == PackageManager.PERMISSION_GRANTED; } private static File getExternalCacheDir(Context context) { File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data"); File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache"); if (!appCacheDir.exists()) { if (!appCacheDir.mkdirs()) { DebugUtils.log("Unable to create external cache directory"); return null; } try { new File(appCacheDir, ".nomedia").createNewFile(); } catch (IOException e) { DebugUtils.log("Can't create \".nomedia\" file in application external cache directory"); } } return appCacheDir; } }
jj-io/jj-android
mylibrary/src/main/java/me/yugy/app/common/utils/StorageUtils.java
Java
gpl-2.0
3,221
/* This file is part of the KDE project Copyright (C) 2005-2014 Jarosław Staniek <staniek@kde.org> Copyright (C) 2014 Roman Shtemberko <shtemberko@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "kexidbconnectionwidget.h" #include <kexi.h> #include <kexiguimsghandler.h> #include <db/connection.h> #include <db/utils.h> #include <db/drivermanager.h> #include <widget/KexiDBPasswordDialog.h> #include "kexidbdrivercombobox.h" #include <KoIcon.h> #include <kdebug.h> #include <klineedit.h> #include <KStandardAction> #include <KAction> #include <QLabel> #include <QCheckBox> #include <QRadioButton> #include <QVBoxLayout> #include <QHBoxLayout> #include <QWhatsThis> //! Templorary hides db list //! @todo reenable this when implemented #define NO_LOAD_DB_LIST // @internal class KexiDBConnectionWidget::Private { public: Private() : connectionOnly(false) { } KPushButton *btnSaveChanges, *btnTestConnection; bool connectionOnly; KexiProjectData data; KexiDBDriverComboBox *driversCombo; QAction *savePasswordHelpAction; }; class KexiDBConnectionDialog::Private { public: Private() { } KexiDBConnectionTabWidget *tabWidget; }; //--------- KexiDBConnectionWidget::KexiDBConnectionWidget(QWidget* parent) : QWidget(parent) , d(new Private) { setupUi(this); setObjectName("KexiConnectionSelectorWidget"); iconLabel->setPixmap(DesktopIcon(Kexi::serverIconName())); QVBoxLayout *driversComboLyr = new QVBoxLayout(frmEngine); driversComboLyr->setMargin(0); d->driversCombo = new KexiDBDriverComboBox(frmEngine, Kexi::driverManager().driversInfo(), KexiDBDriverComboBox::ShowServerDrivers); driversComboLyr->addWidget(d->driversCombo); frmEngine->setFocusProxy(d->driversCombo); lblEngine->setBuddy(d->driversCombo); QWidget::setTabOrder(lblEngine, d->driversCombo); #ifdef NO_LOAD_DB_LIST btnLoadDBList->hide(); #endif btnLoadDBList->setIcon(koIcon("view-refresh")); btnLoadDBList->setToolTip(i18n("Load database list from the server")); btnLoadDBList->setWhatsThis( i18n("Loads database list from the server, so you can select one using the <interface>Name</interface> combo box.")); btnSavePasswordHelp->setIcon(koIcon("help-contextual")); btnSavePasswordHelp->setToolTip(KStandardAction::whatsThis(0, 0, btnSavePasswordHelp)->text().remove('&')); d->savePasswordHelpAction = QWhatsThis::createAction(chkSavePassword); connect(btnSavePasswordHelp, SIGNAL(clicked()), this, SLOT(slotShowSavePasswordHelp())); QHBoxLayout *hbox = new QHBoxLayout(frmBottom); hbox->addStretch(2); d->btnSaveChanges = new KPushButton( KGuiItem( i18n("Save Changes"), "document-save", i18n("Save all changes made to this connection information"), i18n("Save all changes made to this connection information. " "You can later reuse this information.")), frmBottom); d->btnSaveChanges->setObjectName("savechanges"); hbox->addWidget(d->btnSaveChanges); hbox->addSpacing(KDialog::spacingHint()); QWidget::setTabOrder(titleEdit, d->btnSaveChanges); d->btnSaveChanges->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); d->btnTestConnection = new KPushButton( //! @todo add Test Connection icon KGuiItem(i18n("&Test Connection"), QString(), i18n("Test database connection"), i18n("Tests database connection. " "You can check validity of connection information.")), frmBottom); d->btnTestConnection->setObjectName("testConnection"); hbox->addWidget(d->btnTestConnection); setTabOrder(d->btnSaveChanges, d->btnTestConnection); d->btnTestConnection->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); connect(localhostRBtn, SIGNAL(clicked()), this, SLOT(slotLocationRadioClicked())); connect(remotehostRBtn, SIGNAL(clicked()), this, SLOT(slotLocationRadioClicked())); connect(chkPortDefault, SIGNAL(toggled(bool)), this , SLOT(slotCBToggled(bool))); connect(btnLoadDBList, SIGNAL(clicked()), this, SIGNAL(loadDBList())); connect(d->btnSaveChanges, SIGNAL(clicked()), this, SIGNAL(saveChanges())); } KexiDBConnectionWidget::~KexiDBConnectionWidget() { delete d; } bool KexiDBConnectionWidget::connectionOnly() const { return d->connectionOnly; } void KexiDBConnectionWidget::setDataInternal(const KexiProjectData& data, bool connectionOnly, const QString& shortcutFileName) { d->data = data; d->connectionOnly = connectionOnly; if (d->connectionOnly) { nameLabel->hide(); nameCombo->hide(); btnLoadDBList->hide(); dbGroupBox->setTitle(i18n("Database Connection")); } else { nameLabel->show(); nameCombo->show(); #ifndef NO_LOAD_DB_LIST btnLoadDBList->show(); #endif nameCombo->setEditText(d->data.databaseName()); dbGroupBox->setTitle(i18n("Database")); } //! @todo what if there's no such driver name? d->driversCombo->setDriverName(d->data.connectionData()->driverName); hostEdit->setText(d->data.connectionData()->hostName); if (d->data.connectionData()->hostName.isEmpty()) { localhostRBtn->setChecked(true); } else { remotehostRBtn->setChecked(true); } slotLocationRadioClicked(); if (d->data.connectionData()->port != 0) { chkPortDefault->setChecked(false); customPortEdit->setValue(d->data.connectionData()->port); } else { chkPortDefault->setChecked(true); /* @todo default port # instead of 0 */ customPortEdit->setValue(0); } userEdit->setText(d->data.connectionData()->userName); passwordEdit->setText(d->data.connectionData()->password); if (d->connectionOnly) titleEdit->setText(d->data.connectionData()->caption); else titleEdit->setText(d->data.caption()); if (shortcutFileName.isEmpty()) { d->btnSaveChanges->hide(); } else { if (!QFileInfo(shortcutFileName).isWritable()) { d->btnSaveChanges->setEnabled(false); } } chkSavePassword->setChecked(d->data.connectionData()->savePassword); adjustSize(); } void KexiDBConnectionWidget::setData(const KexiProjectData& data, const QString& shortcutFileName) { setDataInternal(data, false /*!connectionOnly*/, shortcutFileName); } void KexiDBConnectionWidget::setData(const KexiDB::ConnectionData& data, const QString& shortcutFileName) { KexiProjectData pdata(data); setDataInternal(pdata, true /*connectionOnly*/, shortcutFileName); } KPushButton* KexiDBConnectionWidget::saveChangesButton() const { return d->btnSaveChanges; } KPushButton* KexiDBConnectionWidget::testConnectionButton() const { return d->btnTestConnection; } KexiDBDriverComboBox* KexiDBConnectionWidget::driversCombo() const { return d->driversCombo; } KexiProjectData KexiDBConnectionWidget::data() { return d->data; } void KexiDBConnectionWidget::slotLocationRadioClicked() { hostLbl->setEnabled(remotehostRBtn->isChecked()); hostEdit->setEnabled(remotehostRBtn->isChecked()); } void KexiDBConnectionWidget::slotCBToggled(bool on) { if (sender() == chkPortDefault) { customPortEdit->setEnabled(!on); portLbl->setEnabled(!on); if (on) { portLbl->setBuddy(customPortEdit); } } } void KexiDBConnectionWidget::slotShowSavePasswordHelp() { QWhatsThis::showText(chkSavePassword->mapToGlobal(QPoint(0, chkSavePassword->height())), chkSavePassword->whatsThis()); } //----------- KexiDBConnectionWidgetDetails::KexiDBConnectionWidgetDetails(QWidget* parent) : QWidget(parent) { setupUi(this); customSocketEdit->setMode(KFile::File | KFile::ExistingOnly | KFile::LocalOnly); } KexiDBConnectionWidgetDetails::~KexiDBConnectionWidgetDetails() { } //----------- KexiDBConnectionTabWidget::KexiDBConnectionTabWidget(QWidget* parent) : KTabWidget(parent) { mainWidget = new KexiDBConnectionWidget(this); mainWidget->setObjectName("mainWidget"); mainWidget->layout()->setMargin(KDialog::marginHint()); addTab(mainWidget, i18n("Parameters")); detailsWidget = new KexiDBConnectionWidgetDetails(this); detailsWidget->setObjectName("detailsWidget"); addTab(detailsWidget, i18n("Details")); connect(detailsWidget->chkSocketDefault, SIGNAL(toggled(bool)), this, SLOT(slotSocketComboboxToggled(bool))); connect(detailsWidget->chkUseSocket, SIGNAL(toggled(bool)), this, SLOT(slotSocketComboboxToggled(bool))); connect(mainWidget->testConnectionButton(), SIGNAL(clicked()), this, SLOT(slotTestConnection())); } KexiDBConnectionTabWidget::~KexiDBConnectionTabWidget() { } void KexiDBConnectionTabWidget::setData(const KexiProjectData& data, const QString& shortcutFileName) { mainWidget->setData(data, shortcutFileName); detailsWidget->chkUseSocket->setChecked(data.constConnectionData()->useLocalSocketFile); detailsWidget->customSocketEdit->setUrl(data.constConnectionData()->localSocketFileName); detailsWidget->customSocketEdit->setEnabled(detailsWidget->chkUseSocket->isChecked()); detailsWidget->chkSocketDefault->setChecked(data.constConnectionData()->localSocketFileName.isEmpty()); detailsWidget->chkSocketDefault->setEnabled(detailsWidget->chkUseSocket->isChecked()); detailsWidget->descriptionEdit->setText(data.description()); } void KexiDBConnectionTabWidget::setData(const KexiDB::ConnectionData& data, const QString& shortcutFileName) { mainWidget->setData(data, shortcutFileName); detailsWidget->chkUseSocket->setChecked(data.useLocalSocketFile); detailsWidget->customSocketEdit->setUrl(data.localSocketFileName); detailsWidget->customSocketEdit->setEnabled(detailsWidget->chkUseSocket->isChecked()); detailsWidget->chkSocketDefault->setChecked(data.localSocketFileName.isEmpty()); detailsWidget->chkSocketDefault->setEnabled(detailsWidget->chkUseSocket->isChecked()); detailsWidget->descriptionEdit->setText(data.description); } KexiProjectData KexiDBConnectionTabWidget::currentProjectData() { KexiProjectData data; //! @todo check if that's database of connection shortcut. Now we're assuming db shortcut only! // collect data from the form's fields if (mainWidget->connectionOnly()) { data.connectionData()->caption = mainWidget->titleEdit->text(); data.setCaption(QString()); data.connectionData()->description = detailsWidget->descriptionEdit->toPlainText(); data.setDatabaseName(QString()); } else { data.connectionData()->caption.clear(); /* connection name is not specified... */ data.setCaption(mainWidget->titleEdit->text()); data.setDescription(detailsWidget->descriptionEdit->toPlainText()); data.setDatabaseName(mainWidget->nameCombo->currentText()); } data.connectionData()->driverName = mainWidget->driversCombo()->selectedDriverName(); data.connectionData()->hostName = (mainWidget->remotehostRBtn->isChecked()/*remote*/) ? mainWidget->hostEdit->text() : QString(); data.connectionData()->port = mainWidget->chkPortDefault->isChecked() ? 0 : mainWidget->customPortEdit->value(); data.connectionData()->localSocketFileName = detailsWidget->chkSocketDefault->isChecked() ? QString() : detailsWidget->customSocketEdit->url().toLocalFile(); data.connectionData()->useLocalSocketFile = detailsWidget->chkUseSocket->isChecked(); //UNSAFE!!!! data.connectionData()->userName = mainWidget->userEdit->text(); if (mainWidget->chkSavePassword->isChecked()) { // avoid keeping potentially wrong password that then will be re-used data.connectionData()->password = mainWidget->passwordEdit->text(); } data.connectionData()->savePassword = mainWidget->chkSavePassword->isChecked(); /*! @todo add "options=", eg. as string list? */ return data; } bool KexiDBConnectionTabWidget::savePasswordOptionSelected() const { return mainWidget->chkSavePassword->isChecked(); } void KexiDBConnectionTabWidget::slotTestConnection() { KexiDB::ConnectionData connectionData = *currentProjectData().connectionData(); bool savePasswordChecked = connectionData.savePassword; if (!savePasswordChecked) { connectionData.password = mainWidget->passwordEdit->text(); //not saved otherwise } if (mainWidget->passwordEdit->text().isEmpty()) { connectionData.password = QString::null; if (savePasswordChecked) { connectionData.savePassword = false; //for getPasswordIfNeeded() } if (~KexiDBPasswordDialog::getPasswordIfNeeded(&connectionData,this)) { return; } } KexiGUIMessageHandler msgHandler; KexiDB::connectionTestDialog(this, connectionData, msgHandler); } void KexiDBConnectionTabWidget::slotSocketComboboxToggled(bool on) { if (sender() == detailsWidget->chkSocketDefault) { detailsWidget->customSocketEdit->setEnabled(!on); } else if (sender() == detailsWidget->chkUseSocket) { detailsWidget->customSocketEdit->setEnabled( on && !detailsWidget->chkSocketDefault->isChecked()); detailsWidget->chkSocketDefault->setEnabled(on); } } //-------- //! @todo set proper help ctxt ID KexiDBConnectionDialog::KexiDBConnectionDialog(QWidget* parent, const KexiProjectData& data, const QString& shortcutFileName, const KGuiItem& acceptButtonGuiItem) : KDialog(parent) , d(new Private) { setWindowTitle(i18nc("@title:window", "Open Database")); d->tabWidget = new KexiDBConnectionTabWidget(this); d->tabWidget->setData(data, shortcutFileName); init(acceptButtonGuiItem); } KexiDBConnectionDialog::KexiDBConnectionDialog(QWidget* parent, const KexiDB::ConnectionData& data, const QString& shortcutFileName, const KGuiItem& acceptButtonGuiItem) : KDialog(parent) , d(new Private) { setWindowTitle(i18nc("@title:window", "Connect to a Database Server")); d->tabWidget = new KexiDBConnectionTabWidget(this); d->tabWidget->setData(data, shortcutFileName); init(acceptButtonGuiItem); } KexiDBConnectionDialog::~KexiDBConnectionDialog() { delete d; } void KexiDBConnectionDialog::init(const KGuiItem& acceptButtonGuiItem) { setObjectName("KexiDBConnectionDialog"); setButtons(KDialog::User1 | KDialog::Cancel | KDialog::Help); setButtonGuiItem(KDialog::User1, acceptButtonGuiItem.text().isEmpty() ? KGuiItem(i18n("&Open"), koIconName("document-open"), i18n("Open Database Connection")) : acceptButtonGuiItem ); setModal(true); setMainWidget(d->tabWidget); connect(this, SIGNAL(user1Clicked()), this, SLOT(accept())); connect(d->tabWidget->mainWidget, SIGNAL(saveChanges()), this, SIGNAL(saveChanges())); connect(d->tabWidget, SIGNAL(testConnection()), this, SIGNAL(testConnection())); adjustSize(); resize(width(), d->tabWidget->height()); if (d->tabWidget->mainWidget->connectionOnly()) d->tabWidget->mainWidget->driversCombo()->setFocus(); else if (d->tabWidget->mainWidget->nameCombo->currentText().isEmpty()) d->tabWidget->mainWidget->nameCombo->setFocus(); else if (d->tabWidget->mainWidget->userEdit->text().isEmpty()) d->tabWidget->mainWidget->userEdit->setFocus(); else if (d->tabWidget->mainWidget->passwordEdit->text().isEmpty()) d->tabWidget->mainWidget->passwordEdit->setFocus(); else //back d->tabWidget->mainWidget->nameCombo->setFocus(); } KexiProjectData KexiDBConnectionDialog::currentProjectData() { return d->tabWidget->currentProjectData(); } bool KexiDBConnectionDialog::savePasswordOptionSelected() const { return d->tabWidget->savePasswordOptionSelected(); } KexiDBConnectionWidget* KexiDBConnectionDialog::mainWidget() const { return d->tabWidget->mainWidget; } KexiDBConnectionWidgetDetails* KexiDBConnectionDialog::detailsWidget() const { return d->tabWidget->detailsWidget; } #include "kexidbconnectionwidget.moc"
donniexyz/calligra
kexi/widget/kexidbconnectionwidget.cpp
C++
gpl-2.0
17,168
package de.tum.bgu.msm.utils; import cern.colt.matrix.tdouble.DoubleMatrix2D; import org.matsim.core.utils.collections.Tuple; import java.util.*; public class DeferredAcceptanceMatching { public static Map<Integer, Integer> match(Collection<Integer> set1, Collection<Integer> set2, DoubleMatrix2D preferences) { Map<Integer, Integer> matches; do { matches = iteration(set1, set2, preferences); } while (matches.size() < set1.size()); return matches; } private static Map<Integer, Integer> iteration(Collection<Integer> set, Collection<Integer> set2, DoubleMatrix2D preferences) { Map<Integer, Integer> matches = new HashMap<>(); Map<Integer, List<Tuple<Integer, Double>>> offers = new HashMap<>(); for (int id: set) { double[] max = preferences.viewRow(id).getMaxLocation(); if (offers.containsKey((int) max[1])) { offers.get((int) max[1]).add(new Tuple<>(id, max[0])); } else { List<Tuple<Integer, Double>> list = new ArrayList<>(); list.add(new Tuple<>(id, max[0])); offers.put((int) max[1], list); } } for (Integer id : set2) { if (offers.containsKey(id)) { List<Tuple<Integer, Double>> personalOffers = offers.get(id); if (!personalOffers.isEmpty()) { Tuple<Integer, Double> maxOffer = personalOffers.stream().max(Comparator.comparing(Tuple::getSecond)).get(); matches.put(id, maxOffer.getFirst()); personalOffers.remove(maxOffer); for (Tuple<Integer, Double> offer : personalOffers) { preferences.setQuick(offer.getFirst(), id, 0); } } } } return matches; } }
msmobility/silo
siloCore/src/main/java/de/tum/bgu/msm/utils/DeferredAcceptanceMatching.java
Java
gpl-2.0
2,026
<?php namespace FluidTYPO3\Vhs\ViewHelpers\Context; /* * This file is part of the FluidTYPO3/Vhs 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 TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper; /** * ### Context: Get * * Returns the current application context which may include possible sub-contexts. * The application context can be 'Production', 'Development' or 'Testing'. * Additionally each context can be extended with custom sub-contexts like: 'Production/Staging' or * 'Production/Staging/Server1'. If no application context has been set by the configuration, then the * default context is 'Production'. * * #### Note about how to set the application context * * The context TYPO3 CMS runs in is specified through the environment variable TYPO3_CONTEXT. * It can be set by .htaccess or in the server configuration * * See: http://docs.typo3.org/typo3cms/CoreApiReference/ApiOverview/Bootstrapping/Index.html#bootstrapping-context */ class GetViewHelper extends AbstractViewHelper { /** * @return string */ public function render() { return (string) GeneralUtility::getApplicationContext(); } }
ahmedRguei/job
typo3conf/ext/vhs/Classes/ViewHelpers/Context/GetViewHelper.php
PHP
gpl-2.0
1,326
/* * Copyright (C) 2010 Michael Buesch <m@bues.ch> * * 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. */ #include "util.h" #include <time.h> #include <errno.h> #include <string.h> #include <iostream> void msleep(unsigned int msecs) { int err; struct timespec time; time.tv_sec = 0; while (msecs >= 1000) { time.tv_sec++; msecs -= 1000; } time.tv_nsec = msecs; time.tv_nsec *= 1000000; do { err = nanosleep(&time, &time); } while (err && errno == EINTR); if (err) { std::cerr << "nanosleep() failed with: " << strerror(errno) << std::endl; } }
mbuesch/pwrtray
tray/util.cpp
C++
gpl-2.0
1,046
<?php /* __ * _| |_ * ____ _ _ __ __ _ __ __ ____ |_ _| * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ __ |__| * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | _| |_ * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ |_ _| * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| |__| * * This program 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. * * @author PocketMine++ Team * @link http://pm-plus-plus.tk/ */ namespace pocketmine\entity; use pocketmine\inventory\InventoryHolder; use pocketmine\inventory\PlayerInventory; use pocketmine\item\Item as ItemItem; use pocketmine\nbt\NBT; use pocketmine\nbt\tag\ByteTag; use pocketmine\nbt\tag\CompoundTag; use pocketmine\nbt\tag\ListTag; use pocketmine\nbt\tag\ShortTag; use pocketmine\nbt\tag\StringTag; use pocketmine\network\NetworkTag; use pocketmine\network\protocol\AddPlayerPacket; use pocketmine\network\protocol\RemovePlayerPacket; use pocketmine\Player; use pocketmine\utils\UUID; class Human extends Creature implements ProjectileSource, InventoryHolder { const DATA_PLAYER_FLAG_SLEEP = 1; const DATA_PLAYER_FLAG_DEAD = 2; const DATA_PLAYER_FLAGS = 16; const DATA_PLAYER_BED_POSITION = 17; /** @var PlayerInventory */ protected $inventory; /** @var UUID */ protected $uuid; protected $rawUUID; public $width = 0.6; public $length = 0.6; public $height = 1.8; public $eyeHeight = 1.62; protected $skin; protected $skinname; protected $isOldClient; protected $isSlim = \false; protected $isTransparent = \false; public function getSkinData() { return $this->skin; } public function getSkinName() { return $this->skinname; } public function isOldClient() { return $this->isOldClient; } public function isSkinTransparent() { return $this->isTransparent; } public function isSkinSlim() { return $this->isSlim; } /** * @return UUID|null */ public function getUniqueId() { return $this->uuid; } /** * @return string */ public function getRawUniqueId() { return $this->rawUUID; } /** * @param string $str * @param bool $isSlim */ public function setSkin($str, $skinname = "", $isOldClient = \false, $isSlim = \false, $isTransparent = \null) { $this->skin = $str; $this->skinname = $skinname; $this->isOldClient = (bool)$isOldClient; $this->isTransparent = (bool)$isTransparent; $this->isSlim = (bool)$isSlim; } public function getInventory() { return $this->inventory; } protected function initEntity() { $this->setDataFlag(self::DATA_PLAYER_FLAGS, self::DATA_PLAYER_FLAG_SLEEP, \false); $this->setDataProperty(self::DATA_PLAYER_BED_POSITION, self::DATA_TYPE_POS, [0, 0, 0]); $this->inventory = new PlayerInventory($this); if ($this instanceof Player) { $this->addWindow($this->inventory, 0); } if (!($this instanceof Player)) { if (isset($this->namedtag->NameTag)) { $this->setNameTag($this->namedtag["NameTag"]); } if (isset($this->namedtag->Skin) and $this->namedtag->Skin instanceof CompoundTag) { $this->setSkin($this->namedtag->Skin["Data"], $this->namedtag->Skin["Slim"] > 0, $this->namedtag->Skin["Transparent"] > 0); } $this->uuid = UUID::fromData($this->getId(), $this->getSkinData(), $this->getNameTag()); } if (isset($this->namedtag->Inventory) and $this->namedtag->Inventory instanceof ListTag) { foreach ($this->namedtag->Inventory as $item) { if ($item["Slot"] >= 0 and $item["Slot"] < 9) { //Hotbar $this->inventory->setHotbarSlotIndex($item["Slot"], isset($item["TrueSlot"]) ? $item["TrueSlot"] : -1); } elseif ($item["Slot"] >= 100 and $item["Slot"] < 104) { //Armor $this->inventory->setItem($this->inventory->getSize() + $item["Slot"] - 100, NBT::getItemHelper($item)); } else { $this->inventory->setItem($item["Slot"] - 9, NBT::getItemHelper($item)); } } } parent::initEntity(); } public function getName() { return $this->getNameTag(); } public function getDrops() { $drops = []; if ($this->inventory !== \null) { foreach ($this->inventory->getContents() as $item) { $drops[] = $item; } } return $drops; } public function saveNBT() { parent::saveNBT(); $this->namedtag->Inventory = new ListTag("Inventory", []); $this->namedtag->Inventory->setTagType(NBT::TAG_Compound); if ($this->inventory !== \null) { for ($slot = 0; $slot < 9; ++$slot) { $hotbarSlot = $this->inventory->getHotbarSlotIndex($slot); if ($hotbarSlot !== -1) { $item = $this->inventory->getItem($hotbarSlot); if ($item->getId() !== 0 and $item->getCount() > 0) { $tag = NBT::putItemHelper($item, $slot); $tag->TrueSlot = new ByteTag("TrueSlot", $hotbarSlot); $this->namedtag->Inventory[$slot] = $tag; continue; } } $this->namedtag->Inventory[$slot] = new CompoundTag("", [ new ByteTag("Count", 0), new ShortTag("Damage", 0), new ByteTag("Slot", $slot), new ByteTag("TrueSlot", -1), new ShortTag("id", 0), ]); } //Normal inventory $slotCount = Player::SURVIVAL_SLOTS + 9; //$slotCount = (($this instanceof Player and ($this->gamemode & 0x01) === 1) ? Player::CREATIVE_SLOTS : Player::SURVIVAL_SLOTS) + 9; for ($slot = 9; $slot < $slotCount; ++$slot) { $item = $this->inventory->getItem($slot - 9); $this->namedtag->Inventory[$slot] = NBT::putItemHelper($item, $slot); } //Armor for ($slot = 100; $slot < 104; ++$slot) { $item = $this->inventory->getItem($this->inventory->getSize() + $slot - 100); if ($item instanceof ItemItem and $item->getId() !== ItemItem::AIR) { $this->namedtag->Inventory[$slot] = NBT::putItemHelper($item, $slot); } } } if (strlen($this->getSkinData()) > 0) { $this->namedtag->Skin = new CompoundTag("Skin", [ "Data" => new StringTag("Data", $this->getSkinData()), "Name" => new StringTag("Name", $this->getSkinName()), "Client" => new ByteTag("Clinet", $this->isOldClient() ? 1 : 0), "Slim" => new ByteTag("Slim", $this->isSkinSlim() ? 1 : 0), "Transparent" => new ByteTag("Transparent", $this->isSkinTransparent() ? 1 : 0) ]); } } public function spawnTo(Player $player) { if ($player !== $this and !isset($this->hasSpawned[$player->getLoaderId()])) { $this->hasSpawned[$player->getLoaderId()] = $player; if (strlen($this->skin) < 64 * 32 * 4) { throw new \InvalidStateException((new \ReflectionClass($this))->getShortName() . " must have a valid skin set"); } if ($this instanceof Player) { $this->server->updatePlayerListData($this->getUniqueId(), $this->getId(), $this->getName(), $this->isSlim, $this->skin, [$player], $this->isTransparent, $this->skinname); } $pk = new AddPlayerPacket(); $pk->uuid = $this->getUniqueId(); $pk->username = $this->getName(); $pk->eid = $this->getId(); $pk->x = $this->x; $pk->y = $this->y; $pk->z = $this->z; $pk->speedX = $this->motionX; $pk->speedY = $this->motionY; $pk->speedZ = $this->motionZ; $pk->yaw = $this->yaw; $pk->pitch = $this->pitch; $pk->item = $this->getInventory()->getItemInHand(); $pk->metadata = $this->dataProperties; $player->dataPacket($pk); $this->inventory->sendArmorContents($player); } } public function despawnFrom(Player $player) { if (isset($this->hasSpawned[$player->getLoaderId()])) { if ($this instanceof Player) { $this->server->removePlayerListData($this->getUniqueId(), [$player]); } $pk = new RemovePlayerPacket(); $pk->eid = $this->getId(); $pk->clientId = $this->getUniqueId(); $player->dataPacket($pk); unset($this->hasSpawned[$player->getLoaderId()]); } } public function close() { if (!$this->closed) { if (!($this instanceof Player) or $this->loggedIn) { foreach ($this->inventory->getViewers() as $viewer) { $viewer->removeWindow($this->inventory); } } parent::close(); } } }
PocketMinePlusPlus/PocketMinePlusPlus
src/pocketmine/entity/Human.php
PHP
gpl-2.0
9,941
<?php /** * @file * Contains \Drupal\lingotek\LingotekTranslatableEntity. */ namespace Drupal\lingotek; use Drupal\lingotek\LingotekInterface; use Drupal\Core\Entity\ContentEntityInterface; use Drupal\Core\Entity\ContentEntityTypeInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Class for wrapping entities with translation meta data and functions. */ class LingotekTranslatableEntity { /** * An entity instance. * * @var \Drupal\Core\Entity\ContentEntityInterface */ public $entity; /** * The title of the document */ protected $title; /* * The source locale code */ protected $locale; /** * Constructs a LingotekTranslatableEntity object. * * @param \Drupal\Core\Form\FormBuilderInterface $form_builder * The form builder. */ public function __construct(ContentEntityInterface $entity, LingotekInterface $lingotek) { $this->entity = $entity; $this->L = $lingotek; $this->translatable_field_types = array('text_with_summary', 'text'); $this->entity_manager = \Drupal::entityManager(); } public static function load(ContainerInterface $container, $entity) { $lingotek = $container->get('lingotek'); return new static($entity, $lingotek); } public static function loadByDocId($doc_id) { $entity = FALSE; $query = db_select('lingotek_entity_metadata', 'l')->fields('l', array('entity_id', 'entity_type')); $query->condition('entity_key', 'document_id'); $query->condition('value', $doc_id); $result = $query->execute(); if ($record = $result->fetchAssoc()) { $id = $record['entity_id']; $entity_type = $record['entity_type']; } if ($id && $entity_type) { $entity = self::loadById($id, $entity_type); } return $entity; } public static function loadById($id, $entity_type) { $container = \Drupal::getContainer(); $entity = entity_load($entity_type, $id); return self::load($container, $entity); } public function getSourceLocale() { $this->locale = LingotekLocale::convertDrupal2Lingotek($this->entity->language()->getId()); return $this->locale; } public function getSourceData() { // Logic adapted from Content Translation core module and TMGMT contrib // module for pulling translatable field info from content entities. $entity_type = $this->entity->getEntityType(); $storage_definitions = $entity_type instanceof ContentEntityTypeInterface ? $this->entity_manager->getFieldStorageDefinitions($entity_type->id()) : array(); $translatable_fields = array(); foreach ($this->entity->getFields(FALSE) as $field_name => $definition) { if (!empty($storage_definitions[$field_name]) && $storage_definitions[$field_name]->isTranslatable() && $field_name != $entity_type->getKey('langcode') && $field_name != $entity_type->getKey('default_langcode')) { $translatable_fields[$field_name] = $definition; } } $data = array(); $translation = $this->entity->getTranslation($this->entity->language()->getId()); foreach ($translatable_fields as $k => $definition) { $field = $translation->get($k); foreach ($field as $fkey => $fval) { foreach ($fval->getProperties() as $pkey => $pval) { // TODO: add a check for the fields that should be sent up for translation. $data[$k][$fkey][$pkey] = $pval->getValue(); } } } return $data; } public function saveTargetData($data, $locale) { // Logic adapted from TMGMT contrib module for saving // translated fields to their entity. /* @var \Drupal\Core\Entity\ContentEntityInterface $entity */ $lock = \Drupal::lock(); if ($lock->acquire(__FUNCTION__)) { $this->entity = entity_load($this->entity->getEntityTypeId(), $this->entity->id(), TRUE); $langcode = LingotekLocale::convertLingotek2Drupal($locale); if (!$langcode) { // TODO: log warning that downloaded translation's langcode is not enabled. $lock->release(__FUNCTION__); return FALSE; } // initialize the translation on the Drupal side, if necessary if (!$this->entity->hasTranslation($langcode)) { $this->entity->addTranslation($langcode, $this->entity->toArray()); } $translation = $this->entity->getTranslation($langcode); foreach ($data as $name => $field_data) { foreach ($field_data as $delta => $delta_data) { foreach ($delta_data as $property => $property_data) { if (method_exists($translation->get($name)->offsetGet($delta), "set")) { $translation->get($name)->offsetGet($delta)->set($property, $property_data); } } } } $translation->save(); $lock->release(__FUNCTION__); } else { $lock->wait(__FUNCTION__); } return $this; } public function hasEntityChanged() { $source_data = json_encode($this->getSourceData()); $hash = md5($source_data); $old_hash = $this->getHash(); if (!$old_hash || strcmp($hash, $old_hash)){ $this->setHash($hash); return true; } return false; } public function setProfileForNewlyIdentifiedEntities() { $current_profile = $this->L->get('translate.entity.' . $this->entity->getEntityTypeId() . '.' . $this->entity->bundle() . '.profile'); if ($current_profile == NULL) { $this->setProfile(Lingotek::PROFILE_AUTOMATIC); } else { $this->setProfile($current_profile); } } public function hasAutomaticUpload() { $profiles = $this->L->get('profile'); $lte_profile_id = $this->getProfile(); foreach ($profiles as $profile_id => $profile) { if ($profile['id'] == $lte_profile_id) { $lte_auto_upload = $profile['auto_upload']; break; } } return $lte_auto_upload; } public function hasAutomaticDownload() { $profiles = $this->L->get('profile'); $lte_profile_id = $this->getProfile(); foreach ($profiles as $profile_id => $profile) { if ($profile['id'] == $lte_profile_id) { $lte_auto_download = $profile['auto_download']; break; } } return $lte_auto_download; } public function getProfile() { return $this->getMetadata('profile'); } public function setProfile($profile) { return $this->setMetadata('profile', $profile); } public function getSourceStatus() { return $this->getMetadata('source_status'); } public function setSourceStatus($status) { return $this->setMetadata('source_status', $status); } public function getTargetStatus($locale) { return $this->getMetadata('target_status_' . $locale); } public function setTargetStatus($locale, $status) { return $this->setMetadata('target_status_' . $locale, $status); } public function getDocId() { return $this->getMetadata('document_id'); } public function setDocId($id) { return $this->setMetadata('document_id', $id); } public function getHash() { return $this->getMetadata('hash'); } public function setHash($hash) { return $this->setMetadata('hash', $hash); } public function setTargetStatuses($status) { $target_languages = \Drupal::languageManager()->getLanguages(); $entity_langcode = $this->entity->language()->getId(); foreach($target_languages as $langcode => $language) { $locale = LingotekLocale::convertDrupal2Lingotek($langcode); if ($langcode != $entity_langcode && $this->getTargetStatus($locale)) { $this->setTargetStatus($locale, $status); } } } /** * Gets a Lingotek metadata value for the given key. * * @param string $key * The key whose value should be returned. (Returns all * metadata values if not set.) * * @return string * The value for the specified key, if it exists, or * an array of values if no key is passed. */ public function getMetadata($key = NULL) { $metadata = array(); $query = db_select('lingotek_entity_metadata', 'meta') ->fields('meta') ->condition('entity_id', $this->entity->id()) ->condition('entity_type', $this->entity->getEntityTypeId()); if ($key) { $query->condition('entity_key', $key); } $results = $query->execute(); foreach ($results as $result) { $metadata[$result->entity_key] = $result->value; } if (empty($metadata)) { return NULL; } if ($key && !empty($metadata[$result->entity_key])) { return $metadata[$result->entity_key]; } return $metadata; } /** * Sets a Lingotek metadata value for this item. * * @param string $key * The key for a name/value pair. * @param string $value * The value for a name/value pair. */ public function setMetadata($key, $value) { $metadata = $this->getMetadata(); if (!isset($metadata[$key])) { db_insert('lingotek_entity_metadata') ->fields(array( 'entity_id' => $this->entity->id(), 'entity_type' => $this->entity->getEntityTypeId(), 'entity_key' => $key, 'value' => $value, 'created' => $this->entity->getCreatedTime(), 'modified' => $this->entity->getChangedTime(), )) ->execute(); } else { db_update('lingotek_entity_metadata') ->fields(array( 'value' => $value, 'created' => $this->entity->getCreatedTime(), 'modified' => $this->entity->getChangedTime(), )) ->condition('entity_id', $this->entity->id()) ->condition('entity_type', $this->entity->getEntityTypeId()) ->condition('entity_key', $key) ->execute(); } return $this; } public function deleteMetadata() { $metadata = $this->getMetadata(); foreach($metadata as $key => $value) { db_delete('lingotek_entity_metadata') ->condition('entity_id', $this->entity->id()) ->condition('entity_type', $this->entity->getEntityTypeId()) ->condition('entity_key', $key, 'LIKE') ->execute(); } } public function checkSourceStatus() { if ($this->L->documentImported($this->getDocId())) { $this->setSourceStatus(Lingotek::STATUS_CURRENT); return TRUE; } return FALSE; } public function checkTargetStatus($locale) { $current_status = $this->getTargetStatus($locale); if (($current_status == Lingotek::STATUS_PENDING) && $this->L->getDocumentStatus($this->getDocId())) { $current_status = Lingotek::STATUS_READY; $this->setTargetStatus($locale, $current_status); } return $current_status; } //perhaps this function should be protected public function addTarget($locale) { if ($this->L->addTarget($this->getDocId(), $locale)) { $this->setTargetStatus($locale, Lingotek::STATUS_PENDING); return TRUE; } return FALSE; } public function requestTranslations() { $target_languages = \Drupal::languageManager()->getLanguages(); $entity_langcode = $this->entity->language()->getId(); foreach($target_languages as $langcode => $language) { $locale = LingotekLocale::convertDrupal2Lingotek($langcode); if ($langcode != $entity_langcode) { $this->setTargetStatus($locale, Lingotek::STATUS_PENDING); $response = $this->addTarget($locale); } } } public function upload() { $source_data = json_encode($this->getSourceData()); $document_name = $this->entity->bundle() . ' (' . $this->entity->getEntityTypeId() . '): ' . $this->entity->label(); $doc_id = $this->L->uploadDocument($document_name, $source_data, $this->getSourceLocale()); if ($doc_id) { $this->setDocId($doc_id); $this->setSourceStatus(Lingotek::STATUS_PENDING); return $doc_id; } return FALSE; } public function delete() { if($this->L->deleteDocument($this->getDocId())) { return TRUE; } return FALSE; } public function update() { $source_data = json_encode($this->getSourceData()); if ($this->L->updateDocument($this->getDocId(), $source_data)){ $this->setSourceStatus(Lingotek::STATUS_PENDING); return TRUE; } return FALSE; } public function download($locale) { $data = $this->L->downloadDocument($this->getDocId(), $locale); if ($data) { $transaction = db_transaction(); try { $this->saveTargetData($data, $locale); $this->setTargetStatus($locale, Lingotek::STATUS_CURRENT); } catch(Exception $e) { $transaction->rollback(); } return TRUE; } return FALSE; } }
M1r1k/d8intranet
drupal/modules/contrib/lingotek/src/LingotekTranslatableEntity.php
PHP
gpl-2.0
12,705
//Pyjama compiler version:v1.5.3 package PyjamaCode.TestingDirectives.Sections; import pj.Pyjama; import pj.pr.*; import pj.PjRuntime; import pj.Pyjama; import pi.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import javax.swing.SwingUtilities; import java.lang.reflect.InvocationTargetException; import pj.pr.exceptions.OmpParallelRegionLocalCancellationException; public class section_positive_test1 { /** * return 2 because nomater how many threads are allowed there are only two section * */ public int[] parallel_sections(int threadNumber) {{ Pyjama.omp_set_num_threads(threadNumber); int[] array = new int[threadNumber]; int index = 0; /*OpenMP Parallel region (#0) -- START */ InternalControlVariables icv_previous__OMP_ParallelRegion_0 = PjRuntime.getCurrentThreadICV(); InternalControlVariables icv__OMP_ParallelRegion_0 = PjRuntime.inheritICV(icv_previous__OMP_ParallelRegion_0); int _threadNum__OMP_ParallelRegion_0 = icv__OMP_ParallelRegion_0.nthreads_var.get(icv__OMP_ParallelRegion_0.levels_var); ConcurrentHashMap<String, Object> inputlist__OMP_ParallelRegion_0 = new ConcurrentHashMap<String,Object>(); ConcurrentHashMap<String, Object> outputlist__OMP_ParallelRegion_0 = new ConcurrentHashMap<String,Object>(); inputlist__OMP_ParallelRegion_0.put("array",array); inputlist__OMP_ParallelRegion_0.put("index",index); _OMP_ParallelRegion_0 _OMP_ParallelRegion_0_in = new _OMP_ParallelRegion_0(_threadNum__OMP_ParallelRegion_0,icv__OMP_ParallelRegion_0,inputlist__OMP_ParallelRegion_0,outputlist__OMP_ParallelRegion_0); _OMP_ParallelRegion_0_in.runParallelCode(); array = (int[])outputlist__OMP_ParallelRegion_0.get("array"); index = (Integer)outputlist__OMP_ParallelRegion_0.get("index"); PjRuntime.recoverParentICV(icv_previous__OMP_ParallelRegion_0); RuntimeException OMP_ee_0 = (RuntimeException) _OMP_ParallelRegion_0_in.OMP_CurrentParallelRegionExceptionSlot.get(); if (OMP_ee_0 != null) {throw OMP_ee_0;} /*OpenMP Parallel region (#0) -- END */ return array; } } class _OMP_ParallelRegion_0{ private int OMP_threadNumber = 1; private InternalControlVariables icv; private ConcurrentHashMap<String, Object> OMP_inputList = new ConcurrentHashMap<String, Object>(); private ConcurrentHashMap<String, Object> OMP_outputList = new ConcurrentHashMap<String, Object>(); private ReentrantLock OMP_lock; private ParIterator<?> OMP__ParIteratorCreator; public AtomicReference<Throwable> OMP_CurrentParallelRegionExceptionSlot = new AtomicReference<Throwable>(null); //#BEGIN shared variables defined here int[] array = null; int index = 0; //#END shared variables defined here public _OMP_ParallelRegion_0(int thread_num, InternalControlVariables icv, ConcurrentHashMap<String, Object> inputlist, ConcurrentHashMap<String, Object> outputlist) { this.icv = icv; if ((false == Pyjama.omp_get_nested()) && (Pyjama.omp_get_level() > 0)) { this.OMP_threadNumber = 1; }else { this.OMP_threadNumber = thread_num; } this.OMP_inputList = inputlist; this.OMP_outputList = outputlist; icv.currentParallelRegionThreadNumber = this.OMP_threadNumber; icv.OMP_CurrentParallelRegionBarrier = new PjCyclicBarrier(this.OMP_threadNumber); //#BEGIN shared variables initialised here array = (int[])OMP_inputList.get("array"); index = (Integer)OMP_inputList.get("index"); //#END shared variables initialised here } private void updateOutputListForSharedVars() { //BEGIN update outputlist OMP_outputList.put("array",array); OMP_outputList.put("index",index); //END update outputlist } class MyCallable implements Callable<ConcurrentHashMap<String,Object>> { private int alias_id; private ConcurrentHashMap<String, Object> OMP_inputList; private ConcurrentHashMap<String, Object> OMP_outputList; //#BEGIN private/firstprivate reduction variables defined here //#END private/firstprivate reduction variables defined here MyCallable(int id, ConcurrentHashMap<String,Object> inputlist, ConcurrentHashMap<String,Object> outputlist){ this.alias_id = id; this.OMP_inputList = inputlist; this.OMP_outputList = outputlist; //#BEGIN firstprivate reduction variables initialised here //#END firstprivate reduction variables initialised here } @Override public ConcurrentHashMap<String,Object> call() { try { /****User Code BEGIN***/ /*OpenMP Work Share region (#0) -- START */ {//#BEGIN firstprivate lastprivate reduction variables defined and initialized here //#set implicit barrier here, otherwise unexpected initial value happens PjRuntime.setBarrier(); //#END firstprivate lastprivate reduction variables defined and initialized here try{ int _OMP_VANCY_ITERATOR_=0; int OMP_iterator = 0; int OMP_end = (int)((2)-(0))/(1); if (((2)-(0))%(1) == 0) { OMP_end = OMP_end - 1; } if (0 == Pyjama.omp_get_thread_num()) { PjRuntime.get_OMP_loopCursor().getAndSet(0);} PjRuntime.setBarrier(); while ((OMP_iterator = PjRuntime.get_OMP_loopCursor().getAndAdd(1)) <= OMP_end) { for (int OMP_local_iterator = OMP_iterator; OMP_local_iterator<OMP_iterator+1 && OMP_local_iterator<=OMP_end; OMP_local_iterator++){ _OMP_VANCY_ITERATOR_ = 0 + OMP_local_iterator * (1); switch(_OMP_VANCY_ITERATOR_) { case 0: { index = Pyjama.omp_get_thread_num(); array[index] += 1; } break; case 1: { index = Pyjama.omp_get_thread_num(); array[index] += 1; } break; default: break; }if (OMP_end == OMP_local_iterator) { //BEGIN lastprivate variables value set //END lastprivate variables value set } } } } catch (pj.pr.exceptions.OmpWorksharingLocalCancellationException wse){ } catch (Exception e){throw e;} //BEGIN reduction PjRuntime.reductionLockForWorksharing.lock(); PjRuntime.reductionLockForWorksharing.unlock();//END reduction PjRuntime.setBarrier(); } PjRuntime.setBarrier(); PjRuntime.reset_OMP_orderCursor(); /*OpenMP Work Share region (#0) -- END */ /****User Code END***/ //BEGIN reduction procedure //END reduction procedure PjRuntime.setBarrier(); } catch (OmpParallelRegionLocalCancellationException e) { PjRuntime.decreaseBarrierCount(); } catch (Exception e) { PjRuntime.decreaseBarrierCount(); PjExecutor.cancelCurrentThreadGroup(); OMP_CurrentParallelRegionExceptionSlot.compareAndSet(null, e); } if (0 == this.alias_id) { updateOutputListForSharedVars(); } return null; } } public void runParallelCode() { for (int i = 1; i <= this.OMP_threadNumber-1; i++) { Callable<ConcurrentHashMap<String,Object>> slaveThread = new MyCallable(i, OMP_inputList, OMP_outputList); PjRuntime.submit(i, slaveThread, icv); } Callable<ConcurrentHashMap<String,Object>> masterThread = new MyCallable(0, OMP_inputList, OMP_outputList); PjRuntime.getCurrentThreadICV().currentThreadAliasID = 0; try { masterThread.call(); } catch (Exception e) { e.printStackTrace(); } } } }
ParallelAndReconfigurableComputing/Pyjama
test/PyjamaCode/TestingDirectives/Sections/section_positive_test1.java
Java
gpl-2.0
10,076
<?php /* +------------------------------------------------ | TBDev.net BitTorrent Tracker PHP | ============================================= | by CoLdFuSiOn | (c) 2003 - 2009 TBDev.Net | http://www.tbdev.net | ============================================= | svn: http://sourceforge.net/projects/tbdevnet/ | Licence Info: GPL +------------------------------------------------ | $Date$ | $Revision$ | $Author$ | $URL$ +------------------------------------------------ */ error_reporting(E_ALL); define('SQL_DEBUG', 2); /* Compare php version for date/time stuff etc! */ if (version_compare(PHP_VERSION, "5.1.0", ">=")) date_default_timezone_set('Europe/Bucharest'); define('TIME_NOW', time()); $TBDEV['time_adjust'] = 0; $TBDEV['time_offset'] = '0'; $TBDEV['time_use_relative'] = 1; $TBDEV['time_use_relative_format'] = '{--}, h:i A'; $TBDEV['time_joined'] = 'j-F y'; $TBDEV['time_short'] = 'jS F Y - h:i A'; $TBDEV['time_long'] = 'M j Y, h:i A'; $TBDEV['time_tiny'] = ''; $TBDEV['time_date'] = ''; // DB setup // FYNNON FUCKWIT FRENCH RETARD /* $mysql_host = "mysql3.000webhost.com"; $mysql_database = "a2547881_pizda"; $mysql_user = "a2547881_pizda"; $mysql_password = "832LGAf8dYcErwhf"; */ $TBDEV['mysql_host'] = "cancer"; $TBDEV['mysql_user'] = "you_wish"; $TBDEV['mysql_pass'] = "you_wish"; $TBDEV['mysql_db'] = "cancer_live"; // Cookie setup $TBDEV['cookie_prefix'] = 'xleech'; // This allows you to have multiple trackers, eg for demos, testing etc. $TBDEV['cookie_path'] = ''; // ATTENTION: You should never need this unless the above applies eg: /tbdev $TBDEV['cookie_domain'] = '.xleech.in'; // set to eg: .somedomain.com or is subdomain set to: .sub.somedomain.com $TBDEV['site_online'] = 1; $TBDEV['tracker_post_key'] = 'ioyt57i6hnnb98'; $TBDEV['max_torrent_size'] = 1000000; $TBDEV['announce_interval'] = 60 * 30; $TBDEV['signup_timeout'] = 86400 * 3; $TBDEV['minvotes'] = 1; $TBDEV['max_dead_torrent_time'] = 31 * 3600; // Max users on site $TBDEV['maxusers'] = 5000; // LoL Who we kiddin' here? if ( strtoupper( substr(PHP_OS, 0, 3) ) == 'WIN' ) { $file_path = str_replace( "\\", "/", dirname(__FILE__) ); $file_path = str_replace( "/include", "", $file_path ); } else { $file_path = dirname(__FILE__); $file_path = str_replace( "/include", "", $file_path ); } define('ROOT_PATH', $file_path); $TBDEV['torrent_dir'] = ROOT_PATH . '/torrents'; # must be writable for httpd user # the first one will be displayed on the pages $TBDEV['announce_urls'] = array(); $TBDEV['announce_urls'][] = "http://tracker.xleech.in/announce.php"; //$TBDEV['announce_urls'] = "http://localhost:2710/announce"; //$TBDEV['announce_urls'] = "http://domain.com:83/announce.php"; if ($_SERVER["HTTP_HOST"] == "") $_SERVER["HTTP_HOST"] = $_SERVER["SERVER_NAME"]; $TBDEV['baseurl'] = "http://" . $_SERVER["HTTP_HOST"].""; /* ## DO NOT UNCOMMENT THIS: IT'S FOR LATER USE! $host = getenv( 'SERVER_NAME' ); $script = getenv( 'SCRIPT_NAME' ); $script = str_replace( "\\", "/", $script ); if( $host AND $script ) { $script = str_replace( '/index.php', '', $script ); $TBDEV['baseurl'] = "http://{$host}{$script}"; } */ //set this to true to make this a tracker that only registered users may use //$TBDEV['membersonly'] = 1; //deprecated no longer needed //maximum number of peers (seeders+leechers) allowed before torrents starts to be deleted to make room... //set this to something high if you don't require this feature //$TBDEV['peerlimit'] = 50000; //deprecated. no longer used. // Email for sender/return path. $TBDEV['site_email'] = "support@xleech.in"; $TBDEV['site_name'] = "xLeech"; $TBDEV['language'] = 'en'; $TBDEV['msg_alert'] = 0; // saves a query when off $TBDEV['autoclean_interval'] = 900; $TBDEV['sql_error_log'] = ROOT_PATH.'/logs/sql_err_'.date("M_D_Y").'.log'; $TBDEV['pic_base_url'] = "./pic/"; $TBDEV['stylesheet'] = "./1.css"; $TBDEV['readpost_expiry'] = 14 * 86400; // 14 days //set this to size of user avatars $TBDEV['av_img_height'] = 150; $TBDEV['av_img_width'] = 250; $TBDEV['allowed_ext'] = array('image/gif', 'image/png', 'image/jpeg'); // Invites $TBDEV['invites'] = 3500; // set this to what you want $TBDEV['openreg'] = true; //==true=open, false = closed // wait time $TBDEV['user_ratios'] = 0; // Set this to the line break character sequence of your system //$TBDEV['linebreak'] = "\r\n"; // not used at present. define ('UC_USER', 0); define ('UC_POWER_USER', 1); define ('UC_VIP', 2); define ('UC_UPLOADER', 3); define ('UC_MODERATOR', 4); define ('UC_ADMINISTRATOR', 5); define ('UC_SYSOP', 6); //Do not modify -- versioning system //This will help identify code for support issues at tbdev.net define ('TBVERSION','TBDev_2009_svn'); ?>
gitrab/xleech
include/config.php
PHP
gpl-2.0
4,963
<?php /** * @package Prism * @subpackage Constants * @author Todor Iliev * @copyright Copyright (C) 2016 Todor Iliev <todor@itprism.com>. All rights reserved. * @license GNU General Public License version 3 or later; see LICENSE.txt */ namespace Prism; defined('JPATH_PLATFORM') or die; /** * Prism constants * * @package Prism * @subpackage Constants */ class Constants { // States const PUBLISHED = 1; const UNPUBLISHED = 0; const TRASHED = -2; const AWAITING_APPROVAL = -3; const APPROVED = 1; const NOT_APPROVED = 0; const FEATURED = 1; const NOT_FEATURED = 0; const ENABLED = 1; const DISABLED = 0; const VERIFIED = 1; const NOT_VERIFIED = 0; const FOLLOWED = 1; const UNFOLLOWED = 0; const DISPLAY = 1; const DO_NOT_DISPLAY = 0; const INACTIVE = 0; const ACTIVE = 1; // Mail modes - html and plain text. const MAIL_MODE_HTML = true; const MAIL_MODE_PLAIN = false; // Logs const ENABLE_SYSTEM_LOG = true; const DISABLE_SYSTEM_LOG = false; // Notification statuses const SENT = 1; const NOT_SENT = 0; const READ = 1; const NOT_READ = 0; // Categories const CATEGORY_ROOT = 1; // Return values const RETURN_DEFAULT = 1; const DO_NOT_RETURN_DEFAULT = 0; // State default const STATE_DEFAULT = 1; const STATE_NOT_DEFAULT = 0; // State replace const REPLACE = 1; const DO_NOT_REPLACE = 0; // Access state const ACCESS_PRIVATE = 0; const ACCESS_PUBLIC = 1; const ACCESS_FOLLOWERS = 2; const ACCESS_FRIENDS = 3; const ACCESS_FOLLOWERS_FRIENDS = 5; const ORDER_MOST_RECENT_FIRST = 'rdate'; const ORDER_OLDEST_FIRST = 'date'; const ORDER_TITLE_ALPHABETICAL = 'alpha'; const ORDER_TITLE_REVERSE_ALPHABETICAL = 'ralpha'; const ORDER_AUTHOR_ALPHABETICAL = 'author'; const ORDER_AUTHOR_REVERSE_ALPHABETICAL = 'rauthor'; const ORDER_MOST_HITS = 'hits'; const ORDER_LEAST_HITS = 'rhits'; const ORDER_RANDOM_ORDER = 'random'; const ORDER_ITEM_MANAGER_ORDER = 'order'; }
ITPrism/GamificationDistribution
libraries/Prism/Constants.php
PHP
gpl-2.0
2,208
package com.fasterxml.jackson.databind.deser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.util.AccessPattern; /** * Helper interface implemented by classes that are to be used as * null providers during deserialization. Most importantly implemented by * {@link com.fasterxml.jackson.databind.JsonDeserializer} (as a mix-in * interface), but also by converters used to support more configurable * null replacement. * * @since 2.9 */ public interface NullValueProvider { /** * Method called to possibly convert incoming `null` token (read via * underlying streaming input source) into other value of type accessor * supports. May return `null`, or value compatible with type binding. *<p> * NOTE: if {@link #getNullAccessPattern()} returns `ALWAYS_NULL` or * `CONSTANT`, this method WILL NOT use provided `ctxt` and it may thus * be passed as `null`. */ public Object getNullValue(DeserializationContext ctxt) throws JsonMappingException; /** * Accessor that may be used to determine if and when provider must be called to * access null replacement value. */ public AccessPattern getNullAccessPattern(); }
lamsfoundation/lams
3rdParty_sources/jackson/com/fasterxml/jackson/databind/deser/NullValueProvider.java
Java
gpl-2.0
1,303
/** * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.iucn.whp.dbservice; import com.liferay.portal.NoSuchModelException; /** * @author alok.sen */ public class NoSuch_sites_countryException extends NoSuchModelException { public NoSuch_sites_countryException() { super(); } public NoSuch_sites_countryException(String msg) { super(msg); } public NoSuch_sites_countryException(String msg, Throwable cause) { super(msg, cause); } public NoSuch_sites_countryException(Throwable cause) { super(cause); } }
iucn-whp/world-heritage-outlook
portlets/iucn-dbservice-portlet/docroot/WEB-INF/service/com/iucn/whp/dbservice/NoSuch_sites_countryException.java
Java
gpl-2.0
1,074
namespace Sdl.Community.AdvancedDisplayFilter.Models { public class SegmentRange { public int Min { get; set; } public int Max { get; set; } } }
sdl/Sdl-Community
AdvancedDisplayFilter/Models/SegmentRange.cs
C#
gpl-2.0
158
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hotswap.agent.util.spring.io.resource; import java.io.IOException; import java.io.OutputStream; /** * Extended interface for a resource that supports writing to it. Provides an * {@link #getOutputStream() OutputStream accessor}. * * @author Juergen Hoeller * @since 3.1 * @see java.io.OutputStream */ public interface WritableResource extends Resource { /** * Return whether the contents of this resource can be modified, e.g. via * {@link #getOutputStream()} or {@link #getFile()}. * <p> * Will be {@code true} for typical resource descriptors; note that actual * content writing may still fail when attempted. However, a value of * {@code false} is a definitive indication that the resource content cannot * be modified. * * @see #getOutputStream() * @see #isReadable() */ boolean isWritable(); /** * Return an {@link OutputStream} for the underlying resource, allowing to * (over-)write its content. * * @throws IOException * if the stream could not be opened * @see #getInputStream() */ OutputStream getOutputStream() throws IOException; }
HotswapProjects/HotswapAgent
hotswap-agent-core/src/main/java/org/hotswap/agent/util/spring/io/resource/WritableResource.java
Java
gpl-2.0
1,809
/** * @author Marc Moerig * @version 3.0 */ #include <iostream> #include <fstream> #include "../../algorithm/nb_iter/iterate.hpp" #include "../../lisa/ctrlpara.hpp" #include "travel_graph.hpp" #include "travel_neighbourhood.hpp" using namespace std; //************************************************************************** int main(int argc, char *argv[]){ // print any errors G_ExceptionList.set_output_to_cout(); // arguments ? if(argc != 3){ std::cout << "Usage: " << argv[0] << " [input file] [output file]" << std::endl; exit(1); } // open input file std::ifstream i_strm(argv[1]); // file exists ? if(!i_strm){ std::cout << "File '"<< argv[1] <<"' not found. Exiting."<< std::endl; exit(1); } // create an object holding parameters and read it Lisa_ControlParameters param; i_strm >> param; // parse our parameters string method_in = "II"; int METHOD = II; // which algorithm: II,SA,SA_anti,TA,TS string NGBH = "API"; // which neighbourhood: API,RPI int STEPS = 100; //int NUMB_STUCKS = 999999; //double ABORT_BOUND = 1; //string ngbh_type_in = "ENUM"; //int NGBH_TYPE = ENUM; // ENUM,RAND .. only for II,TS //int PROB = 50; // 0..100 only for SA,SA_anti,TA //int MAX_STUCK = 2000; // only for SA,SA_anti,TA //int TABU_LENGTH = 1; // length of tabulist ... only TS //int NUMB_NGB = 1; // how many NGB's to generate in each step ... only TS // algorithm if (!param.defined("METHOD")){ G_ExceptionList.lthrow("You must define an algorithm (METHOD) in the input file."); exit(7); }else{ method_in = param.get_string("METHOD"); if(method_in=="II") METHOD = II; else if(method_in=="SA") METHOD = SA; else if(method_in=="TS") METHOD = TS ; else if(method_in=="TA") METHOD = TA; else { std::cout << method_in << " is not a valid algorithm." << std::endl; std::cout << "Must be II,SA,TS or TA." << std::endl; exit(7); } } // neighbourhood if (!param.defined("NGBH")){ G_ExceptionList.lthrow("You must define a neighbourhood (NGBH) in the input file."); exit(7); }else{ NGBH = param.get_string("NGBH"); if(NGBH!="API"&&NGBH!="RPI"){ std::cout << NGBH << " is not a valid Neighbourhood." << std::endl; std::cout << "Must be API or RPI." << std::endl; exit(7); } } //steps if (!param.defined("STEPS")){ G_ExceptionList.lthrow("You must define a number of steps (STEPS) in the input file."); exit(7); }else{ STEPS = param.get_long("STEPS"); } // create an object holding our problem and read it Travel_Graph tr1; i_strm >> tr1; // close input stream/file i_strm.close(); // create neighbourhood object Travel_RPI_Neighbourhood* nbh=0; if(NGBH=="API") nbh = new Travel_API_Neighbourhood(&tr1); else if(NGBH=="RPI") nbh = new Travel_RPI_Neighbourhood(&tr1); // create iteration object Lisa_Iter* it=0; // init algorithm type and parameters if(METHOD==II) it = new Lisa_IterativeImprovement(&param); else if(METHOD==SA) it = new Lisa_OldSimulatedAnnealing(&param); else if(METHOD==TA) it = new Lisa_ThresholdAccepting(&param); else if(METHOD==TS) it = new Lisa_TabuSearch(&param); //go for it ;) it->iterate(nbh,1,STEPS); delete it; // put our best result back into our problem object nbh->write_best(); // open file for output std::ofstream o_strm(argv[2]); // done ? if(!o_strm){ std::cout << "Could not open file '" << argv[2] << "'. Exiting." << std::endl; exit(1); } // write parameters so we can use the outputfile as inputfile again o_strm << param; // write problem .. which now contains a solution o_strm << tr1; // cleanup delete nbh; // done return 0; } //**************************************************************************
hojsimpson/LiSA
src/sample/travel/travel.cpp
C++
gpl-2.0
3,906
/* * Copyright (c) 2012-2013 Open Source Community - <http://www.peerfact.org> * Copyright (c) 2011-2012 University of Paderborn - UPB * Copyright (c) 2005-2011 KOM - Multimedia Communications Lab * * This file is part of PeerfactSim.KOM. * * PeerfactSim.KOM 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. * * PeerfactSim.KOM 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 PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>. * */ package org.peerfact.impl.application.infodissemination.moveModels; import java.awt.Point; import org.peerfact.impl.application.infodissemination.IDOApplication; /** * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * This part of the Simulator is not maintained in the current version of * PeerfactSim.KOM. There is no intention of the authors to fix this * circumstances, since the changes needed are huge compared to overall benefit. * * If you want it to work correctly, you are free to make the specific changes * and provide it to the community. * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!! * * This interface is used to allow the interchangeability of the move model for * the peers. * * @author Julius Rueckert <peerfact@kom.tu-darmstadt.de> * @version 01/06/2011 * */ public interface IMoveModel { public Point getNextPosition(IDOApplication app); }
flyroom/PeerfactSimKOM_Clone
src/org/peerfact/impl/application/infodissemination/moveModels/IMoveModel.java
Java
gpl-2.0
1,841
/****************************************************************************** * Icinga 2 * * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software Foundation * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************/ #include "cli/pkirequestcommand.hpp" #include "cli/pkiutility.hpp" #include "base/logger.hpp" #include "base/tlsutility.hpp" #include <iostream> using namespace icinga; namespace po = boost::program_options; REGISTER_CLICOMMAND("pki/request", PKIRequestCommand); String PKIRequestCommand::GetDescription(void) const { return "Sends a PKI request to Icinga 2."; } String PKIRequestCommand::GetShortDescription(void) const { return "requests a certificate"; } void PKIRequestCommand::InitParameters(boost::program_options::options_description& visibleDesc, boost::program_options::options_description& hiddenDesc) const { visibleDesc.add_options() ("key", po::value<std::string>(), "Key file path (input)") ("cert", po::value<std::string>(), "Certificate file path (input + output)") ("ca", po::value<std::string>(), "CA file path (output)") ("trustedcert", po::value<std::string>(), "Trusted certificate file path (input)") ("host", po::value<std::string>(), "Icinga 2 host") ("port", po::value<std::string>(), "Icinga 2 port") ("ticket", po::value<std::string>(), "Icinga 2 PKI ticket"); } std::vector<String> PKIRequestCommand::GetArgumentSuggestions(const String& argument, const String& word) const { if (argument == "key" || argument == "cert" || argument == "ca" || argument == "trustedcert") return GetBashCompletionSuggestions("file", word); else if (argument == "host") return GetBashCompletionSuggestions("hostname", word); else if (argument == "port") return GetBashCompletionSuggestions("service", word); else return CLICommand::GetArgumentSuggestions(argument, word); } /** * The entry point for the "pki request" CLI command. * * @returns An exit status. */ int PKIRequestCommand::Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const { if (!vm.count("host")) { Log(LogCritical, "cli", "Icinga 2 host (--host) must be specified."); return 1; } if (!vm.count("key")) { Log(LogCritical, "cli", "Key input file path (--key) must be specified."); return 1; } if (!vm.count("cert")) { Log(LogCritical, "cli", "Certificate output file path (--cert) must be specified."); return 1; } if (!vm.count("ca")) { Log(LogCritical, "cli", "CA certificate output file path (--ca) must be specified."); return 1; } if (!vm.count("trustedcert")) { Log(LogCritical, "cli", "Trusted certificate input file path (--trustedcert) must be specified."); return 1; } if (!vm.count("ticket")) { Log(LogCritical, "cli", "Ticket (--ticket) must be specified."); return 1; } String port = "5665"; if (vm.count("port")) port = vm["port"].as<std::string>(); return PkiUtility::RequestCertificate(vm["host"].as<std::string>(), port, vm["key"].as<std::string>(), vm["cert"].as<std::string>(), vm["ca"].as<std::string>(), GetX509Certificate(vm["trustedcert"].as<std::string>()), vm["ticket"].as<std::string>()); }
daniilyar/icinga2
lib/cli/pkirequestcommand.cpp
C++
gpl-2.0
4,399
/*************************************************************************** gmainwindow.cpp (c) 2004-2006 - Daniel Campos Fernández <dcamposf@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, 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 <ctype.h> #include <time.h> #include "widgets.h" #ifdef GDK_WINDOWING_X11 #include <X11/extensions/shape.h> #endif #include "x11.h" #include "sm/sm.h" #include "gapplication.h" #include "gdesktop.h" #include "gkey.h" #include "gmenu.h" #include "gmessage.h" #include "gdialog.h" #include "gmouse.h" #include "gmainwindow.h" static gboolean cb_frame(GtkWidget *widget,GdkEventWindowState *event,gMainWindow *data) { data->performArrange(); data->emit(SIGNAL(data->onState)); return false; } static gboolean cb_show(GtkWidget *widget, gMainWindow *data) { data->emitOpen(); if (data->opened) { data->setGeometryHints(); //data->performArrange(); data->emitResize(); data->emit(SIGNAL(data->onShow)); data->_not_spontaneous = false; } return false; } static gboolean cb_hide(GtkWidget *widget, gMainWindow *data) { data->emit(SIGNAL(data->onHide)); data->_not_spontaneous = false; return false; //if (data == gDesktop::activeWindow()) // gMainWindow::setActiveWindow(NULL); } static gboolean cb_close(GtkWidget *widget,GdkEvent *event,gMainWindow *data) { if (!gMainWindow::_current || data == gMainWindow::_current) data->doClose(); return true; } static gboolean cb_configure(GtkWidget *widget, GdkEventConfigure *event, gMainWindow *data) { gint x, y; if (data->opened) { if (data->isTopLevel()) { gtk_window_get_position(GTK_WINDOW(data->border), &x, &y); } else { x = event->x; y = event->y; } //fprintf(stderr, "cb_configure: %s: (%d %d %d %d) -> (%d %d %d %d) window = %p resized = %d\n", data->name(), data->bufX, data->bufY, data->bufW, data->bufH, x, y, event->width, event->height, event->window, data->_resized); if (x != data->bufX || y != data->bufY) { data->bufX = x; data->bufY = y; if (data->onMove) data->onMove(data); } if ((event->width != data->bufW) || (event->height != data->bufH) || (data->_resized) || !event->window) { data->_resized = false; data->bufW = event->width; data->bufH = event->height; data->emitResize(); } } return false; } #ifdef GTK3 static gboolean cb_draw(GtkWidget *wid, cairo_t *cr, gMainWindow *data) { if (data->isTransparent()) { if (data->background() == COLOR_DEFAULT) gt_cairo_set_source_color(cr, 0xFF000000); else gt_cairo_set_source_color(cr, data->background()); cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE); cairo_paint(cr); } if (data->_picture) { cairo_pattern_t *pattern; pattern = cairo_pattern_create_for_surface(data->_picture->getSurface()); cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT); cairo_set_source(cr, pattern); cairo_paint(cr); cairo_pattern_destroy(pattern); } return false; } #else static gboolean cb_expose(GtkWidget *wid, GdkEventExpose *e, gMainWindow *data) { bool draw_bg = data->isTransparent(); bool draw_pic = data->_picture; if (!draw_bg && !draw_pic) return false; cairo_t *cr = gdk_cairo_create(gtk_widget_get_window(wid)); if (draw_bg) { if (data->background() == COLOR_DEFAULT) gt_cairo_set_source_color(cr, 0xFF000000); else gt_cairo_set_source_color(cr, data->background()); cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE); cairo_paint(cr); } if (draw_pic) { cairo_pattern_t *pattern; gdk_cairo_region(cr, e->region); cairo_clip(cr); pattern = cairo_pattern_create_for_surface(data->_picture->getSurface()); cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT); cairo_set_source(cr, pattern); cairo_paint(cr); cairo_pattern_destroy(pattern); } cairo_destroy(cr); return false; } #endif GList *gMainWindow::windows = NULL; gMainWindow *gMainWindow::_active = NULL; gMainWindow *gMainWindow::_current = NULL; void gMainWindow::initialize() { //fprintf(stderr, "new window: %p in %p\n", this, parent()); opened = false; sticky = false; persistent = false; stack = 0; _type = 0; _mask = false; _masked = false; _resized = false; accel = NULL; _default = NULL; _cancel = NULL; menuBar = NULL; layout = NULL; top_only = false; _icon = NULL; _picture = NULL; focus = 0; _closing = false; _title = NULL; _not_spontaneous = false; _skip_taskbar = false; _current = NULL; _style = NULL; _xembed = false; _activate = false; _hidden = false; _hideMenuBar = false; _showMenuBar = true; _popup = false; _maximized = _minimized = _fullscreen = false; _resize_last_w = _resize_last_h = -1; _min_w = _min_h = 0; _transparent = false; _utility = false; onOpen = NULL; onShow = NULL; onHide = NULL; onMove = NULL; onResize = NULL; onActivate = NULL; onDeactivate = NULL; onState = NULL; accel = gtk_accel_group_new(); } void gMainWindow::initWindow() { //resize(200,150); if (!isTopLevel()) { g_signal_connect(G_OBJECT(border), "configure-event", G_CALLBACK(cb_configure), (gpointer)this); g_signal_connect_after(G_OBJECT(border), "map", G_CALLBACK(cb_show), (gpointer)this); g_signal_connect(G_OBJECT(border),"unmap",G_CALLBACK(cb_hide),(gpointer)this); //g_signal_connect_after(G_OBJECT(border), "size-allocate", G_CALLBACK(cb_configure), (gpointer)this); ON_DRAW_BEFORE(widget, this, cb_expose, cb_draw); gtk_widget_add_events(border, GDK_STRUCTURE_MASK); } else { //g_signal_connect(G_OBJECT(border),"size-request",G_CALLBACK(cb_realize),(gpointer)this); g_signal_connect(G_OBJECT(border), "show",G_CALLBACK(cb_show),(gpointer)this); g_signal_connect(G_OBJECT(border), "hide",G_CALLBACK(cb_hide),(gpointer)this); g_signal_connect(G_OBJECT(border), "configure-event",G_CALLBACK(cb_configure),(gpointer)this); g_signal_connect(G_OBJECT(border), "delete-event",G_CALLBACK(cb_close),(gpointer)this); g_signal_connect(G_OBJECT(border), "window-state-event",G_CALLBACK(cb_frame),(gpointer)this); gtk_widget_add_events(widget,GDK_BUTTON_MOTION_MASK); ON_DRAW_BEFORE(border, this, cb_expose, cb_draw); } gtk_window_add_accel_group(GTK_WINDOW(topLevel()->border), accel); have_cursor = true; //parent() == 0 && !_xembed; } #if 0 //def GTK3 static void (*old_fixed_get_preferred_width)(GtkWidget *, gint *, gint *); static void (*old_fixed_get_preferred_height)(GtkWidget *, gint *, gint *); static void gtk_fixed_get_preferred_width(GtkWidget *widget, gint *minimum_size, gint *natural_size) { (*old_fixed_get_preferred_width)(widget, minimum_size, natural_size); *minimum_size = 0; } static void gtk_fixed_get_preferred_height(GtkWidget *widget, gint *minimum_size, gint *natural_size) { (*old_fixed_get_preferred_height)(widget, minimum_size, natural_size); *minimum_size = 0; } #endif gMainWindow::gMainWindow(int plug) : gContainer(NULL) { initialize(); g_typ = Type_gMainWindow; windows = g_list_append(windows, (gpointer)this); _xembed = plug != 0; if (_xembed) border = gtk_plug_new(plug); else border = gtk_window_new(GTK_WINDOW_TOPLEVEL); widget = gtk_fixed_new(); //gtk_layout_new(0,0); #if 0 //def GTK3 static bool patch = FALSE; if (!patch) { GtkWidgetClass *klass; klass = (GtkWidgetClass *)GTK_FIXED_GET_CLASS(widget); old_fixed_get_preferred_width = klass->get_preferred_width; klass->get_preferred_width = gtk_fixed_get_preferred_width; old_fixed_get_preferred_height = klass->get_preferred_height; klass->get_preferred_height = gtk_fixed_get_preferred_height; /*klass = (GtkWidgetClass *)GTK_FIXED_GET_CLASS(border); old_window_get_preferred_width = klass->get_preferred_width; klass->get_preferred_width = gtk_window_get_preferred_width; old_window_get_preferred_height = klass->get_preferred_height; klass->get_preferred_height = gtk_window_get_preferred_height;*/ patch = true; } #endif realize(false); initWindow(); gtk_widget_realize(border); gtk_widget_show(widget); gtk_widget_set_size_request(border, 1, 1); setCanFocus(false); } gMainWindow::gMainWindow(gContainer *par) : gContainer(par) { initialize(); g_typ = Type_gMainWindow; border = gtk_alignment_new(0,0,1,1); //gtk_fixed_new(); //gtk_event_box_new(); widget = gtk_fixed_new(); realize(false); initWindow(); setCanFocus(false); } gMainWindow::~gMainWindow() { //fprintf(stderr, "delete window %p %s\n", this, name()); if (opened) { emit(SIGNAL(onClose)); opened = false; if (GTK_IS_WINDOW(border) && isModal()) gApplication::exitLoop(this); } gPicture::assign(&_picture); gPicture::assign(&_icon); if (_title) g_free(_title); g_object_unref(accel); if (_style) g_object_unref(_style); if (_active == this) _active = NULL; if (gApplication::mainWindow() == this) gApplication::setMainWindow(NULL); windows = g_list_remove(windows, (gpointer)this); } bool gMainWindow::getSticky() { return sticky; } int gMainWindow::getStacking() { return stack; } void gMainWindow::setSticky(bool vl) { sticky=vl; if (!isTopLevel()) return; if (vl) gtk_window_stick(GTK_WINDOW(border)); else gtk_window_unstick(GTK_WINDOW(border)); } void gMainWindow::setStacking(int vl) { stack=vl; if (!isTopLevel()) return; switch (vl) { case 0: gtk_window_set_keep_below(GTK_WINDOW(border),FALSE); gtk_window_set_keep_above(GTK_WINDOW(border),FALSE); break; case 1: gtk_window_set_keep_below(GTK_WINDOW(border),FALSE); gtk_window_set_keep_above(GTK_WINDOW(border),TRUE); break; case 2: gtk_window_set_keep_above(GTK_WINDOW(border),FALSE); gtk_window_set_keep_below(GTK_WINDOW(border),TRUE); break; } } void gMainWindow::setRealBackground(gColor color) { if (!_picture) { gControl::setRealBackground(color); gMenu::updateColor(this); } } void gMainWindow::setRealForeground(gColor color) { gControl::setRealForeground(color); gMenu::updateColor(this); } void gMainWindow::move(int x, int y) { gint ox, oy; if (isTopLevel()) { if (x == bufX && y == bufY) return; #ifdef GDK_WINDOWING_X11 gdk_window_get_origin(gtk_widget_get_window(border), &ox, &oy); ox = x + ox - bufX; oy = y + oy - bufY; bufX = x; bufY = y; if (bufW > 0 && bufH > 0) { if (!X11_send_move_resize_event(GDK_WINDOW_XID(gtk_widget_get_window(border)), ox, oy, width(), height())) return; } #else bufX = x; bufY = y; #endif gtk_window_move(GTK_WINDOW(border), x, y); } else { gContainer::move(x,y); } } void gMainWindow::resize(int w, int h) { if (w == bufW && h == bufH) return; _resized = true; if (isTopLevel()) { //fprintf(stderr, "resize: %s: %d %d\n", name(), w, h); //gdk_window_enable_synchronized_configure (border->window); bufW = w < 0 ? 0 : w; bufH = h < 0 ? 0 : h; if (w < 1 || h < 1) { if (visible) gtk_widget_hide(border); } else { if (isResizable()) gtk_window_resize(GTK_WINDOW(border), w, h); else gtk_widget_set_size_request(border, w, h); if (visible) gtk_widget_show(border); } } else { //fprintf(stderr, "resize %p -> (%d %d) (%d %d)\n", this, bufW, bufH, w, h); gContainer::resize(w, h); } } void gMainWindow::moveResize(int x, int y, int w, int h) { //if (isTopLevel()) // gdk_window_move_resize(border->window, x, y, w, h); //else gContainer::moveResize(x, y, w, h); } void gMainWindow::emitOpen() { //fprintf(stderr, "emit Open: %p (%d %d) %d resizable = %d fullscreen = %d\n", this, width(), height(), opened, isResizable(), fullscreen()); if (!opened) { opened = true; //_no_resize_event = true; // If the event loop is run during emitOpen(), some spurious configure events are received. if (!_min_w && !_min_h) { _min_w = width(); _min_h = height(); } gtk_widget_realize(border); performArrange(); emit(SIGNAL(onOpen)); if (opened) { //fprintf(stderr, "emit Move & Resize: %p\n", this); emit(SIGNAL(onMove)); emitResize(); } } //_no_resize_event = false; } void gMainWindow::afterShow() { if (_activate) { gtk_window_present(GTK_WINDOW(border)); _activate = false; } } void gMainWindow::setVisible(bool vl) { if (!vl) _hidden = true; if (vl == isVisible()) return; if (vl) { bool arr = !isVisible(); emitOpen(); if (!opened) return; _not_spontaneous = !visible; visible = true; _hidden = false; setTransparent(_transparent); if (isTopLevel()) { if (!_title || !*_title) gtk_window_set_title(GTK_WINDOW(border), gApplication::defaultTitle()); /*if (!_xembed) { fprintf(stderr, "gtk_window_group_add_window: %p -> %p\n", border, gApplication::currentGroup()); gtk_window_group_add_window(gApplication::currentGroup(), GTK_WINDOW(border)); fprintf(stderr, "-> %p\n", gtk_window_get_group(GTK_WINDOW(border))); }*/ // Thanks for Ubuntu's GTK+ patching :-( #if GTK_CHECK_VERSION(3,0,0) gtk_window_set_has_resize_grip(GTK_WINDOW(border), false); #else if (g_object_class_find_property(G_OBJECT_GET_CLASS(border), "has-resize-grip")) g_object_set(G_OBJECT(border), "has-resize-grip", false, (char *)NULL); #endif gtk_window_move(GTK_WINDOW(border), bufX, bufY); if (isPopup()) { gtk_widget_show_now(border); gtk_widget_grab_focus(border); } else gtk_window_present(GTK_WINDOW(border)); if (isUtility()) { gMainWindow *parent = _current; if (!parent && gApplication::mainWindow() && gApplication::mainWindow() != this) parent = gApplication::mainWindow(); if (parent) gtk_window_set_transient_for(GTK_WINDOW(border), GTK_WINDOW(parent->border)); } if (gApplication::mainWindow() == this) { int desktop = session_manager_get_desktop(); if (desktop >= 0) { //fprintf(stderr, "X11_window_set_desktop: %d (%d)\n", desktop, true); X11_window_set_desktop((Window)handle(), true, desktop); session_manager_set_desktop(-1); } } } else { gtk_widget_show(border); parent()->performArrange(); } drawMask(); if (focus) { //fprintf(stderr, "focus = %s\n", focus->name()); focus->setFocus(); focus = 0; } if (skipTaskBar()) _activate = true; if (arr) performArrange(); } else { if (this == _active) focus = gApplication::activeControl(); _not_spontaneous = visible; gContainer::setVisible(false); if (_popup) gApplication::exitLoop(this); if (gApplication::_button_grab && !gApplication::_button_grab->isReallyVisible()) gApplication::setButtonGrab(NULL); } } void gMainWindow::setMinimized(bool vl) { if (!isTopLevel()) return; _minimized = vl; if (vl) gtk_window_iconify(GTK_WINDOW(border)); else gtk_window_deiconify(GTK_WINDOW(border)); } void gMainWindow::setMaximized(bool vl) { if (!isTopLevel()) return; _maximized = vl; if (vl) gtk_window_maximize(GTK_WINDOW(border)); else gtk_window_unmaximize(GTK_WINDOW(border)); } void gMainWindow::setFullscreen(bool vl) { if (!isTopLevel()) return; _fullscreen = vl; if (vl) { gtk_window_fullscreen(GTK_WINDOW(border)); if (isVisible()) gtk_window_present(GTK_WINDOW(border)); } else gtk_window_unfullscreen(GTK_WINDOW(border)); } void gMainWindow::center() { GdkRectangle rect; int x, y; if (!isTopLevel()) return; gDesktop::availableGeometry(screen(), &rect); x = rect.x + (rect.width - width()) / 2; y = rect.y + (rect.height - height()) / 2; move(x, y); } bool gMainWindow::isModal() const { if (!isTopLevel()) return false; return gtk_window_get_modal(GTK_WINDOW(border)); } void gMainWindow::showModal() { gMainWindow *save; if (!isTopLevel()) return; if (isModal()) return; //show(); gtk_window_set_modal(GTK_WINDOW(border), true); center(); //show(); gtk_grab_add(border); if (_active) gtk_window_set_transient_for(GTK_WINDOW(border), GTK_WINDOW(_active->topLevel()->border)); save = _current; _current = this; gApplication::enterLoop(this, true); _current = save; gtk_grab_remove(border); gtk_window_set_modal(GTK_WINDOW(border), false); if (!persistent) destroyNow(); else hide(); } void gMainWindow::showPopup(int x, int y) { gMainWindow *save; bool has_border; int oldx, oldy; //int type; if (!isTopLevel()) return; if (isModal()) return; //gtk_widget_unrealize(border); //((GtkWindow *)border)->type = GTK_WINDOW_POPUP; //gtk_widget_realize(border); oldx = left(); oldy = top(); has_border = gtk_window_get_decorated(GTK_WINDOW(border)); //type = getType(); //setType(_NET_WM_WINDOW_TYPE_COMBO); gtk_window_set_decorated(GTK_WINDOW(border), false); //gtk_window_set_type_hint(GTK_WINDOW(border), GDK_WINDOW_TYPE_HINT_POPUP_MENU); move(x, y); gtk_window_resize(GTK_WINDOW(border), bufW, bufH); //reparent(NULL, x, y, GTK_WINDOW_POPUP); _popup = true; save = _current; _current = this; gApplication::enterPopup(this); _current = save; _popup = false; if (!persistent) { destroyNow(); } else { hide(); //gdk_window_set_override_redirect(gtk_widget_get_window(GTK_WINDOW(border)), false); gtk_window_set_decorated(GTK_WINDOW(border), has_border); //setType(type); //gtk_window_set_type_hint(GTK_WINDOW(border), type); move(oldx, oldy); } } void gMainWindow::showActivate() { bool v = isTopLevel() && isVisible(); show(); if (v) gtk_window_present(GTK_WINDOW(border)); } void gMainWindow::showPopup() { int x, y; gMouse::getScreenPos(&x, &y); showPopup(x, y); } void gMainWindow::raise() { if (!isTopLevel()) { gControl::raise(); return; } gtk_window_present(GTK_WINDOW(border)); } const char* gMainWindow::text() { return _title; } bool gMainWindow::skipTaskBar() { if (!isTopLevel()) return false; else return _skip_taskbar; } void gMainWindow::setText(const char *txt) { if (_title) g_free(_title); _title = g_strdup(txt); if (isTopLevel()) gtk_window_set_title(GTK_WINDOW(border), txt); } bool gMainWindow::hasBorder() { if (isTopLevel()) return gtk_window_get_decorated(GTK_WINDOW(border)); else return false; } bool gMainWindow::isResizable() { if (isTopLevel()) return gtk_window_get_resizable(GTK_WINDOW(border)); else return false; } void gMainWindow::setBorder(bool b) { if (!isTopLevel()) return; gtk_window_set_decorated(GTK_WINDOW(border), b); /*#ifdef GDK_WINDOWING_X11 XSetWindowAttributes attr; attr.override_redirect = !b; XChangeWindowAttributes(GDK_WINDOW_XDISPLAY(border->window), GDK_WINDOW_XID(border->window), CWOverrideRedirect, &attr); #endif*/ } void gMainWindow::setResizable(bool b) { if (!isTopLevel()) return; if (b == isResizable()) return; gtk_window_set_resizable(GTK_WINDOW(border), b); if (b) gtk_widget_set_size_request(border, 1, 1); else gtk_widget_set_size_request(border, bufW, bufH); } void gMainWindow::setSkipTaskBar(bool b) { _skip_taskbar = b; if (!isTopLevel()) return; gtk_window_set_skip_taskbar_hint (GTK_WINDOW(border), b); } /*gPicture* gMainWindow::icon() { GdkPixbuf *buf; gPicture *pic; if (!isTopLevel()) return NULL; buf=gtk_window_get_icon(GTK_WINDOW(border)); if (!buf) return NULL; pic=gPicture::fromPixbuf(buf); return pic; }*/ void gMainWindow::setIcon(gPicture *pic) { gPicture::assign(&_icon, pic); if (!isTopLevel()) return; gtk_window_set_icon(GTK_WINDOW(border), pic ? pic->getPixbuf() : NULL); } bool gMainWindow::topOnly() { if (!isTopLevel()) return false; return top_only; } void gMainWindow::setTopOnly(bool vl) { if (!isTopLevel()) return; gtk_window_set_keep_above (GTK_WINDOW(border),vl); top_only=vl; } void gMainWindow::setMask(bool vl) { if (_mask == vl) return; _mask = vl; drawMask(); } void gMainWindow::setPicture(gPicture *pic) { gPicture::assign(&_picture, pic); drawMask(); } void gMainWindow::remap() { if (!isVisible()) return; gtk_widget_unmap(border); gtk_widget_map(border); if (_skip_taskbar) { setSkipTaskBar(false); setSkipTaskBar(true); } if (top_only) { setTopOnly(false); setTopOnly(true); } if (sticky) { setSticky(false); setSticky(true); } if (stack) { setStacking(0); setStacking(stack); } X11_set_window_type(handle(), _type); } void gMainWindow::drawMask() { bool do_remap = false; if (!isVisible()) return; #ifdef GTK3 cairo_region_t *mask; if (_mask && _picture) mask = gdk_cairo_region_create_from_surface(_picture->getSurface()); else mask = NULL; gdk_window_shape_combine_region(gtk_widget_get_window(border), mask, 0, 0); if (mask) cairo_region_destroy(mask); refresh(); #else GdkBitmap *mask = (_mask && _picture) ? _picture->getMask() : NULL; do_remap = !mask && _masked; gdk_window_shape_combine_mask(border->window, mask, 0, 0); #endif if (_picture) { gtk_widget_set_app_paintable(border, TRUE); gtk_widget_realize(border); gtk_widget_realize(widget); for (int i = 0; i < controlCount(); i++) getControl(i)->refresh(); } else if (!_transparent) { gtk_widget_set_app_paintable(border, FALSE); setRealBackground(background()); } _masked = mask != NULL; if (do_remap) remap(); else { if (!_skip_taskbar) { setSkipTaskBar(true); setSkipTaskBar(false); } } } int gMainWindow::menuCount() { if (!menuBar) return 0; return gMenu::winChildCount(this); } void gMainWindow::setPersistent(bool vl) { persistent = vl; } bool gMainWindow::doClose() { if (_closing) return false; if (opened) { if (isModal() && !gApplication::hasLoop(this)) return true; _closing = true; if (onClose) { if (!onClose(this)) opened = false; } else opened = false; _closing = false; if (!opened && isModal()) gApplication::exitLoop(this); } if (!opened) // && !modal()) { if (_active == this) setActiveWindow(NULL); if (!isModal()) { if (persistent) hide(); else destroy(); } return false; } else return opened; } bool gMainWindow::close() { return doClose(); } static void hide_hidden_children(gContainer *cont) { int i; gControl *child; for (i = 0;; i++) { child = cont->child(i); if (!child) break; if (!child->isVisible()) gtk_widget_hide(child->border); else if (child->isContainer()) hide_hidden_children((gContainer *)child); } } void gMainWindow::reparent(gContainer *newpr, int x, int y) { GtkWidget *new_border; int w, h; gColor fg, bg; if (_xembed) return; bg = background(); fg = foreground(); if (isTopLevel() && newpr) { gtk_window_remove_accel_group(GTK_WINDOW(topLevel()->border), accel); new_border = gtk_event_box_new(); gtk_widget_reparent(widget, new_border); embedMenuBar(new_border); _no_delete = true; gtk_widget_destroy(border); _no_delete = false; border = new_border; registerControl(); setCanFocus(false); setParent(newpr); connectParent(); borderSignals(); initWindow(); setBackground(bg); setForeground(fg); setFont(font()); checkMenuBar(); bufX = bufY = 0; move(x, y); gtk_widget_set_size_request(border, width(), height()); // Hidden children are incorrectly shown. Fix that! hideHiddenChildren(); } else if ((!isTopLevel() && !newpr) || (isTopLevel() && isPopup())) //|| (isTopLevel() && (isPopup() ^ (type == GTK_WINDOW_POPUP)))) { gtk_window_remove_accel_group(GTK_WINDOW(topLevel()->border), accel); // TODO: test that new_border = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_widget_reparent(widget, new_border); embedMenuBar(new_border); _no_delete = true; gtk_widget_destroy(border); _no_delete = false; border = new_border; registerControl(); setCanFocus(true); if (parent()) { parent()->remove(this); parent()->arrange(); setParent(NULL); } initWindow(); borderSignals(); setBackground(bg); setForeground(fg); setFont(font()); move(x, y); w = width(); h = height(); bufW = bufH = -1; gtk_widget_set_size_request(border, 1, 1); resize(w, h); hideHiddenChildren(); _popup = false; //type == GTK_WINDOW_POPUP; } else { gContainer::reparent(newpr, x, y); } } int gMainWindow::controlCount() { GList *list = gControl::controlList(); gControl *ctrl; int n = 0; while (list) { ctrl = (gControl *)list->data; if (ctrl->window() == this && !ctrl->isDestroyed()) n++; list = g_list_next(list); } return n; } gControl *gMainWindow::getControl(char *name) { GList *list = gControl::controlList(); gControl *ctrl; while (list) { ctrl = (gControl *)list->data; if (ctrl->window() == this && !strcasecmp(ctrl->name(), name) && !ctrl->isDestroyed()) return ctrl; list = g_list_next(list); } return NULL; } gControl *gMainWindow::getControl(int index) { GList *list = gControl::controlList(); gControl *ctrl; int i = 0; while (list) { ctrl = (gControl *)list->data; if (ctrl->window() == this && !ctrl->isDestroyed()) { if (i == index) return ctrl; i++; } list = g_list_next(list); } return NULL; } int gMainWindow::clientX() { return 0; } int gMainWindow::containerX() { return 0; } int gMainWindow::clientY() { if (isMenuBarVisible()) return menuBarHeight(); else return 0; } int gMainWindow::containerY() { return 0; } int gMainWindow::clientWidth() { return width(); } int gMainWindow::menuBarHeight() { int h = 0; if (menuBar) { //gtk_widget_show(GTK_WIDGET(menuBar)); //fprintf(stderr, "menuBarHeight: gtk_widget_get_visible: %d\n", gtk_widget_get_visible(GTK_WIDGET(menuBar))); #ifdef GTK3 gtk_widget_get_preferred_height(GTK_WIDGET(menuBar), NULL, &h); #else GtkRequisition req = { 0, 0 }; gtk_widget_size_request(GTK_WIDGET(menuBar), &req); h = req.height; #endif //fprintf(stderr, "menuBarHeight: %d\n", h); } return h; } int gMainWindow::clientHeight() { if (isMenuBarVisible()) return height() - menuBarHeight(); else return height(); } void gMainWindow::setActiveWindow(gControl *control) { gMainWindow *window = control ? control->window() : NULL; gMainWindow *old = _active; if (window == _active) return; _active = window; //fprintf(stderr, "setActiveWindow: %p %s\n", _active, _active ? _active->name() : ""); if (old) old->emit(SIGNAL(old->onDeactivate)); if (window) window->emit(SIGNAL(window->onActivate)); } #ifdef GDK_WINDOWING_X11 bool gMainWindow::isUtility() const { return _utility; } void gMainWindow::setUtility(bool v) { bool remap = false; if (!isTopLevel()) return; // TODO: works only if the window is not mapped! _utility = v; if (gtk_widget_get_mapped(border)) { remap = true; gtk_widget_unmap(border); } gtk_window_set_type_hint(GTK_WINDOW(border), v ? GDK_WINDOW_TYPE_HINT_UTILITY : GDK_WINDOW_TYPE_HINT_NORMAL); if (remap) gtk_widget_map(border); } #else bool gMainWindow::isUtility() { return _utility; } void gMainWindow::setUtility(bool v) { _utility = v; } #endif void gMainWindow::configure() { int h; if (bufW < 1 || bufH < 1) return; h = menuBarHeight(); //fprintf(stderr, "configure: %s: %d %d - %d %d\n", name(), isMenuBarVisible(), h, width(), height()); if (isMenuBarVisible()) { gtk_fixed_move(layout, GTK_WIDGET(menuBar), 0, 0); if (h > 1) gtk_widget_set_size_request(GTK_WIDGET(menuBar), width(), h); gtk_fixed_move(layout, widget, 0, h); gtk_widget_set_size_request(widget, width(), Max(0, height() - h)); } else { if (layout) { if (menuBar) gtk_fixed_move(layout, GTK_WIDGET(menuBar), 0, -h); gtk_fixed_move(layout, widget, 0, 0); } gtk_widget_set_size_request(widget, width(), height()); } } void gMainWindow::setMenuBarVisible(bool v) { _showMenuBar = v; if (!menuBar) return; configure(); performArrange(); } bool gMainWindow::isMenuBarVisible() { //fprintf(stderr, "isMenuBarVisible: %d\n", !!(menuBar && !_hideMenuBar && _showMenuBar)); return menuBar && !_hideMenuBar && _showMenuBar; //|| (menuBar && GTK_WIDGET_MAPPED(GTK_WIDGET(menuBar))); } void gMainWindow::updateFont() { gContainer::updateFont(); gMenu::updateFont(this); } void gMainWindow::checkMenuBar() { int i; gMenu *menu; //fprintf(stderr, "gMainWindow::checkMenuBar\n"); if (menuBar) { _hideMenuBar = true; for (i = 0;; i++) { menu = gMenu::winChildMenu(this, i); if (!menu) break; if (menu->isVisible() && !menu->isSeparator()) { _hideMenuBar = false; break; } } } configure(); performArrange(); } void gMainWindow::embedMenuBar(GtkWidget *border) { if (menuBar) { // layout is automatically destroyed ? layout = GTK_FIXED(gtk_fixed_new()); g_object_ref(G_OBJECT(menuBar)); if (gtk_widget_get_parent(GTK_WIDGET(menuBar))) gtk_container_remove(GTK_CONTAINER(gtk_widget_get_parent(GTK_WIDGET(menuBar))), GTK_WIDGET(menuBar)); gtk_fixed_put(layout, GTK_WIDGET(menuBar), 0, 0); g_object_unref(G_OBJECT(menuBar)); gtk_widget_reparent(widget, GTK_WIDGET(layout)); gtk_container_add(GTK_CONTAINER(border), GTK_WIDGET(layout)); gtk_widget_show(GTK_WIDGET(menuBar)); gtk_widget_show(GTK_WIDGET(layout)); gtk_widget_show(GTK_WIDGET(widget)); gMenu::updateFont(this); gMenu::updateColor(this); checkMenuBar(); } } /*bool gMainWindow::getScreenPos(int *x, int *y) { return gContainer::getScreenPos(x, y); }*/ double gMainWindow::opacity() { if (isTopLevel()) #if GTK_CHECK_VERSION(3, 8, 0) return gtk_widget_get_opacity(border); #else return gtk_window_get_opacity(GTK_WINDOW(border)); #endif else return 1.0; } void gMainWindow::setOpacity(double v) { if (isTopLevel()) #if GTK_CHECK_VERSION(3, 8, 0) gtk_widget_set_opacity(border, v); #else gtk_window_set_opacity(GTK_WINDOW(border), v); #endif } int gMainWindow::screen() { gMainWindow *tl = topLevel(); return gdk_screen_get_number(gtk_window_get_screen(GTK_WINDOW(tl->border))); } void gMainWindow::emitResize() { if (bufW == _resize_last_w && bufH == _resize_last_h) return; _resize_last_w = bufW; _resize_last_h = bufH; configure(); performArrange(); emit(SIGNAL(onResize)); } void gMainWindow::setGeometryHints() { if (isTopLevel() && isResizable()) { if (isModal()) { GdkGeometry geometry; geometry.min_width = _min_w; geometry.min_height = _min_h; gdk_window_set_geometry_hints(gtk_widget_get_window(border), &geometry, (GdkWindowHints)(GDK_HINT_MIN_SIZE | GDK_HINT_POS)); } } } void gMainWindow::setBackground(gColor vl) { _bg = vl; if (!_transparent) gControl::setBackground(vl); } void gMainWindow::setTransparent(bool vl) { if (!vl) return; _transparent = TRUE; if (!isVisible()) return; #ifdef GTK3 GdkScreen *screen = NULL; GdkVisual *visual = NULL; screen = gtk_widget_get_screen(border); visual = gdk_screen_get_rgba_visual(screen); if (visual == NULL) return; #else GdkScreen *screen; GdkColormap *colormap; screen = gtk_widget_get_screen(border); colormap = gdk_screen_get_rgba_colormap(screen); if (colormap == NULL) return; #endif gtk_widget_unrealize(border); gtk_widget_set_app_paintable(border, TRUE); #ifdef GTK3 gtk_widget_set_visual(border, visual); #else gtk_widget_set_colormap(border, colormap); #endif gtk_widget_realize(border); int w = width(); int h = height(); bufW = w - 1; resize(w, h); gtk_window_present(GTK_WINDOW(border)); } bool gMainWindow::closeAll() { int i; gMainWindow *win; for(i = 0; i < count(); i++) { win = get(i); if (!win) break; if (win == gApplication::mainWindow()) continue; if (win->close()) return true; } return false; }
justlostintime/gambas
gb.gtk/src/gmainwindow.cpp
C++
gpl-2.0
32,346
package sicxe.model.simulator.assembler.command.bits; /** * Created by maciek on 14/01/16. */ public class FormatFourBits extends Bits{ private final int e = 1 << 20; private final int b = 0; private final int p = 0; private int x = 0; public int getX() { return x; } public void setX() { this.x = 1 << 23; } public void zeroX(){ this.x = 0; } public int getE() { return e; } public int getB() { return b; } public int getP() { return p; } }
mwalercz/sicxe-sim-mvn
src/main/java/sicxe/model/simulator/assembler/command/bits/FormatFourBits.java
Java
gpl-2.0
563
<?php /** * duena functions and definitions * * @package duena */ /** * Set the content width based on the theme's design and stylesheet. */ if ( ! isset( $content_width ) ) $content_width = 900; /* pixels */ // The excerpt based on words if ( !function_exists('duena_string_limit_words') ) { function duena_string_limit_words($string, $word_limit) { $words = explode(' ', $string, ($word_limit + 1)); if(count($words) > $word_limit) array_pop($words); $res = implode(' ', $words); $res = trim ($res); $res = preg_replace("/[.]+$/", "", $res); if ( '' != $res) { return $res . '... '; } else { return $res; } } } /* * Load Files. */ //Loading options.php for theme customizer include_once( get_template_directory() . '/options.php'); //Loads the Options Panel if ( !function_exists( 'optionsframework_init' ) ) { define( 'OPTIONS_FRAMEWORK_DIRECTORY', get_template_directory_uri() . '/options/' ); include_once( get_template_directory() . '/options/options-framework.php' ); } /* * Load Jetpack compatibility file. */ require( get_template_directory() . '/inc/jetpack.php' ); if ( ! function_exists( 'duena_setup' ) ) : /** * Sets up theme defaults and registers support for various WordPress features. * * Note that this function is hooked into the after_setup_theme hook, which runs * before the init hook. The init hook is too late for some features, such as indicating * support post thumbnails. */ function duena_setup() { $defaults = array( 'default-color' => '', 'default-image' => '', 'wp-head-callback' => '_custom_background_cb', 'admin-head-callback' => '', 'admin-preview-callback' => '' ); add_theme_support( 'custom-background', $defaults ); /** * Custom functions that act independently of the theme templates */ require( get_template_directory() . '/inc/extras.php' ); /** * Customizer additions */ require( get_template_directory() . '/inc/customizer.php' ); /** * Make theme available for translation * Translations can be filed in the /languages/ directory * If you're building a theme based on duena, use a find and replace * to change 'duena' to the name of your theme in all the template files */ load_theme_textdomain( 'duena', get_template_directory() . '/languages' ); /** * Add editor styles */ add_editor_style( 'css/editor-style.css' ); /** * Add default posts and comments RSS feed links to head */ add_theme_support( 'automatic-feed-links' ); /** * This theme uses wp_nav_menu() in two locations. */ register_nav_menus( array( 'primary' => __( 'Primary Menu', 'duena' ), 'footer' => __( 'Footer Menu', 'duena' ) ) ); /* * This theme supports all available post formats. * See http://codex.wordpress.org/Post_Formats * * Structured post formats are formats where Twenty Thirteen handles the * output instead of the default core HTML output. */ add_theme_support( 'structured-post-formats', array( 'link', 'video' ) ); add_theme_support( 'post-formats', array( 'aside', 'audio', 'chat', 'gallery', 'image', 'quote', 'status' ) ); // This theme uses its own gallery styles. add_filter( 'use_default_gallery_style', '__return_false' ); /** * Add image sizes */ if ( function_exists( 'add_theme_support' ) ) { // Added in 2.9 add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 750, 290, true ); // Normal post thumbnails add_image_size( 'slider-post-thumbnail', 1140, 440, true ); // Slider Thumbnail add_image_size( 'image_post_format', 750, 440, true ); // Image Post Format output add_image_size( 'related-thumb', 160, 160, true ); // Realted Post Image output add_image_size( 'portfolio-large-th', 550, 210, true ); // 2 cols portfolio image add_image_size( 'portfolio-small-th', 265, 100, true ); // 4 cols portfolio image } } endif; // duena_setup add_action( 'after_setup_theme', 'duena_setup' ); /** * Register widgetized area and update sidebar with default widgets */ function duena_widgets_init() { register_sidebar( array( 'name' => __( 'Sidebar', 'duena' ), 'id' => 'sidebar-1', 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); } //add_action( 'widgets_init', 'duena_widgets_init' ); /** * Enqueue scripts and styles */ function duena_styles() { global $wp_styles; // Bootstrap styles wp_register_style( 'duena-bootstrap', get_template_directory_uri() . '/bootstrap/css/bootstrap.css'); wp_enqueue_style( 'duena-bootstrap' ); // Slider styles wp_register_style( 'flexslider', get_template_directory_uri() . '/css/flexslider.css'); wp_enqueue_style( 'flexslider' ); // Popup styles wp_register_style( 'magnific', get_template_directory_uri() . '/css/magnific-popup.css'); wp_enqueue_style( 'magnific' ); // FontAwesome stylesheet wp_register_style( 'font-awesome', get_template_directory_uri() . '/css/font-awesome.css', '', '4.0.3'); wp_enqueue_style( 'font-awesome' ); // Main stylesheet wp_enqueue_style( 'duena-style', get_stylesheet_uri() ); // Add inline styles from theme options $duena_user_css = duena_get_user_colors(); wp_add_inline_style( 'duena-style', $duena_user_css ); // Loads the Internet Explorer specific stylesheet. wp_enqueue_style( 'duena_ie', get_template_directory_uri() . '/css/ie.css' ); $wp_styles->add_data( 'duena_ie', 'conditional', 'lt IE 9' ); } function duena_scripts() { wp_enqueue_script( 'duena-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20120206', true ); wp_enqueue_script( 'duena-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20130115', true ); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } if ( is_singular() && wp_attachment_is_image() ) { wp_enqueue_script( 'duena-keyboard-image-navigation', get_template_directory_uri() . '/js/keyboard-image-navigation.js', array( 'jquery' ), '20120202' ); } // Menu scripts wp_enqueue_script('superfish', get_template_directory_uri() . '/js/superfish.js', array('jquery'), '1.4.8', true); wp_enqueue_script('mobilemenu', get_template_directory_uri() . '/js/jquery.mobilemenu.js', array('jquery'), '1.0', true); wp_enqueue_script('sf_Touchscreen', get_template_directory_uri() . '/js/sfmenu-touch.js', array('jquery'), '1.0', true); // Slider wp_enqueue_script('flexslider', get_template_directory_uri() . '/js/jquery.flexslider.js', array('jquery'), '2.1', true); // PopUp wp_enqueue_script('magnific', get_template_directory_uri() . '/js/jquery.magnific-popup.js', array('jquery'), '0.8.9', true); // Bootstrap JS wp_enqueue_script('bootstrap-custom', get_template_directory_uri() . '/js/bootstrap.js', array('jquery'), '1.0', true); // Custom Script File wp_enqueue_script('custom', get_template_directory_uri() . '/js/custom.js', array('jquery'), '1.0', true); } add_action( 'wp_enqueue_scripts', 'duena_scripts', 10 ); add_action( 'wp_enqueue_scripts', 'duena_styles', 10 ); /** * Include additional assests for admin area */ function duena_admin_assets() { $screen = get_current_screen(); if ( isset( $screen ) && 'page' == $screen->post_type ) { // scripts wp_enqueue_script( 'duena-admin-script', get_template_directory_uri() . '/js/admin-scripts.js', array('jquery'), '1.0', true ); // styles wp_enqueue_style( 'duena-admin-style', get_template_directory_uri() . '/css/admin-style.css', '', '1.0' ); } } add_action( 'admin_enqueue_scripts', 'duena_admin_assets' ); /** * Adding class 'active' to current menu item */ add_filter( 'nav_menu_css_class', 'duena_active_item_classes', 10, 2 ); function duena_active_item_classes($classes = array(), $menu_item = false){ if(in_array('current-menu-item', $menu_item->classes)){ $classes[] = 'active'; } return $classes; } /** * Load localization */ load_theme_textdomain( 'duena', get_template_directory() . '/languages' ); /*-----------------------------------------------------------------------------------*/ /* Custom Gallery /*-----------------------------------------------------------------------------------*/ if ( ! function_exists( 'duena_featured_gallery' ) ) : function duena_featured_gallery() { $pattern = get_shortcode_regex(); if ( preg_match( "/$pattern/s", get_the_content(), $match ) && 'gallery' == $match[2] ) { add_filter( 'shortcode_atts_gallery', 'duena_gallery_atts' ); echo do_shortcode_tag( $match ); } } endif; function duena_gallery_atts( $atts ) { $atts['size'] = 'large'; return $atts; } /*-----------------------------------------------------------------------------------*/ /* Get link URL for link post type /*-----------------------------------------------------------------------------------*/ function duena_get_link_url() { $has_url = get_the_post_format_url(); return ( $has_url ) ? $has_url : apply_filters( 'the_permalink', get_permalink() ); } /*-----------------------------------------------------------------------------------*/ /* Breabcrumbs /*-----------------------------------------------------------------------------------*/ if (! function_exists( 'duena_breadcrumb' )) { function duena_breadcrumb() { $showOnHome = 0; // 1 - show "breadcrumbs" on home page, 0 - hide $delimiter = '<li class="divider">/</li>'; // divider $home = 'Home'; // text for link "Home" $showCurrent = 1; // 1 - show title current post/page, 0 - hide $before = '<li class="active">'; // open tag for active breadcrumb $after = '</li>'; // close tag for active breadcrumb global $post; $homeLink = home_url(); if (is_front_page()) { if ($showOnHome == 1) echo '<ul class="breadcrumb breadcrumb__t"><li><a href="' . $homeLink . '">' . $home . '</a><li></ul>'; } else { echo '<ul class="breadcrumb breadcrumb__t"><li><a href="' . $homeLink . '">' . $home . '</a></li> ' . $delimiter . ' '; if ( is_home() ) { echo $before . 'Blog' . $after; } elseif ( is_category() ) { $thisCat = get_category(get_query_var('cat'), false); if ($thisCat->parent != 0) echo get_category_parents($thisCat->parent, TRUE, ' ' . $delimiter . ' '); echo $before . 'Category Archives: "' . single_cat_title('', false) . '"' . $after; } elseif ( is_search() ) { echo $before . 'Search for: "' . get_search_query() . '"' . $after; } elseif ( is_day() ) { echo '<li><a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a></li> ' . $delimiter . ' '; echo '<li><a href="' . get_month_link(get_the_time('Y'),get_the_time('m')) . '">' . get_the_time('F') . '</a></li> ' . $delimiter . ' '; echo $before . get_the_time('d') . $after; } elseif ( is_month() ) { echo '<li><a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a></li> ' . $delimiter . ' '; echo $before . get_the_time('F') . $after; } elseif ( is_year() ) { echo $before . get_the_time('Y') . $after; } elseif ( is_single() && !is_attachment() ) { if ( get_post_type() != 'post' ) { $post_name = get_post_type(); $post_type = get_post_type_object(get_post_type()); $slug = $post_type->rewrite; echo '<li><a href="' . $homeLink . '/' . $post_name . '/">' . $post_type->labels->singular_name . '</a></li>'; if ($showCurrent == 1) echo ' ' . $delimiter . ' ' . $before . get_the_title() . $after; } else { $cat = get_the_category(); $cat = $cat[0]; $cats = get_category_parents($cat, TRUE, ' ' . $delimiter . ' '); if ($showCurrent == 0) $cats = preg_replace("#^(.+)\s$delimiter\s$#", "$1", $cats); echo $cats; if ($showCurrent == 1) echo $before . get_the_title() . $after; } } elseif ( !is_single() && !is_page() && get_post_type() != 'post' && !is_404() ) { $post_type = get_post_type_object(get_post_type()); echo $before . $post_type->labels->singular_name . $after; } elseif ( is_attachment() ) { $parent = get_post($post->post_parent); $cat = get_the_category($parent->ID); $cat = $cat[0]; echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' '); echo '<li><a href="' . get_permalink($parent) . '">' . $parent->post_title . '</a></li>'; if ($showCurrent == 1) echo ' ' . $delimiter . ' ' . $before . get_the_title() . $after; } elseif ( is_page() && !$post->post_parent ) { if ($showCurrent == 1) echo $before . get_the_title() . $after; } elseif ( is_page() && $post->post_parent ) { $parent_id = $post->post_parent; $breadcrumbs = array(); while ($parent_id) { $page = get_page($parent_id); $breadcrumbs[] = '<li><a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a></li>'; $parent_id = $page->post_parent; } $breadcrumbs = array_reverse($breadcrumbs); for ($i = 0; $i < count($breadcrumbs); $i++) { echo $breadcrumbs[$i]; if ($i != count($breadcrumbs)-1) echo ' ' . $delimiter . ' '; } if ($showCurrent == 1) echo ' ' . $delimiter . ' ' . $before . get_the_title() . $after; } elseif ( is_tag() ) { echo $before . 'Tag Archives: "' . single_tag_title('', false) . '"' . $after; } elseif ( is_author() ) { global $author; $userdata = get_userdata($author); echo $before . 'by ' . $userdata->display_name . $after; } elseif ( is_404() ) { echo $before . '404' . $after; } /* if ( get_query_var('paged') ) { if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' ('; echo __(' Page') . ' ' . get_query_var('paged'); if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')'; } */ echo '</ul>'; } } // end breadcrumbs() } /*-----------------------------------------------------------------------------------*/ /* Author Bio /*-----------------------------------------------------------------------------------*/ add_action( 'before_sidebar', 'duena_show_author_bio', 10 ); function duena_show_author_bio() { if ( 'no' != of_get_option('g_author_bio') ) { ?> <div class="author_bio_sidebar"> <div class="social_box"> <?php if ( '' != of_get_option('g_author_bio_social_twitter') ) { echo "<a href='".esc_url( of_get_option('g_author_bio_social_twitter') )."' target='_blank'><i class='fa fa-twitter'></i></a>\n"; } if ( '' != of_get_option('g_author_bio_social_facebook') ) { echo "<a href='".esc_url( of_get_option('g_author_bio_social_facebook') )."' target='_blank'><i class='fa fa-facebook'></i></a>\n"; } if ( '' != of_get_option('g_author_bio_social_google') ) { echo "<a href='".esc_url( of_get_option('g_author_bio_social_google') )."' target='_blank'><i class='fa fa-google-plus'></i></a>\n"; } if ( '' != of_get_option('g_author_bio_social_linked') ) { echo "<a href='".esc_url( of_get_option('g_author_bio_social_linked') )."' target='_blank'><i class='fa fa-linkedin'></i></a>\n"; } if ( '' != of_get_option('g_author_bio_social_rss') ) { echo "<a href='".esc_url( of_get_option('g_author_bio_social_rss') )."' target='_blank'><i class='fa fa-rss'></i></a>\n"; } ?> </div> <?php if (( '' != of_get_option('g_author_bio_title') ) || ('' != of_get_option('g_author_bio_img')) || ('' != of_get_option('g_author_bio_message')) ) { ?> <div class="content_box"> <?php if ( '' != of_get_option('g_author_bio_title') ) { echo "<h2>".of_get_option('g_author_bio_title')."</h2>\n"; } if ( '' != of_get_option('g_author_bio_img') ) { if ( '' != of_get_option('g_author_bio_title') ) { $img_alt = of_get_option('g_author_bio_title'); } else { $img_alt = get_bloginfo( 'name' ); } echo "<figure class='author_bio_img'><img src='".esc_url( of_get_option('g_author_bio_img') )."' alt='".esc_attr( $img_alt )."'></figure>\n"; } if ( '' != of_get_option('g_author_bio_message') ) { echo "<div class='author_bio_message'>".of_get_option('g_author_bio_message')."</div>\n"; } ?> </div> <?php } ?> </div> <?php } } /*-----------------------------------------------------------------------------------*/ /* Pagination (based on Twenty Fourteen pagination function) /*-----------------------------------------------------------------------------------*/ function duena_pagination() { global $wp_query, $wp_rewrite; if ( $wp_query->max_num_pages < 2 ) { return; } $paged = get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1; $pagenum_link = html_entity_decode( get_pagenum_link() ); $query_args = array(); $url_parts = explode( '?', $pagenum_link ); if ( isset( $url_parts[1] ) ) { wp_parse_str( $url_parts[1], $query_args ); } $pagenum_link = remove_query_arg( array_keys( $query_args ), $pagenum_link ); $pagenum_link = trailingslashit( $pagenum_link ) . '%_%'; $format = $wp_rewrite->using_index_permalinks() && ! strpos( $pagenum_link, 'index.php' ) ? 'index.php/' : ''; $format .= $wp_rewrite->using_permalinks() ? user_trailingslashit( 'page/%#%', 'paged' ) : '?paged=%#%'; // Set up paginated links. $links = paginate_links( array( 'base' => $pagenum_link, 'format' => $format, 'total' => $wp_query->max_num_pages, 'current' => $paged, 'mid_size' => 1, 'add_args' => array_map( 'urlencode', $query_args ), 'prev_text' => __( '&larr; Previous', 'duena' ), 'next_text' => __( 'Next &rarr;', 'duena' ), 'type' => 'list' ) ); if ( $links ) { ?> <div class="page_nav_wrap"> <div class="post_nav"> <?php echo $links; ?> </div><!-- .pagination --> </div><!-- .navigation --> <?php } } /*-----------------------------------------------------------------------------------*/ /* Custom Comments Structure /*-----------------------------------------------------------------------------------*/ function duena_comment($comment, $args, $depth) { $GLOBALS['comment'] = $comment; ?> <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>" class="clearfix"> <div id="comment-<?php comment_ID(); ?>" class="comment-body clearfix"> <div class="clearfix"> <div class="comment-author vcard"> <?php echo get_avatar( $comment->comment_author_email, 65 ); ?> <?php printf(__('<span class="author fn">%1$s</span>' ), get_comment_author_link()) ?> </div> <?php if ($comment->comment_approved == '0') : ?> <em><?php _e('Your comment is awaiting moderation.', 'cherry') ?></em> <?php endif; ?> <div class="extra-wrap"> <?php comment_text() ?> </div> </div> <div class="clearfix comment-footer"> <div class="reply"> <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?> </div> <div class="comment-meta commentmetadata"><?php printf(__('%1$s', 'cherry' ), get_comment_date('F j, Y')) ?></div> </div> </div> <?php } if (!function_exists('img_html_to_post_id')) { function img_html_to_post_id( $html, &$matched_html = null ) { $attachment_id = 0; // Look for an <img /> tag if ( ! preg_match( '#' . get_tag_regex( 'img' ) . '#i', $html, $matches ) || empty( $matches ) ) return $attachment_id; $matched_html = $matches[0]; // Look for attributes. if ( ! preg_match_all( '#(src|class)=([\'"])(.+?)\2#is', $matched_html, $matches ) || empty( $matches ) ) return $attachment_id; $attr = array(); foreach ( $matches[1] as $key => $attribute_name ) $attr[ $attribute_name ] = $matches[3][ $key ]; if ( ! empty( $attr['class'] ) && false !== strpos( $attr['class'], 'wp-image-' ) ) if ( preg_match( '#wp-image-([0-9]+)#i', $attr['class'], $matches ) ) $attachment_id = absint( $matches[1] ); if ( ! $attachment_id && ! empty( $attr['src'] ) ) $attachment_id = attachment_url_to_postid( $attr['src'] ); return $attachment_id; } } if (!function_exists('duena_footer_js')) { function duena_footer_js() { $sf_delay = esc_attr( of_get_option('sf_delay') ); $sf_f_animation = esc_attr( of_get_option('sf_f_animation') ); $sf_sl_animation = esc_attr( of_get_option('sf_sl_animation') ); $sf_speed = esc_attr( of_get_option('sf_speed') ); $sf_arrows = esc_attr( of_get_option('sf_arrows') ); if ('' == $sf_delay) {$sf_delay = 1000;} if ('' == $sf_f_animation) {$sf_f_animation = 'show';} if ('' == $sf_sl_animation) {$sf_sl_animation = 'show';} if ('' == $sf_speed) {$sf_speed = 'normal';} if ('' == $sf_arrows) {$sf_arrows = 'false';} ?> <script type="text/javascript"> // initialise plugins jQuery(function(){ // main navigation init jQuery('.navbar_inner > ul').superfish({ delay: <?php echo $sf_delay; ?>, // one second delay on mouseout animation: {opacity:"<?php echo $sf_f_animation; ?>", height:"<?php echo $sf_sl_animation; ?>"}, // fade-in and slide-down animation speed: '<?php echo $sf_speed; ?>', // faster animation speed autoArrows: <?php echo $sf_arrows; ?>, // generation of arrow mark-up (for submenu) dropShadows: false }); jQuery('.navbar_inner > div > ul').superfish({ delay: <?php echo $sf_delay; ?>, // one second delay on mouseout animation: {opacity:"<?php echo $sf_f_animation; ?>", height:"<?php echo $sf_sl_animation; ?>"}, // fade-in and slide-down animation speed: '<?php echo $sf_speed; ?>', // faster animation speed autoArrows: <?php echo $sf_arrows; ?>, // generation of arrow mark-up (for submenu) dropShadows: false }); }); jQuery(function(){ var ismobile = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)|(webOS)/i) if(ismobile){ jQuery('.navbar_inner > ul').sftouchscreen(); jQuery('.navbar_inner > div > ul').sftouchscreen(); } }); </script> <!--[if (gt IE 9)|!(IE)]><!--> <script type="text/javascript"> jQuery(function(){ jQuery('.navbar_inner > ul').mobileMenu(); jQuery('.navbar_inner > div > ul').mobileMenu(); }) </script> <!--<![endif]--> <?php } add_action( 'wp_footer', 'duena_footer_js', 20, 1 ); }
werner/78publicity
wp-content/themes/duena/functions.php
PHP
gpl-2.0
23,364
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 4.1 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2011 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | | | CiviCRM is distributed in the hope that it will be useful, but | | WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | | See the GNU Affero General Public License for more details. | | | | You should have received a copy of the GNU Affero General Public | | License and the CiviCRM Licensing Exception along | | with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * * @package CRM * @copyright CiviCRM LLC (c) 2004-2011 * $Id$ * */ require_once 'CRM/Logging/Differ.php'; class CRM_Logging_Reverter { private $db; private $log_conn_id; private $log_date; function __construct($log_conn_id, $log_date) { $dsn = defined('CIVICRM_LOGGING_DSN') ? DB::parseDSN(CIVICRM_LOGGING_DSN) : DB::parseDSN(CIVICRM_DSN); $this->db = $dsn['database']; $this->log_conn_id = $log_conn_id; $this->log_date = $log_date; } function revert($tables) { // FIXME: split off the table → DAO mapping to a GenCode-generated class $daos = array( 'civicrm_address' => 'CRM_Core_DAO_Address', 'civicrm_contact' => 'CRM_Contact_DAO_Contact', 'civicrm_email' => 'CRM_Core_DAO_Email', 'civicrm_im' => 'CRM_Core_DAO_IM', 'civicrm_openid' => 'CRM_Core_DAO_OpenID', 'civicrm_phone' => 'CRM_Core_DAO_Phone', 'civicrm_website' => 'CRM_Core_DAO_Website', 'civicrm_contribution' => 'CRM_Contribute_DAO_Contribution', ); // get custom data tables, columns and types $ctypes = array(); $dao = CRM_Core_DAO::executeQuery('SELECT table_name, column_name, data_type FROM civicrm_custom_group cg JOIN civicrm_custom_field cf ON (cf.custom_group_id = cg.id)'); while ($dao->fetch()) { if (!isset($ctypes[$dao->table_name])) $ctypes[$dao->table_name] = array('entity_id' => 'Integer'); $ctypes[$dao->table_name][$dao->column_name] = $dao->data_type; } $differ = new CRM_Logging_Differ($this->log_conn_id, $this->log_date); $diffs = $differ->diffsInTables($tables); $deletes = array(); $reverts = array(); foreach ($diffs as $table => $changes) { foreach ($changes as $change) { switch ($change['action']) { case 'Insert': if (!isset($deletes[$table])) $deletes[$table] = array(); $deletes[$table][] = $change['id']; break; case 'Delete': case 'Update': if (!isset($reverts[$table])) $reverts[$table] = array(); if (!isset($reverts[$table][$change['id']])) $reverts[$table][$change['id']] = array('log_action' => $change['action']); $reverts[$table][$change['id']][$change['field']] = $change['from']; break; } } } // revert inserts by deleting foreach ($deletes as $table => $ids) { CRM_Core_DAO::executeQuery("DELETE FROM `$table` WHERE id IN (" . implode(', ', array_unique($ids)) . ')'); } // revert updates by updating to previous values foreach ($reverts as $table => $row) { switch (true) { // DAO-based tables case in_array($table, array_keys($daos)): require_once str_replace('_', DIRECTORY_SEPARATOR, $daos[$table]) . '.php'; eval("\$dao = new {$daos[$table]};"); foreach ($row as $id => $changes) { $dao->id = $id; foreach ($changes as $field => $value) { if ($field == 'log_action') continue; if (empty($value) and $value !== 0 and $value !== '0') $value = 'null'; $dao->$field = $value; } $changes['log_action'] == 'Delete' ? $dao->insert() : $dao->update(); $dao->reset(); } break; // custom data tables case in_array($table, array_keys($ctypes)): foreach ($row as $id => $changes) { $inserts = array('id' => '%1'); $updates = array(); $params = array(1 => array($id, 'Integer')); $counter = 2; foreach ($changes as $field => $value) { if (!isset($ctypes[$table][$field])) continue; // don’t try reverting a field that’s no longer there switch ($ctypes[$table][$field]) { case 'Date': $value = substr(CRM_Utils_Date::isoToMysql($value), 0, 8); break; case 'Timestamp': $value = CRM_Utils_Date::isoToMysql($value); break; } $inserts[$field] = "%$counter"; $updates[] = "$field = %$counter"; $params[$counter] = array($value, $ctypes[$table][$field]); $counter++; } if ($changes['log_action'] == 'Delete') { $sql = "INSERT INTO `$table` (" . implode(', ', array_keys($inserts)) . ') VALUES (' . implode(', ', $inserts) . ')'; } else { $sql = "UPDATE `$table` SET " . implode(', ', $updates) . ' WHERE id = %1'; } CRM_Core_DAO::executeQuery($sql, $params); } break; } } // CRM-7353: if nothing altered civicrm_contact, touch it; this will // make sure there’s an entry in log_civicrm_contact for this revert if (empty($diffs['civicrm_contact'])) { $query = " SELECT id FROM `{$this->db}`.log_civicrm_contact WHERE log_conn_id = %1 AND log_date BETWEEN DATE_SUB(%2, INTERVAL 10 SECOND) AND DATE_ADD(%2, INTERVAL 10 SECOND) ORDER BY log_date DESC LIMIT 1 "; $params = array( 1 => array($this->log_conn_id, 'Integer'), 2 => array($this->log_date, 'String'), ); $cid = CRM_Core_DAO::singleValueQuery($query, $params); if (!$cid) return; require_once 'CRM/Contact/DAO/Contact.php'; $dao = new CRM_Contact_DAO_Contact; $dao->id = $cid; if ($dao->find(true)) { // CRM-8102: MySQL can’t parse its own dates $dao->birth_date = CRM_Utils_Date::isoToMysql($dao->birth_date); $dao->deceased_date = CRM_Utils_Date::isoToMysql($dao->deceased_date); $dao->save(); } } } }
jblanford/Uber-Web-Site
sites/all/modules/civicrm/CRM/Logging/Reverter.php
PHP
gpl-2.0
8,305
/////////////////////////////////////////////////////////////////////////////// // // wxFormBuilder - A Visual Dialog Editor for wxWidgets. // Copyright (C) 2005 José Antonio Hurtado // // 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. // // Written by // José Antonio Hurtado - joseantonio.hurtado@gmail.com // Juan Antonio Ortega - jortegalalmolda@gmail.com // /////////////////////////////////////////////////////////////////////////////// #include <plugin.h> #include <ticpp.h> #include <wx/gbsizer.h> #include <wx/wrapsizer.h> #include <xrcconv.h> #ifdef __WX24__ #define wxFIXED_MINSIZE wxADJUST_MINSIZE #endif class SpacerComponent : public ComponentBase { public: // ImportFromXRC is handled in sizeritem components ticpp::Element* ExportToXrc(IObject* obj) override { ObjectToXrcFilter xrc(obj, _("spacer")); xrc.AddPropertyPair( _("width"), _("height"), _("size") ); return xrc.GetXrcObject(); } }; class GBSizerItemComponent : public ComponentBase { public: ticpp::Element* ExportToXrc(IObject* obj) override { ObjectToXrcFilter xrc(obj, _("sizeritem")); xrc.AddPropertyPair( _("row"), _("column"), _("cellpos") ); xrc.AddPropertyPair( _("rowspan"), _("colspan"), _("cellspan") ); xrc.AddProperty(_("flag"), _("flag"), XRC_TYPE_BITLIST); xrc.AddProperty(_("border"), _("border"), XRC_TYPE_INTEGER); return xrc.GetXrcObject(); } ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { // XrcLoader::GetObject imports spacers as sizeritems XrcToXfbFilter filter(xrcObj, _("gbsizeritem")); filter.AddPropertyPair( "cellpos", _("row"), _("column") ); filter.AddPropertyPair( "cellspan", _("rowspan"), _("colspan") ); filter.AddProperty(_("flag"), _("flag"), XRC_TYPE_BITLIST); filter.AddProperty(_("border"), _("border"), XRC_TYPE_INTEGER); ticpp::Element* sizeritem = filter.GetXfbObject(); // XrcLoader::GetObject imports spacers as sizeritems, so check for a spacer if ( xrcObj->FirstChildElement( "size", false ) && !xrcObj->FirstChildElement( "object", false ) ) { // it is a spacer XrcToXfbFilter spacer( xrcObj, _("spacer") ); spacer.AddPropertyPair( "size", _("width"), _("height") ); sizeritem->LinkEndChild( spacer.GetXfbObject() ); } return sizeritem; } }; class SizerItemComponent : public ComponentBase { public: void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { // Get parent sizer wxObject* parent = GetManager()->GetParent( wxobject ); wxSizer* sizer = wxDynamicCast( parent, wxSizer ); if ( NULL == sizer ) { wxLogError( wxT("The parent of a SizerItem is either missing or not a wxSizer - this should not be possible!") ); return; } // Get child window wxObject* child = GetManager()->GetChild( wxobject, 0 ); if ( NULL == child ) { wxLogError( wxT("The SizerItem component has no child - this should not be possible!") ); return; } // Get IObject for property access IObject* obj = GetManager()->GetIObject( wxobject ); IObject* childObj = GetManager()->GetIObject( child ); // Add the spacer if ( _("spacer") == childObj->GetClassName() ) { sizer->Add( childObj->GetPropertyAsInteger( _("width") ), childObj->GetPropertyAsInteger( _("height") ), obj->GetPropertyAsInteger(_("proportion")), obj->GetPropertyAsInteger(_("flag")), obj->GetPropertyAsInteger(_("border")) ); return; } // Add the child ( window or sizer ) to the sizer wxWindow* windowChild = wxDynamicCast( child, wxWindow ); wxSizer* sizerChild = wxDynamicCast( child, wxSizer ); if ( windowChild != NULL ) { sizer->Add( windowChild, obj->GetPropertyAsInteger(_("proportion")), obj->GetPropertyAsInteger(_("flag")), obj->GetPropertyAsInteger(_("border"))); } else if ( sizerChild != NULL ) { sizer->Add( sizerChild, obj->GetPropertyAsInteger(_("proportion")), obj->GetPropertyAsInteger(_("flag")), obj->GetPropertyAsInteger(_("border"))); } else { wxLogError( wxT("The SizerItem component's child is not a wxWindow or a wxSizer or a spacer - this should not be possible!") ); } } ticpp::Element* ExportToXrc(IObject* obj) override { ObjectToXrcFilter xrc(obj, _("sizeritem")); xrc.AddProperty(_("proportion"), _("option"), XRC_TYPE_INTEGER); xrc.AddProperty(_("flag"), _("flag"), XRC_TYPE_BITLIST); xrc.AddProperty(_("border"), _("border"), XRC_TYPE_INTEGER); return xrc.GetXrcObject(); } ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { XrcToXfbFilter filter(xrcObj, _("sizeritem")); filter.AddProperty(_("option"), _("proportion"), XRC_TYPE_INTEGER); filter.AddProperty(_("flag"), _("flag"), XRC_TYPE_BITLIST); filter.AddProperty(_("border"), _("border"), XRC_TYPE_INTEGER); ticpp::Element* sizeritem = filter.GetXfbObject(); // XrcLoader::GetObject imports spacers as sizeritems, so check for a spacer if ( xrcObj->FirstChildElement("size", false ) && !xrcObj->FirstChildElement("object", false ) ) { // it is a spacer XrcToXfbFilter spacer( xrcObj, _("spacer") ); spacer.AddPropertyPair( "size", _("width"), _("height") ); sizeritem->LinkEndChild( spacer.GetXfbObject() ); } return sizeritem; } }; class BoxSizerComponent : public ComponentBase { public: wxObject* Create(IObject* obj, wxObject* /*parent*/) override { wxBoxSizer *sizer = new wxBoxSizer(obj->GetPropertyAsInteger(_("orient"))); sizer->SetMinSize( obj->GetPropertyAsSize(_("minimum_size")) ); return sizer; } ticpp::Element* ExportToXrc(IObject* obj) override { ObjectToXrcFilter xrc(obj, _("wxBoxSizer")); if( obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize ) xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); xrc.AddProperty(_("orient"), _("orient"), XRC_TYPE_TEXT); return xrc.GetXrcObject(); } ticpp::Element* ImportFromXrc( ticpp::Element* xrcObj ) override { XrcToXfbFilter filter(xrcObj, _("wxBoxSizer")); filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); filter.AddProperty(_("orient"),_("orient"),XRC_TYPE_TEXT); return filter.GetXfbObject(); } }; class WrapSizerComponent : public ComponentBase { public: wxObject* Create(IObject* obj, wxObject* /*parent*/) override { const auto sizer = new wxWrapSizer(obj->GetPropertyAsInteger(_("orient")), obj->GetPropertyAsInteger(_("flags"))); sizer->SetMinSize( obj->GetPropertyAsSize(_("minimum_size")) ); return sizer; } ticpp::Element* ExportToXrc(IObject* obj) override { ObjectToXrcFilter xrc(obj, _("wxWrapSizer")); if (obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize) { xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); } xrc.AddProperty(_("orient"), _("orient"), XRC_TYPE_TEXT); xrc.AddProperty(_("flags"), _("flags"), XRC_TYPE_BITLIST); return xrc.GetXrcObject(); } ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { XrcToXfbFilter filter(xrcObj, _("wxWrapSizer")); filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); filter.AddProperty(_("orient"), _("orient"), XRC_TYPE_TEXT); filter.AddProperty(_("flags"), _("flags"), XRC_TYPE_BITLIST); return filter.GetXfbObject(); } }; class StaticBoxSizerComponent : public ComponentBase { public: int m_count; StaticBoxSizerComponent() { m_count = 0; } wxObject* Create(IObject* obj, wxObject* parent) override { m_count++; wxStaticBox* box = new wxStaticBox((wxWindow *)parent, wxID_ANY, obj->GetPropertyAsString(_("label"))); wxStaticBoxSizer* sizer = new wxStaticBoxSizer(box, obj->GetPropertyAsInteger(_("orient"))); sizer->SetMinSize( obj->GetPropertyAsSize(_("minimum_size")) ); return sizer; } ticpp::Element* ExportToXrc(IObject* obj) override { ObjectToXrcFilter xrc(obj, _("wxStaticBoxSizer")); if( obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize ) xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); xrc.AddProperty(_("orient"), _("orient"), XRC_TYPE_TEXT); xrc.AddProperty(_("label"), _("label"), XRC_TYPE_TEXT); return xrc.GetXrcObject(); } ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { XrcToXfbFilter filter(xrcObj, _("wxStaticBoxSizer")); filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); filter.AddProperty(_("orient"),_("orient"),XRC_TYPE_TEXT); filter.AddProperty(_("label"),_("label"),XRC_TYPE_TEXT); return filter.GetXfbObject(); } }; class GridSizerComponent : public ComponentBase { public: wxObject* Create(IObject* obj, wxObject* /*parent*/) override { wxGridSizer *sizer = new wxGridSizer( obj->GetPropertyAsInteger(_("rows")), obj->GetPropertyAsInteger(_("cols")), obj->GetPropertyAsInteger(_("vgap")), obj->GetPropertyAsInteger(_("hgap"))); sizer->SetMinSize( obj->GetPropertyAsSize(_("minimum_size")) ); return sizer; } ticpp::Element* ExportToXrc(IObject* obj) override { ObjectToXrcFilter xrc(obj, _("wxGridSizer")); if( obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize ) xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); xrc.AddProperty(_("rows"), _("rows"), XRC_TYPE_INTEGER); xrc.AddProperty(_("cols"), _("cols"), XRC_TYPE_INTEGER); xrc.AddProperty(_("vgap"), _("vgap"), XRC_TYPE_INTEGER); xrc.AddProperty(_("hgap"), _("hgap"), XRC_TYPE_INTEGER); return xrc.GetXrcObject(); } ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { XrcToXfbFilter filter(xrcObj, _("wxGridSizer")); filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); filter.AddProperty(_("rows"), _("rows"), XRC_TYPE_INTEGER); filter.AddProperty(_("cols"), _("cols"), XRC_TYPE_INTEGER); filter.AddProperty(_("vgap"), _("vgap"), XRC_TYPE_INTEGER); filter.AddProperty(_("hgap"), _("hgap"), XRC_TYPE_INTEGER); return filter.GetXfbObject(); } }; class FlexGridSizerBase : public ComponentBase { public: void AddProperties( IObject* obj, wxFlexGridSizer* sizer ) { for (const auto& col : obj->GetPropertyAsVectorIntPair(_("growablecols"))) { sizer->AddGrowableCol(col.first, col.second); } for (const auto& row : obj->GetPropertyAsVectorIntPair(_("growablerows"))) { sizer->AddGrowableRow(row.first, row.second); } sizer->SetMinSize( obj->GetPropertyAsSize(_("minimum_size")) ); sizer->SetFlexibleDirection( obj->GetPropertyAsInteger(_("flexible_direction")) ); sizer->SetNonFlexibleGrowMode( (wxFlexSizerGrowMode )obj->GetPropertyAsInteger(_("non_flexible_grow_mode")) ); } void ExportXRCProperties( ObjectToXrcFilter* xrc, IObject* obj ) { if( obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize ) xrc->AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); xrc->AddProperty(_("vgap"), _("vgap"), XRC_TYPE_INTEGER); xrc->AddProperty(_("hgap"), _("hgap"), XRC_TYPE_INTEGER); xrc->AddPropertyValue(_("growablecols"), obj->GetPropertyAsString(_("growablecols"))); xrc->AddPropertyValue(_("growablerows"), obj->GetPropertyAsString(_("growablerows"))); } void ImportXRCProperties( XrcToXfbFilter* filter ) { filter->AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); filter->AddProperty(_("vgap"), _("vgap"), XRC_TYPE_INTEGER); filter->AddProperty(_("hgap"), _("hgap"), XRC_TYPE_INTEGER); filter->AddProperty(_("growablecols"),_("growablecols"),XRC_TYPE_TEXT); filter->AddProperty(_("growablerows"),_("growablerows"),XRC_TYPE_TEXT); } }; class FlexGridSizerComponent : public FlexGridSizerBase { public: wxObject* Create(IObject* obj, wxObject* /*parent*/) override { wxFlexGridSizer *sizer = new wxFlexGridSizer( obj->GetPropertyAsInteger(_("rows")), obj->GetPropertyAsInteger(_("cols")), obj->GetPropertyAsInteger(_("vgap")), obj->GetPropertyAsInteger(_("hgap"))); AddProperties( obj, sizer ); return sizer; } ticpp::Element* ExportToXrc(IObject* obj) override { ObjectToXrcFilter xrc(obj, _("wxFlexGridSizer")); xrc.AddProperty(_("rows"), _("rows"), XRC_TYPE_INTEGER); xrc.AddProperty(_("cols"), _("cols"), XRC_TYPE_INTEGER); ExportXRCProperties( &xrc, obj ); return xrc.GetXrcObject(); } ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { XrcToXfbFilter filter(xrcObj, _("wxFlexGridSizer")); filter.AddProperty(_("rows"), _("rows"), XRC_TYPE_INTEGER); filter.AddProperty(_("cols"), _("cols"), XRC_TYPE_INTEGER); ImportXRCProperties( &filter ); return filter.GetXfbObject(); } }; class GridBagSizerComponent : public FlexGridSizerBase { private: wxGBSizerItem* GetGBSizerItem( IObject* sizeritem, const wxGBPosition& position, const wxGBSpan& span, wxObject* child ) { IObject* childObj = GetManager()->GetIObject( child ); if ( _("spacer") == childObj->GetClassName() ) { return new wxGBSizerItem( childObj->GetPropertyAsInteger( _("width") ), childObj->GetPropertyAsInteger( _("height") ), position, span, sizeritem->GetPropertyAsInteger(_("flag")), sizeritem->GetPropertyAsInteger(_("border")), NULL ); } // Add the child ( window or sizer ) to the sizer wxWindow* windowChild = wxDynamicCast( child, wxWindow ); wxSizer* sizerChild = wxDynamicCast( child, wxSizer ); if ( windowChild != NULL ) { return new wxGBSizerItem( windowChild, position, span, sizeritem->GetPropertyAsInteger(_("flag")), sizeritem->GetPropertyAsInteger(_("border")), NULL ); } else if ( sizerChild != NULL ) { return new wxGBSizerItem( sizerChild, position, span, sizeritem->GetPropertyAsInteger(_("flag")), sizeritem->GetPropertyAsInteger(_("border")), NULL ); } else { wxLogError( wxT("The GBSizerItem component's child is not a wxWindow or a wxSizer or a Spacer - this should not be possible!") ); return NULL; } } public: wxObject* Create(IObject* obj, wxObject* /*parent*/) override { wxGridBagSizer* sizer = new wxGridBagSizer( obj->GetPropertyAsInteger(_("vgap")), obj->GetPropertyAsInteger(_("hgap"))); if ( !obj->IsNull( _("empty_cell_size") ) ) { sizer->SetEmptyCellSize( obj->GetPropertyAsSize( _("empty_cell_size") ) ); } return sizer; } void OnCreated(wxObject* wxobject, wxWindow* /*wxparent*/) override { // For storing objects whose position needs to be determined std::vector< std::pair< wxObject*, wxGBSizerItem* > > newObjects; wxGBPosition lastPosition( 0, 0 ); // Get sizer wxGridBagSizer* sizer = wxDynamicCast( wxobject, wxGridBagSizer ); if ( NULL == sizer ) { wxLogError( wxT("This should be a wxGridBagSizer!") ); return; } // Add the children IManager* manager = GetManager(); size_t count = manager->GetChildCount( wxobject ); if ( 0 == count ) { // wxGridBagSizer gets upset sometimes without children sizer->Add( 0, 0, wxGBPosition( 0, 0 ) ); return; } for ( size_t i = 0; i < count; ++i ) { // Should be a GBSizerItem wxObject* wxsizerItem = manager->GetChild( wxobject, i ); IObject* isizerItem = manager->GetIObject( wxsizerItem ); // Get the location of the item wxGBSpan span( isizerItem->GetPropertyAsInteger( _("rowspan") ), isizerItem->GetPropertyAsInteger( _("colspan") ) ); int column = isizerItem->GetPropertyAsInteger( _("column") ); if ( column < 0 ) { // Needs to be auto positioned after the other children are added wxGBSizerItem* item = GetGBSizerItem( isizerItem, lastPosition, span, manager->GetChild( wxsizerItem, 0 ) ); if ( item != NULL ) { newObjects.push_back( std::pair< wxObject*, wxGBSizerItem* >( wxsizerItem, item ) ); } continue; } wxGBPosition position( isizerItem->GetPropertyAsInteger( _("row") ), column ); // Check for intersection if ( sizer->CheckForIntersection( position, span ) ) { continue; } lastPosition = position; // Add the child to the sizer wxGBSizerItem* item = GetGBSizerItem( isizerItem, position, span, manager->GetChild( wxsizerItem, 0 ) ); if ( item != NULL ) { sizer->Add( item ); } } std::vector< std::pair< wxObject*, wxGBSizerItem* > >::iterator it; for ( it = newObjects.begin(); it != newObjects.end(); ++it ) { wxGBPosition position = it->second->GetPos(); wxGBSpan span = it->second->GetSpan(); int column = position.GetCol(); while ( sizer->CheckForIntersection( position, span ) ) { column++; position.SetCol( column ); } it->second->SetPos( position ); sizer->Add( it->second ); GetManager()->ModifyProperty( it->first, _("row"), wxString::Format( wxT("%i"), position.GetRow() ), false ); GetManager()->ModifyProperty( it->first, _("column"), wxString::Format( wxT("%i"), column ), false ); } AddProperties(manager->GetIObject(wxobject), sizer); } ticpp::Element* ExportToXrc(IObject* obj) override { ObjectToXrcFilter xrc(obj, _("wxGridBagSizer")); ExportXRCProperties( &xrc, obj ); return xrc.GetXrcObject(); } ticpp::Element* ImportFromXrc(ticpp::Element* xrcObj) override { XrcToXfbFilter filter(xrcObj, _("wxGridBagSizer")); ImportXRCProperties( &filter ); return filter.GetXfbObject(); } }; class StdDialogButtonSizerComponent : public ComponentBase { private: void AddXRCButton( ticpp::Element* sizer, const std::string& id, const std::string& label ) { try { ticpp::Element button( "object" ); button.SetAttribute( "class", "button" ); ticpp::Element flag( "flag" ); flag.SetText( "wxALIGN_CENTER_HORIZONTAL|wxALL" ); button.LinkEndChild( &flag ); ticpp::Element border( "border" ); border.SetText( "5" ); button.LinkEndChild( &border ); ticpp::Element wxbutton( "object" ); wxbutton.SetAttribute( "class", "wxButton" ); wxbutton.SetAttribute( "name", id ); ticpp::Element labelEl( "label" ); labelEl.SetText( label ); wxbutton.LinkEndChild( &labelEl ); button.LinkEndChild( &wxbutton ); sizer->LinkEndChild( &button ); } catch( ticpp::Exception& ex ) { wxLogError( wxString( ex.m_details.c_str(), wxConvUTF8 ) ); } } public: wxObject* Create(IObject* obj, wxObject* parent) override { wxStdDialogButtonSizer* sizer = new wxStdDialogButtonSizer(); sizer->SetMinSize( obj->GetPropertyAsSize(_("minimum_size")) ); if (obj->GetPropertyAsInteger(_("OK")) != 0) { sizer->AddButton(new wxButton((wxWindow*)parent, wxID_OK)); } if (obj->GetPropertyAsInteger(_("Yes")) != 0) { sizer->AddButton(new wxButton((wxWindow*)parent, wxID_YES)); } if (obj->GetPropertyAsInteger(_("Save")) != 0) { sizer->AddButton(new wxButton((wxWindow*)parent, wxID_SAVE)); } if (obj->GetPropertyAsInteger(_("Apply")) != 0) { sizer->AddButton(new wxButton((wxWindow*)parent, wxID_APPLY)); } if (obj->GetPropertyAsInteger(_("No")) != 0) { sizer->AddButton(new wxButton((wxWindow*)parent, wxID_NO)); } if (obj->GetPropertyAsInteger(_("Cancel")) != 0) { sizer->AddButton(new wxButton((wxWindow*)parent, wxID_CANCEL)); } if (obj->GetPropertyAsInteger(_("Help")) != 0) { sizer->AddButton(new wxButton((wxWindow*)parent, wxID_HELP)); } if (obj->GetPropertyAsInteger(_("ContextHelp")) != 0) { sizer->AddButton(new wxButton((wxWindow*)parent, wxID_CONTEXT_HELP)); } sizer->Realize(); return sizer; } ticpp::Element* ExportToXrc(IObject* obj) override { ObjectToXrcFilter xrc(obj, _("wxStdDialogButtonSizer")); ticpp::Element* sizer = xrc.GetXrcObject(); if (obj->GetPropertyAsSize(_("minimum_size")) != wxDefaultSize) { xrc.AddProperty(_("minimum_size"), _("minsize"), XRC_TYPE_SIZE); } if (obj->GetPropertyAsInteger(_("OK")) != 0) { AddXRCButton(sizer, "wxID_OK", "&OK"); } if (obj->GetPropertyAsInteger(_("Yes")) != 0) { AddXRCButton(sizer, "wxID_YES", "&Yes"); } if (obj->GetPropertyAsInteger(_("Save")) != 0) { AddXRCButton(sizer, "wxID_SAVE", "&Save"); } if (obj->GetPropertyAsInteger(_("Apply")) != 0) { AddXRCButton(sizer, "wxID_APPLY", "&Apply"); } if (obj->GetPropertyAsInteger(_("No")) != 0) { AddXRCButton(sizer, "wxID_NO", "&No"); } if (obj->GetPropertyAsInteger(_("Cancel")) != 0) { AddXRCButton(sizer, "wxID_CANCEL", "&Cancel"); } if (obj->GetPropertyAsInteger(_("Help")) != 0) { AddXRCButton(sizer, "wxID_HELP", "&Help"); } if (obj->GetPropertyAsInteger(_("ContextHelp")) != 0) { AddXRCButton(sizer, "wxID_CONTEXT_HELP", ""); } return sizer; } ticpp::Element* ImportFromXrc( ticpp::Element* xrcObj ) override { std::map< wxString, wxString > buttons; buttons[ _("OK") ] = wxT("0"); buttons[ _("Yes") ] = wxT("0"); buttons[ _("Save") ] = wxT("0"); buttons[ _("Apply") ] = wxT("0"); buttons[ _("No") ] = wxT("0"); buttons[ _("Cancel") ] = wxT("0"); buttons[ _("Help") ] = wxT("0"); buttons[ _("ContextHelp") ] = wxT("0"); XrcToXfbFilter filter(xrcObj, _("wxStdDialogButtonSizer")); filter.AddProperty(_("minsize"), _("minimum_size"), XRC_TYPE_SIZE); ticpp::Element* button = xrcObj->FirstChildElement( "object", false ); for ( ; button != 0; button = button->NextSiblingElement( "object", false ) ) { try { std::string button_class; button->GetAttribute( "class", &button_class ); if ( std::string("button") != button_class ) { continue; } ticpp::Element* wxbutton = button->FirstChildElement( "object" ); std::string wxbutton_class; wxbutton->GetAttribute( "class", &wxbutton_class ); if ( std::string("wxButton") != wxbutton_class ) { continue; } std::string name; wxbutton->GetAttribute( "name", &name ); if ( name == "wxID_OK" ) { buttons[ _("OK") ] = wxT("1"); } else if ( name == "wxID_YES" ) { buttons[ _("Yes") ] = wxT("1"); } else if ( name == "wxID_SAVE" ) { buttons[ _("Save") ] = wxT("1"); } else if ( name == "wxID_APPLY" ) { buttons[ _("Apply") ] = wxT("1"); } else if ( name == "wxID_NO" ) { buttons[ _("No") ] = wxT("1"); } else if ( name == "wxID_CANCEL" ) { buttons[ _("Cancel") ] = wxT("1"); } else if ( name == "wxID_HELP" ) { buttons[ _("Help") ] = wxT("1"); } else if ( name == "wxID_CONTEXT_HELP" ) { buttons[ _("ContextHelp") ] = wxT("1"); } } catch( ticpp::Exception& ) { continue; } } std::map< wxString, wxString >::iterator prop; for ( prop = buttons.begin(); prop != buttons.end(); ++prop ) { filter.AddPropertyValue( prop->first, prop->second ); } xrcObj->Clear(); return filter.GetXfbObject(); } }; /////////////////////////////////////////////////////////////////////////////// BEGIN_LIBRARY() ABSTRACT_COMPONENT("spacer",SpacerComponent) ABSTRACT_COMPONENT("sizeritem",SizerItemComponent) ABSTRACT_COMPONENT("gbsizeritem",GBSizerItemComponent) SIZER_COMPONENT("wxBoxSizer",BoxSizerComponent) SIZER_COMPONENT("wxWrapSizer",WrapSizerComponent) SIZER_COMPONENT("wxStaticBoxSizer",StaticBoxSizerComponent) SIZER_COMPONENT("wxGridSizer",GridSizerComponent) SIZER_COMPONENT("wxFlexGridSizer",FlexGridSizerComponent) SIZER_COMPONENT("wxGridBagSizer",GridBagSizerComponent) SIZER_COMPONENT("wxStdDialogButtonSizer",StdDialogButtonSizerComponent) // wxBoxSizer MACRO(wxHORIZONTAL) MACRO(wxVERTICAL) // wxWrapSizer MACRO(wxEXTEND_LAST_ON_EACH_LINE) MACRO(wxREMOVE_LEADING_SPACES) MACRO(wxWRAPSIZER_DEFAULT_FLAGS) // wxFlexGridSizer MACRO(wxBOTH) MACRO(wxFLEX_GROWMODE_NONE) MACRO(wxFLEX_GROWMODE_SPECIFIED) MACRO(wxFLEX_GROWMODE_ALL) // Add MACRO(wxALL) MACRO(wxLEFT) MACRO(wxRIGHT) MACRO(wxTOP) MACRO(wxBOTTOM) MACRO(wxEXPAND) MACRO(wxALIGN_BOTTOM) MACRO(wxALIGN_CENTER) MACRO(wxALIGN_CENTER_HORIZONTAL) MACRO(wxALIGN_CENTER_VERTICAL) MACRO(wxSHAPED) MACRO(wxFIXED_MINSIZE) MACRO(wxRESERVE_SPACE_EVEN_IF_HIDDEN) SYNONYMOUS(wxGROW, wxEXPAND) SYNONYMOUS(wxALIGN_CENTRE, wxALIGN_CENTER) SYNONYMOUS(wxALIGN_CENTRE_HORIZONTAL, wxALIGN_CENTER_HORIZONTAL) SYNONYMOUS(wxALIGN_CENTRE_VERTICAL, wxALIGN_CENTER_VERTICAL) END_LIBRARY()
wxFormBuilder/wxFormBuilder
plugins/layout/layout.cpp
C++
gpl-2.0
24,753
/* global FullCalendar, FullCalendarLocales, FullCalendarInteraction */ var GLPIPlanning = { calendar: null, dom_id: "", all_resources: [], visible_res: [], drag_object: null, last_view: null, display: function(params) { // get passed options and merge it with default ones var options = (typeof params !== 'undefined') ? params: {}; var default_options = { full_view: true, default_view: 'timeGridWeek', height: GLPIPlanning.getHeight, plugins: ['dayGrid', 'interaction', 'list', 'timeGrid', 'resourceTimeline', 'rrule'], license_key: "", resources: [], now: null, rand: '', header: { left: 'prev,next,today', center: 'title', right: 'dayGridMonth, timeGridWeek, timeGridDay, listFull, resourceWeek' }, }; options = Object.assign({}, default_options, options); GLPIPlanning.dom_id = 'planning'+options.rand; var window_focused = true; var loaded = false; var disable_qtip = false; var disable_edit = false; // manage visible resources this.all_resources = options.resources; this.visible_res = Object.keys(this.all_resources).filter(function(index) { return GLPIPlanning.all_resources[index].is_visible; }); // get more space for planning if (options.full_view) { $('#'+GLPIPlanning.dom_id).closest('.ui-tabs').width('98%'); } this.calendar = new FullCalendar.Calendar(document.getElementById(GLPIPlanning.dom_id), { plugins: options.plugins, height: options.height, timeZone: 'UTC', theme: true, weekNumbers: options.full_view ? true : false, defaultView: options.default_view, timeFormat: 'H:mm', eventLimit: true, // show 'more' button when too mmany events minTime: CFG_GLPI.planning_begin, maxTime: CFG_GLPI.planning_end, schedulerLicenseKey: options.license_key, resourceAreaWidth: '15%', editable: true, // we can drag / resize items droppable: false, // we cant drop external items by default nowIndicator: true, now: options.now,// as we set the calendar as UTC, we need to reprecise the current datetime listDayAltFormat: false, agendaEventMinHeight: 13, header: options.header, //resources: options.resources, resources: function(fetchInfo, successCallback) { // Filter resources by whether their id is in visible_res. var filteredResources = []; filteredResources = options.resources.filter(function(elem, index) { return GLPIPlanning.visible_res.indexOf(index.toString()) !== -1; }); successCallback(filteredResources); }, views: { listFull: { type: 'list', titleFormat: function() { return ''; }, visibleRange: function(currentDate) { var current_year = currentDate.getFullYear(); return { start: (new Date(currentDate.getTime())).setFullYear(current_year - 5), end: (new Date(currentDate.getTime())).setFullYear(current_year + 5) }; } }, resourceWeek: { type: 'resourceTimeline', buttonText: 'Timeline Week', duration: { weeks: 1 }, //hiddenDays: [6, 0], groupByDateAndResource: true, slotLabelFormat: [ { week: 'short' }, { weekday: 'short', day: 'numeric', month: 'numeric', omitCommas: true }, function(date) { return date.date.hour; } ] }, }, resourceRender: function(info) { var icon = ""; var itemtype = info.resource._resource.extendedProps.itemtype || ""; switch (itemtype.toLowerCase()) { case "group": case "group_user": icon = "users"; break; case "user": icon = "user"; } $(info.el) .find('.fc-cell-text') .prepend('<i class="fas fa-'+icon+'"></i>&nbsp;'); if (info.resource._resource.extendedProps.itemtype == 'Group_User') { info.el.style.backgroundColor = 'lightgray'; } }, eventRender: function(info) { var event = info.event; var extProps = event.extendedProps; var element = $(info.el); var view = info.view; // append event data to dom (to re-use they in clone behavior) element.data('myevent', event); var eventtype_marker = '<span class="event_type" style="background-color: '+extProps.typeColor+'"></span>'; element.append(eventtype_marker); var content = extProps.content; var tooltip = extProps.tooltip; if (view.type !== 'dayGridMonth' && view.type.indexOf('list') < 0 && event.rendering != "background" && !event.allDay){ element.append('<div class="content">'+content+'</div>'); } // add icon if exists if ("icon" in extProps) { var icon_alt = ""; if ("icon_alt" in extProps) { icon_alt = extProps.icon_alt; } element.find(".fc-title, .fc-list-item-title") .append("&nbsp;<i class='"+extProps.icon+"' title='"+icon_alt+"'></i>"); } // add classes to current event var added_classes = ''; if (typeof event.end !== 'undefined' && event.end !== null) { var now = new Date(); var end = event.end; added_classes = end.getTime() < now.getTime() ? ' event_past' : ''; added_classes+= end.getTime() > now.getTime() ? ' event_future' : ''; added_classes+= end.toDateString() === now.toDateString() ? ' event_today' : ''; } if (extProps.state != '') { added_classes+= extProps.state == 0 ? ' event_info' : extProps.state == 1 ? ' event_todo' : extProps.state == 2 ? ' event_done' : ''; } if (added_classes != '') { element.addClass(added_classes); } // add tooltip to event if (!disable_qtip) { // detect ideal position var qtip_position = { target: 'mouse', adjust: { mouse: false }, viewport: $(window) }; if (view.type.indexOf('list') >= 0) { // on central, we want the tooltip on the anchor // because the event is 100% width and so tooltip will be too much on the right. qtip_position.target= element.find('a'); } // show tooltips element.qtip({ position: qtip_position, content: tooltip, style: { classes: 'qtip-shadow qtip-bootstrap' }, show: { solo: true, delay: 100 }, hide: { fixed: true, delay: 100 }, events: { show: function(event) { if (!window_focused) { event.preventDefault(); } } } }); } // context menu element.on('contextmenu', function(e) { // prevent display of browser context menu e.preventDefault(); // get offset of the event var offset = element.offset(); // remove old instances $('.planning-context-menu').remove(); // create new one var context = $('<ul class="planning-context-menu" data-event-id=""> \ <li class="clone-event"><i class="far fa-clone"></i>'+__("Clone")+'</li> \ <li class="delete-event"><i class="fas fa-trash"></i>'+__("Delete")+'</li> \ </ul>'); // add it to body and place it correctly $('body').append(context); context.css({ left: offset.left + element.outerWidth() / 4, top: offset.top }); // get properties of event for context menu actions var extprops = event.extendedProps; var resource = {}; var actor = {}; if (typeof event.getresources === "function") { resource = event.getresources(); } // manage resource changes if (resource.length === 1) { actor = { itemtype: resource[0].extendedProps.itemtype || null, items_id: resource[0].extendedProps.items_id || null, }; } // context menu actions // 1- clone event $('.planning-context-menu .clone-event').click(function() { $.ajax({ url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', data: { action: 'clone_event', event: { old_itemtype: extprops.itemtype, old_items_id: extprops.items_id, actor: actor, start: event.start.toISOString(), end: event.end.toISOString(), } }, success: function() { GLPIPlanning.refresh(); } }); }); // 2- delete event (manage serie/instance specific events) $('.planning-context-menu .delete-event').click(function() { var ajaxDeleteEvent = function(instance) { instance = instance || false; $.ajax({ url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', data: { action: 'delete_event', event: { itemtype: extprops.itemtype, items_id: extprops.items_id, day: event.start.toISOString().substring(0, 10), instance: instance ? 1 : 0, } }, success: function() { GLPIPlanning.refresh(); } }); }; if (!("is_recurrent" in extprops) || !extprops.is_recurrent) { ajaxDeleteEvent(); } else { $('<div title="'+__("Make a choice")+'"></div>') .html(__("Delete the whole serie of the recurrent event") + "<br>" + __("or just add an exception by deleting this instance?")) .dialog({ resizable: false, height: "auto", width: "auto", modal: true, buttons: [ { text: $("<div/>").html(__("Serie")).text(), // html/text method to remove html entities icon: "ui-icon-trash", click: function() { ajaxDeleteEvent(false); $(this).dialog("close"); } }, { text: $("<div/>").html(__("Instance")).text(), // html/text method to remove html entities icon: "ui-icon-trash", click: function() { ajaxDeleteEvent(true); $(this).dialog("close"); } } ] }); } }); }); }, datesRender: function(info) { var view = info.view; // force refetch events from ajax on view change (don't refetch on first load) if (loaded) { GLPIPlanning.refresh(); } else { loaded = true; } // attach button (planning and refresh) in planning header $('#'+GLPIPlanning.dom_id+' .fc-toolbar .fc-center h2') .after( $('<i id="refresh_planning" class="fa fa-sync pointer"></i>') ).after( $('<div id="planning_datepicker"><a data-toggle><i class="far fa-calendar-alt fa-lg pointer"></i></a>') ); // specific process for full list if (view.type == 'listFull') { // hide datepick on full list (which have virtually no limit) if ($('#planning_datepicker').length > 0 && "_flatpickr" in $('#planning_datepicker')[0]) { $('#planning_datepicker')[0]._flatpickr.destroy(); } $('#planning_datepicker').hide(); // hide control buttons $('#planning .fc-left .fc-button-group').hide(); } else { // reinit datepicker $('#planning_datepicker').show(); GLPIPlanning.initFCDatePicker(new Date(view.currentStart)); // show controls buttons $('#planning .fc-left .fc-button-group').show(); } // set end of day markers for timeline GLPIPlanning.setEndofDays(info.view); }, viewSkeletonRender: function(info) { var view_type = info.view.type; GLPIPlanning.last_view = view_type; // inform backend we changed view (to store it in session) $.ajax({ url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', data: { action: 'view_changed', view: view_type } }); // set end of day markers for timeline GLPIPlanning.setEndofDays(info.view); }, events: { url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', extraParams: function() { var view_name = GLPIPlanning.calendar ? GLPIPlanning.calendar.state.viewType : options.default_view; var display_done_events = 1; if (view_name.indexOf('list') >= 0) { display_done_events = 0; } return { 'action': 'get_events', 'display_done_events': display_done_events, 'view_name': view_name }; }, success: function(data) { if (!options.full_view && data.length == 0) { GLPIPlanning.calendar.setOption('height', 0); } }, failure: function(error) { console.error('there was an error while fetching events!', error); } }, // EDIT EVENTS eventResize: function(info) { var event = info.event; var exprops = event.extendedProps; var is_recurrent = exprops.is_recurrent || false; if (is_recurrent) { $('<div></div>') .dialog({ modal: true, title: __("Recurring event resized"), width: 'auto', height: 'auto', buttons: [ { text: __("Serie"), click: function() { $(this).remove(); GLPIPlanning.editEventTimes(info); } }, { text: __("Instance"), click: function() { $(this).remove(); GLPIPlanning.editEventTimes(info, true); } } ] }).text(__("The resized event is a recurring event. Do you want to change the serie or instance ?")); } else { GLPIPlanning.editEventTimes(info); } }, eventResizeStart: function() { disable_edit = true; disable_qtip = true; }, eventResizeStop: function() { setTimeout(function(){ disable_edit = false; disable_qtip = false; }, 300); }, eventDragStart: function() { disable_qtip = true; }, // event was moved (internal element) eventDrop: function(info) { disable_qtip = false; var event = info.event; var exprops = event.extendedProps; var is_recurrent = exprops.is_recurrent || false; if (is_recurrent) { $('<div></div>') .dialog({ modal: true, title: __("Recurring event dragged"), width: 'auto', height: 'auto', buttons: [ { text: __("Serie"), click: function() { $(this).remove(); GLPIPlanning.editEventTimes(info); } }, { text: __("Instance"), click: function() { $(this).remove(); GLPIPlanning.editEventTimes(info, true); } } ] }).text(__("The dragged event is a recurring event. Do you want to move the serie or instance ?")); } else { GLPIPlanning.editEventTimes(info); } }, eventClick: function(info) { var event = info.event; var editable = event.extendedProps._editable; // do not know why editable property is not available if (event.extendedProps.ajaxurl && editable && !disable_edit) { var start = event.start; var ajaxurl = event.extendedProps.ajaxurl+"&start="+start.toISOString(); info.jsEvent.preventDefault(); // don't let the browser navigate $('<div></div>') .dialog({ modal: true, width: 'auto', height: 'auto', close: function() { GLPIPlanning.refresh(); } }) .load(ajaxurl, function() { $(this).dialog({ position: { my: 'center', at: 'center', viewport: $(window), of: $('#page'), collision: 'fit' } }); }); } }, // ADD EVENTS selectable: true, select: function(info) { var itemtype = (((((info || {}) .resource || {}) ._resource || {}) .extendedProps || {}) .itemtype || ''); var items_id = (((((info || {}) .resource || {}) ._resource || {}) .extendedProps || {}) .items_id || 0); // prevent adding events on group users if (itemtype === 'Group_User') { GLPIPlanning.calendar.unselect(); return false; } var start = info.start; var end = info.end; $('<div></div>').dialog({ modal: true, width: 'auto', height: 'auto', open: function () { $(this).load( CFG_GLPI.root_doc+"/ajax/planning.php", { action: 'add_event_fromselect', begin: start.toISOString(), end: end.toISOString(), res_itemtype: itemtype, res_items_id: items_id, }, function() { $(this).dialog({ position: { my: 'center', at: 'center', viewport: $(window), of: $('#page'), collision: 'fit' } }); } ); }, close: function() { $(this).dialog("close"); $(this).remove(); }, position: { my: 'center', at: 'center top', viewport: $(window), of: $('#page') } }); GLPIPlanning.calendar.unselect(); } }); var loadedLocales = Object.keys(FullCalendarLocales); if (loadedLocales.length === 1) { GLPIPlanning.calendar.setOption('locale', loadedLocales[0]); } $('.planning_on_central a') .mousedown(function() { disable_qtip = true; $('.qtip').hide(); }) .mouseup(function() { disable_qtip = false; }); window.onblur = function() { window_focused = false; }; window.onfocus = function() { window_focused = true; }; //window.calendar = calendar; // Required as object is not accessible by forms callback GLPIPlanning.calendar.render(); $('#refresh_planning').click(function() { GLPIPlanning.refresh(); }); // attach the date picker to planning GLPIPlanning.initFCDatePicker(); // force focus on the current window $(window).focus(); // remove all context menus on document click $(document).click(function() { $('.planning-context-menu').remove(); }); }, refresh: function() { if (typeof(GLPIPlanning.calendar.refetchResources) == 'function') { GLPIPlanning.calendar.refetchResources(); } GLPIPlanning.calendar.refetchEvents(); GLPIPlanning.calendar.rerenderEvents(); window.displayAjaxMessageAfterRedirect(); }, // add/remove resource (like when toggling it in side bar) toggleResource: function(res_name, active) { // find the index of current resource to find it in our array of visible resources var index = GLPIPlanning.all_resources.findIndex(function(current) { return current.id == res_name; }); if (index !== -1) { // add only if not already present if (active && GLPIPlanning.visible_res.indexOf(index.toString()) === -1) { GLPIPlanning.visible_res.push(index.toString()); } else if (!active) { GLPIPlanning.visible_res.splice(GLPIPlanning.visible_res.indexOf(index.toString()), 1); } } }, setEndofDays: function(view) { // add a class to last col of day in timeline view // to visualy separate days if (view.constructor.name === "ResourceTimelineView") { // compute the number of hour slots displayed var time_beg = CFG_GLPI.planning_begin.split(':'); var time_end = CFG_GLPI.planning_end.split(':'); var int_beg = parseInt(time_beg[0]) * 60 + parseInt(time_beg[1]); var int_end = parseInt(time_end[0]) * 60 + parseInt(time_end[1]); var sec_inter = int_end - int_beg; var nb_slots = Math.ceil(sec_inter / 60); // add class to day list header $('#planning .fc-time-area.fc-widget-header table tr:nth-child(2) th') .addClass('end-of-day'); // add class to hours list header $('#planning .fc-time-area.fc-widget-header table tr:nth-child(3) th:nth-child('+nb_slots+'n)') .addClass('end-of-day'); // add class to content bg (content slots) $('#planning .fc-time-area.fc-widget-content table td:nth-child('+nb_slots+'n)') .addClass('end-of-day'); } }, planningFilters: function() { $('#planning_filter a.planning_add_filter' ).on( 'click', function( e ) { e.preventDefault(); // to prevent change of url on anchor var url = $(this).attr('href'); $('<div></div>').dialog({ modal: true, open: function () { $(this).load(url); }, position: { my: 'top', at: 'center', of: $('#planning_filter') } }); }); $('#planning_filter .filter_option').on( 'click', function() { $(this).children('ul').toggle(); }); $(document).click(function(e){ if ($(e.target).closest('#planning_filter .filter_option').length === 0) { $('#planning_filter .filter_option ul').hide(); } }); $('#planning_filter .delete_planning').on( 'click', function() { var deleted = $(this); var li = deleted.closest('ul.filters > li'); $.ajax({ url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', data: { action: 'delete_filter', filter: deleted.attr('value'), type: li.attr('event_type') }, success: function() { li.remove(); GLPIPlanning.refresh(); } }); }); var sendDisplayEvent = function(current_checkbox, refresh_planning) { var current_li = current_checkbox.parents('li'); var parent_name = null; if (current_li.parent('ul.group_listofusers').length == 1) { parent_name = current_li .parent('ul.group_listofusers') .parent('li') .attr('event_name'); } var event_name = current_li.attr('event_name'); var event_type = current_li.attr('event_type'); var checked = current_checkbox.is(':checked'); return $.ajax({ url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', data: { action: 'toggle_filter', name: event_name, type: event_type, parent: parent_name, display: checked }, success: function() { GLPIPlanning.toggleResource(event_name, checked); if (refresh_planning) { // don't refresh planning if event triggered from parent checkbox GLPIPlanning.refresh(); } } }); }; $('#planning_filter li:not(li.group_users) input[type="checkbox"]') .on( 'click', function() { sendDisplayEvent($(this), true); }); $('#planning_filter li.group_users > span > input[type="checkbox"]') .on('change', function() { var parent_checkbox = $(this); var parent_li = parent_checkbox.parents('li'); var checked = parent_checkbox.prop('checked'); var event_name = parent_li.attr('event_name'); var chidren_checkboxes = parent_checkbox .parents('li.group_users') .find('ul.group_listofusers input[type="checkbox"]'); chidren_checkboxes.prop('checked', checked); var promises = []; chidren_checkboxes.each(function() { promises.push(sendDisplayEvent($(this), false)); }); GLPIPlanning.toggleResource(event_name, checked); // refresh planning once for all checkboxes (and not for each) // after theirs promises done $.when.apply($, promises).then(function() { GLPIPlanning.refresh(); }); }); $('#planning_filter .color_input input').on('change', function() { var current_li = $(this).parents('li'); var parent_name = null; if (current_li.length >= 1) { parent_name = current_li.eq(1).attr('event_name'); current_li = current_li.eq(0); } $.ajax({ url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', data: { action: 'color_filter', name: current_li.attr('event_name'), type: current_li.attr('event_type'), parent: parent_name, color: $(this).val() }, success: function() { GLPIPlanning.refresh(); } }); }); $('#planning_filter li.group_users .toggle').on('click', function() { $(this).parent().toggleClass('expanded'); }); $('#planning_filter_toggle > a.toggle').on('click', function() { $('#planning_filter_content').animate({ width:'toggle' }, 300, 'swing', function() { $('#planning_filter').toggleClass('folded'); $('#planning_container').toggleClass('folded'); }); }); }, // send ajax for event storage (on event drag/resize) editEventTimes: function(info, move_instance) { move_instance = move_instance || false; var event = info.event; var revertFunc = info.revert; var extProps = event.extendedProps; var old_itemtype = null; var old_items_id = null; var new_itemtype = null; var new_items_id = null; // manage moving the events between resources (users, groups) if ("newResource" in info && info.newResource !== null) { var new_extProps = info.newResource._resource.extendedProps; new_itemtype = new_extProps.itemtype; new_items_id = new_extProps.items_id; } if ("oldResource" in info && info.oldResource !== null) { var old_extProps = info.oldResource._resource.extendedProps; old_itemtype = old_extProps.itemtype; old_items_id = old_extProps.items_id; } var start = event.start; var end = event.end; if (typeof end === 'undefined' || end === null) { end = new Date(start.getTime()); if (event.allDay) { end.setDate(end.getDate() + 1); } else { end.setHours(end.getHours() + 2); } } var old_event = info.oldEvent || {}; var old_start = old_event.start || start; $.ajax({ url: CFG_GLPI.root_doc+"/ajax/planning.php", type: 'POST', data: { action: 'update_event_times', start: start.toISOString(), end: end.toISOString(), itemtype: extProps.itemtype, items_id: extProps.items_id, move_instance: move_instance, old_start: old_start.toISOString(), new_actor_itemtype: new_itemtype, new_actor_items_id: new_items_id, old_actor_itemtype: old_itemtype, old_actor_items_id: old_items_id, }, success: function(html) { if (!html) { revertFunc(); } GLPIPlanning.refresh(); }, error: function() { revertFunc(); } }); }, // datepicker for planning initFCDatePicker: function(currentDate) { $('#planning_datepicker').flatpickr({ defaultDate: currentDate, onChange: function(selected_date) { // convert to UTC to avoid timezone issues var date = new Date( Date.UTC( selected_date[0].getFullYear(), selected_date[0].getMonth(), selected_date[0].getDate() ) ); GLPIPlanning.calendar.gotoDate(date); } }); }, // set planning height getHeight: function() { var _newheight = $(window).height() - 272; if ($('#debugajax').length > 0) { _newheight -= $('#debugajax').height(); } if (CFG_GLPI.glpilayout == 'vsplit') { _newheight = $('.ui-tabs-panel').height() - 30; } //minimal size var _minheight = 300; if (_newheight < _minheight) { _newheight = _minheight; } return _newheight; }, };
smartcitiescommunity/Civikmind
js/planning.js
JavaScript
gpl-2.0
34,622
package controllers; import static akka.pattern.Patterns.ask; import static play.libs.Json.toJson; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.Date; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import models.Atualizacao; import models.AtualizacaoDAO; import models.CidadaoDAO; import play.Configuration; import play.Logger; import play.db.jpa.JPAApi; import play.db.jpa.Transactional; import play.libs.ws.WSClient; import play.libs.ws.WSRequest; import play.mvc.Controller; import play.mvc.Result; import scala.concurrent.duration.Duration; import actors.AtualizadorActorProtocol; import akka.actor.ActorRef; import akka.actor.ActorSystem; @Singleton public class AtualizacaoController extends Controller { private ActorRef atualizador; private AtualizacaoDAO daoAtualizacao; private WSRequest atualizacaoURL; private Pattern padraoDaDataDePublicacao; private JPAApi jpaAPI; private boolean atualizacaoAtivada; private String identificadorUnicoDoServidor; private String dataVotada; @Inject public AtualizacaoController(AtualizacaoDAO daoAtualizacao, CidadaoDAO daoCidadao, @Named("atualizador-actor") ActorRef atualizador, ActorSystem system, Configuration configuration, WSClient client, JPAApi jpaAPI) { this.daoAtualizacao = daoAtualizacao; this.atualizador = atualizador; this.jpaAPI = jpaAPI; this.atualizacaoAtivada = configuration.getBoolean("diferentonas.atualizacao.automatica", false); if(atualizacaoAtivada){ LocalDateTime now = LocalDateTime.now(); LocalDateTime manha = LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 6, 0); LocalDateTime noite = LocalDateTime.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth(), 18, 0); long delay; if(now.isBefore(manha)){ delay = manha.atZone(ZoneOffset.systemDefault()).toEpochSecond() - now.atZone(ZoneOffset.systemDefault()).toEpochSecond(); }else if(now.isBefore(noite)){ delay = noite.atZone(ZoneOffset.systemDefault()).toEpochSecond() - now.atZone(ZoneOffset.systemDefault()).toEpochSecond(); }else{ delay = manha.plusDays(1).atZone(ZoneOffset.systemDefault()).toEpochSecond() - now.atZone(ZoneOffset.systemDefault()).toEpochSecond(); } system.scheduler().schedule(Duration.create(delay, TimeUnit.SECONDS), Duration.create(12, TimeUnit.HOURS), () -> { this.votaEmLider(); }, system.dispatcher()); system.scheduler().schedule(Duration.create(delay + 3600, TimeUnit.SECONDS), Duration.create(12, TimeUnit.HOURS), () -> { this.elegeLiderEAtualiza(); }, system.dispatcher()); this.atualizacaoURL = client.url(configuration.getString("diferentonas.url", "http://portal.convenios.gov.br/download-de-dados")); this.padraoDaDataDePublicacao = Pattern.compile("\\d\\d\\/\\d\\d\\/\\d\\d\\d\\d\\s\\d\\d:\\d\\d:\\d\\d"); this.identificadorUnicoDoServidor = UUID.randomUUID().toString(); Logger.info("ID do servidor: " + this.identificadorUnicoDoServidor); if(configuration.getBoolean("diferentonas.demo.forcaatualizacao", false)){ Logger.info("Iniciando votação extraordinária!"); this.votaEmLider(); try { Thread.sleep(10000); } catch (InterruptedException e) { Logger.error("Dormiu durante a eleição!", e); } Logger.info("Elegendo lider para atualização de urgência!"); this.elegeLiderEAtualiza(); } } } private void votaEmLider() { atualizacaoURL.get().thenApply(response -> { Logger.info("Conexão realizada."); String body = response.getBody(); Matcher matcher = padraoDaDataDePublicacao.matcher(body); if(matcher.find()){ String data = matcher.group(0); this.dataVotada = data; Logger.info("Votando para " + data + " em " + identificadorUnicoDoServidor); jpaAPI.withTransaction(()->daoAtualizacao.vota(data, identificadorUnicoDoServidor)); }else{ Logger.info("Problemas ao acessar página em: " + atualizacaoURL.getUrl()); } return ok(); }); } private void elegeLiderEAtualiza() { Atualizacao lider = jpaAPI.withTransaction(()->daoAtualizacao.getLider(dataVotada)); if(lider == null){ Logger.warn("Impossível eleger lider! Não houveram votos para data: " + dataVotada); return; } if(this.identificadorUnicoDoServidor.equals(lider.getServidorResponsavel())){ Logger.info("Iniciando atualização de dados às: " + new Date() + " com dados publicados em: " + dataVotada); ask(atualizador, new AtualizadorActorProtocol.AtualizaIniciativasEScores(dataVotada, identificadorUnicoDoServidor), 1000L); } } @Transactional public Result getStatus() { return ok(toJson(daoAtualizacao.getMaisRecentes())); } }
nazareno/diferentonas-server
app/controllers/AtualizacaoController.java
Java
gpl-2.0
4,867
#include "ComboBox.h" #include <QDebug> ComboBox::ComboBox(QWidget* parent) : QComboBox(parent) { } ComboBox::~ComboBox() { } void ComboBox::setCurrentItemById(const int id) { const int size = count(); for (int i = 0; i < size; ++i) { if (id == itemData(i).toInt()) { setCurrentIndex(i); return; } } qDebug() << __FUNCTION__ << "Cannot find id: " << id; } int ComboBox::currentId() { return itemData(currentIndex()).toInt(); }
CBRUhelsinki/CENTplatform
CENTSources/cent/CENTSystem/CENTApplication/src/ui/ComboBox.cpp
C++
gpl-2.0
488
class Solution { public: int minCut(string s) { if (s.size() < 2) { return 0; } int len = s.size(); vector<int> cut(len + 1, 0); // cut[i] : s[0..i-1] min cut for (int i = 0; i <= len; i++) { cut[i] = i - 1; } for (int i = 0; i < len; i++) { // odd len for (int l = 0; i - l >= 0 && i + l < len && s[i - l] == s[i + l]; l++) { cut[i + l + 1] = min(cut[i + l + 1], cut[i - l - 1 + 1] + 1); } // even // i,i+1 for (int l = 0; i - l >= 0 && i + 1 + l < len && s[i - l] == s[i + 1 + l]; l++) { cut[i + 1 + l + 1] = min(cut[i + 1 + l + 1], cut[i - l - 1 + 1] + 1); } } return cut[len]; } };
gyang/Algo
leetcode/Palindrome Partitioning II/main1.cpp
C++
gpl-2.0
711
<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' ); /** * * @version $Id: checkout_bar.php 617 2007-01-04 19:43:08Z soeren_nb $ * @package VirtueMart * @subpackage html * @copyright Copyright (C) 2004-2005 Soeren Eberhardt. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details. * * http://virtuemart.net */ mm_showMyFileName( __FILE__ ); /* First, here we have the checkout definitions * Tell me if we can do this less complicated */ if (CHECKOUT_STYLE == '1' ) { $steps_to_do = array(CHECK_OUT_GET_SHIPPING_ADDR, CHECK_OUT_GET_SHIPPING_METHOD, CHECK_OUT_GET_PAYMENT_METHOD, CHECK_OUT_GET_FINAL_CONFIRMATION); $step_msg = array($VM_LANG->_PHPSHOP_ADD_SHIPTO_2,$VM_LANG->_PHPSHOP_ISSHIP_LIST_CARRIER_LBL,$VM_LANG->_PHPSHOP_ORDER_PRINT_PAYMENT_LBL, $VM_LANG->_PHPSHOP_CHECKOUT_CONF_PAYINFO_COMPORDER); $step_count = 4; } elseif (CHECKOUT_STYLE == '2') { $steps_to_do = array(CHECK_OUT_GET_SHIPPING_ADDR, CHECK_OUT_GET_PAYMENT_METHOD, CHECK_OUT_GET_FINAL_CONFIRMATION); $step_msg = array($VM_LANG->_PHPSHOP_ADD_SHIPTO_2, $VM_LANG->_PHPSHOP_ORDER_PRINT_PAYMENT_LBL, $VM_LANG->_PHPSHOP_CHECKOUT_CONF_PAYINFO_COMPORDER); $step_count = 3; } elseif (CHECKOUT_STYLE == '3') { $steps_to_do = array(CHECK_OUT_GET_SHIPPING_METHOD, CHECK_OUT_GET_PAYMENT_METHOD, CHECK_OUT_GET_FINAL_CONFIRMATION); $step_msg = array($VM_LANG->_PHPSHOP_ISSHIP_LIST_CARRIER_LBL, $VM_LANG->_PHPSHOP_ORDER_PRINT_PAYMENT_LBL, $VM_LANG->_PHPSHOP_CHECKOUT_CONF_PAYINFO_COMPORDER); $step_count = 3; } elseif (CHECKOUT_STYLE == '4') { $steps_to_do = array(CHECK_OUT_GET_PAYMENT_METHOD, CHECK_OUT_GET_FINAL_CONFIRMATION); $step_msg = array($VM_LANG->_PHPSHOP_ORDER_PRINT_PAYMENT_LBL, $VM_LANG->_PHPSHOP_CHECKOUT_CONF_PAYINFO_COMPORDER); $step_count = 2; } if (empty($checkout_this_step)) { $checkout_this_step=''; } switch ($checkout_this_step) { case CHECK_OUT_GET_SHIPPING_ADDR: $highlighted_step = 1; break; case CHECK_OUT_GET_SHIPPING_METHOD: if (NO_SHIPTO != '1') { $highlighted_step = 2; } else { $highlighted_step = 1; } break; case CHECK_OUT_GET_PAYMENT_METHOD: if (CHECKOUT_STYLE == '4') { $highlighted_step = 1; } elseif (NO_SHIPPING == '1' || NO_SHIPTO == '1' || CHECKOUT_STYLE == '2') { $highlighted_step = 2; } else { $highlighted_step =3; } break; case CHECK_OUT_GET_FINAL_CONFIRMATION: if (CHECKOUT_STYLE == '4') { $highlighted_step = 2; } elseif (NO_SHIPPING == '1' || NO_SHIPTO == '1' || CHECKOUT_STYLE == '2') { $highlighted_step =3; } else { $highlighted_step =4; } break; default: $highlighted_step = 1; break; } ps_checkout::show_checkout_bar($steps_to_do, $step_msg, $step_count, $highlighted_step); ?>
foresitegroup/sherwin
administrator/components/com_virtuemart/html/checkout_bar.php
PHP
gpl-2.0
3,126
/* * nassh-relay - Relay Server for tunneling ssh through a http endpoint * * Website: https://github.com/zyclonite/nassh-relay * * Copyright 2014-2020 zyclonite networx * http://zyclonite.net * Developer: Lukas Prettenthaler */ package net.zyclonite.nassh.util; import io.vertx.core.http.HttpServerRequest; public class RequestHelper { private RequestHelper() { // } public static String getHost(final HttpServerRequest request) { if (request.headers().contains("X-Forwarded-Host")) { return request.headers().get("X-Forwarded-Host"); } else { return request.host(); } } public static String getRemoteHost(final HttpServerRequest request) { if (request.headers().contains("X-Real-IP")) { return request.headers().get("X-Real-IP"); } else { return request.remoteAddress().host(); } } }
zyclonite/nassh-relay
src/main/java/net/zyclonite/nassh/util/RequestHelper.java
Java
gpl-2.0
953
<?php include "layout/header.php"; ?> <div class="bg_body"> <section class="container-fluid"> <div class="col-xs-12 col-sm-12 col-md-7 col-md-offset-1"> <?php $i = 0; ?> <?php if (have_posts()) { while (have_posts()) { print_r(the_post()); $i++; ?> <div class="post"> <div class="titulo row-fluid"> <div class="numero"><?php echo $i; ?></div> <div class="nome"> <h1> <?php echo the_title(); ?> </h1> <p>Posted by: <?php the_author(); ?> - <?php the_time('d/m/Y'); ?></p> </div> </div> <div class="corpo"> <div class="resumo" ><?php the_content(); ?></div> </div> <div class="menu"> </div> <div class="div_buttom"> <a href="" class="btn btn-mariana">Leia mais</a> </div> </div> <?php } } ?> <ol class="commentlist"> <?php $id = get_the_ID(); //Gather comments for a specific page/post $comments = get_comments(array( 'post_id' => $id, 'status' => 'approve' //Change this to the type of comments to be displayed )); //Display the list of comments wp_list_comments(array( 'per_page' => 10, //Allow comment pagination 'reverse_top_level' => false //Show the latest comments at the top of the list ), $comments); ?> </ol> <?php $args = array( 'title_reply' => 'Deixe um comentário' , 'label_submit' => 'Enviar comentário' ); comment_form( $args, $id ); ?> </div> <div id="listagem" class="col-xs-12 col-sm-12 col-md-4"> <div class="busca"> <form action="" method="POST"> <input type="text" placeholder="Buscar..."> <button type="submit" name="busca"><img src="<?php bloginfo('template_url'); ?>/img/lupa.png"></button> </form> </div> <div class="posts_anteriores"> <h3><img src="<?php bloginfo('template_url'); ?>/img/ico_post_anteriores.png">Posts anteriores</h3> <div class="item">Post de Abril de 2015</div> <div class="item">Post de Março de 2015</div> <div class="item">Post de Fevereiro de 2015</div> </div> </div> </section> </div> <?php include "layout/footer.php"; ?>
Jehny/wp_mariana
wp-content/themes/mariana/single.php
PHP
gpl-2.0
2,251
/* *GRASP(Geo-referential Real-time Acquisition Statistics Platform) Reporting Tool <http://www.brainsen.com> * Developed by Brains Engineering s.r.l (marco.giorgi@brainsen.com) * This file is part of GRASP Reporting Tool. * GRASP Reporting Tool 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. * GRASP Reporting Tool 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 GRASP Reporting Tool. * If not, see <http://www.gnu.org/licenses/> */ using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// ResponseFormList class contains the structure for the responses to some Grasp API /// </summary> public class ResponseFormList { public int FR_id { get; set; } public string FR_clientVersion { get; set; } public string FR_sender { get; set; } public int FR_FParentID { get; set; } public string FR_codeForm { get; set; } public DateTime FR_createDate { get; set; } }
WFPVAM/GRASPReporting
src/App_Code/ResponseFormList.cs
C#
gpl-2.0
1,429
/* * Copyright (C) 2008-2015 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "AuthCodes.h" #include "BitStream.h" #include "PacketManager.h" #include "SessionManager.h" #include "Database/DatabaseEnv.h" #include "HmacHash.h" #include "Log.h" #include "RealmList.h" #include "SHA256.h" #include <map> Battlenet::Session::ModuleHandler const Battlenet::Session::ModuleHandlers[MODULE_COUNT] = { &Battlenet::Session::HandlePasswordModule, &Battlenet::Session::UnhandledModule, &Battlenet::Session::UnhandledModule, &Battlenet::Session::HandleSelectGameAccountModule, &Battlenet::Session::HandleRiskFingerprintModule, &Battlenet::Session::HandleResumeModule, }; void Battlenet::AccountInfo::LoadResult(Field* fields) { // ba.id, ba.email, ba.locked, ba.lock_country, ba.last_ip, ba.failed_logins, bab.unbandate > UNIX_TIMESTAMP() OR bab.unbandate = bab.bandate, bab.unbandate = bab.bandate FROM battlenet_accounts ba LEFT JOIN battlenet_account_bans bab WHERE email = ? Id = fields[0].GetUInt32(); Login = fields[1].GetString(); IsLockedToIP = fields[2].GetBool(); LockCountry = fields[3].GetString(); LastIP = fields[4].GetString(); FailedLogins = fields[5].GetUInt32(); IsBanned = fields[6].GetUInt64() != 0; IsPermanenetlyBanned = fields[7].GetUInt64() != 0; } void Battlenet::GameAccountInfo::LoadResult(Field* fields) { // a.id, a.username, ab.unbandate > UNIX_TIMESTAMP() OR ab.unbandate = ab.bandate, ab.unbandate = ab.bandate, aa.gmlevel Id = fields[0].GetUInt32(); Name = fields[1].GetString(); IsBanned = fields[2].GetUInt64() != 0; IsPermanenetlyBanned = fields[3].GetUInt64() != 0; SecurityLevel = AccountTypes(fields[4].GetUInt8()); std::size_t hashPos = Name.find('#'); if (hashPos != std::string::npos) DisplayName = std::string("WoW") + Name.substr(hashPos + 1); else DisplayName = Name; } Battlenet::Session::Session(tcp::socket&& socket) : Socket(std::move(socket)), _accountInfo(new AccountInfo()), _gameAccountInfo(nullptr), _locale(), _os(), _build(0), _ipCountry(), I(), s(), v(), b(), B(), K(), _reconnectProof(), _crypt(), _authed(false), _subscribedToRealmListUpdates(false), _toonOnline(false) { static uint8 const N_Bytes[] = { 0xAB, 0x24, 0x43, 0x63, 0xA9, 0xC2, 0xA6, 0xC3, 0x3B, 0x37, 0xE4, 0x61, 0x84, 0x25, 0x9F, 0x8B, 0x3F, 0xCB, 0x8A, 0x85, 0x27, 0xFC, 0x3D, 0x87, 0xBE, 0xA0, 0x54, 0xD2, 0x38, 0x5D, 0x12, 0xB7, 0x61, 0x44, 0x2E, 0x83, 0xFA, 0xC2, 0x21, 0xD9, 0x10, 0x9F, 0xC1, 0x9F, 0xEA, 0x50, 0xE3, 0x09, 0xA6, 0xE5, 0x5E, 0x23, 0xA7, 0x77, 0xEB, 0x00, 0xC7, 0xBA, 0xBF, 0xF8, 0x55, 0x8A, 0x0E, 0x80, 0x2B, 0x14, 0x1A, 0xA2, 0xD4, 0x43, 0xA9, 0xD4, 0xAF, 0xAD, 0xB5, 0xE1, 0xF5, 0xAC, 0xA6, 0x13, 0x1C, 0x69, 0x78, 0x64, 0x0B, 0x7B, 0xAF, 0x9C, 0xC5, 0x50, 0x31, 0x8A, 0x23, 0x08, 0x01, 0xA1, 0xF5, 0xFE, 0x31, 0x32, 0x7F, 0xE2, 0x05, 0x82, 0xD6, 0x0B, 0xED, 0x4D, 0x55, 0x32, 0x41, 0x94, 0x29, 0x6F, 0x55, 0x7D, 0xE3, 0x0F, 0x77, 0x19, 0xE5, 0x6C, 0x30, 0xEB, 0xDE, 0xF6, 0xA7, 0x86 }; N.SetBinary(N_Bytes, sizeof(N_Bytes)); g.SetDword(2); SHA256Hash sha; sha.UpdateBigNumbers(&N, &g, NULL); sha.Finalize(); k.SetBinary(sha.GetDigest(), sha.GetLength()); } Battlenet::Session::~Session() { if (_authed) sSessionMgr.RemoveSession(this); delete _accountInfo; } void Battlenet::Session::_SetVSFields(std::string const& pstr) { s.SetRand(uint32(BufferSizes::SRP_6_S) * 8); BigNumber p; p.SetHexStr(pstr.c_str()); SHA256Hash sha; sha.UpdateBigNumbers(&s, &p, NULL); sha.Finalize(); BigNumber x; x.SetBinary(sha.GetDigest(), sha.GetLength()); v = g.ModExp(x, N); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_BNET_VS_FIELDS); stmt->setString(0, v.AsHexStr()); stmt->setString(1, s.AsHexStr()); stmt->setString(2, _accountInfo->Login); LoginDatabase.Execute(stmt); } void Battlenet::Session::LogUnhandledPacket(PacketHeader const& header) { TC_LOG_DEBUG("session.packets", "%s Received unhandled packet %s", GetClientInfo().c_str(), sPacketManager.GetClientPacketName(header)); } void Battlenet::Session::HandleLogonRequest(Authentication::LogonRequest3 const& logonRequest) { if (_queryCallback) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_LOGON_TOO_FAST); AsyncWrite(logonResponse); TC_LOG_DEBUG("session", "[Battlenet::LogonRequest] %s attempted to log too quick after previous attempt!", GetClientInfo().c_str()); return; } if (logonRequest.Program != "WoW") { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_INVALID_PROGRAM); AsyncWrite(logonResponse); TC_LOG_DEBUG("session", "[Battlenet::LogonRequest] %s attempted to log in with game other than WoW (using %s)!", GetClientInfo().c_str(), logonRequest.Program.c_str()); return; } if (!sComponentMgr->HasPlatform(logonRequest.Platform)) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_INVALID_OS); AsyncWrite(logonResponse); TC_LOG_DEBUG("session", "[Battlenet::LogonRequest] %s attempted to log in from an unsupported platform (using %s)!", GetClientInfo().c_str(), logonRequest.Platform.c_str()); return; } if (!sComponentMgr->HasPlatform(logonRequest.Locale)) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_UNSUPPORTED_LANGUAGE); AsyncWrite(logonResponse); TC_LOG_DEBUG("session", "[Battlenet::LogonRequest] %s attempted to log in with unsupported locale (using %s)!", GetClientInfo().c_str(), logonRequest.Locale.c_str()); return; } for (Component const& component : logonRequest.Components) { if (!sComponentMgr->HasComponent(&component)) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); if (!sComponentMgr->HasProgram(component.Program)) { logonResponse->SetAuthResult(AUTH_INVALID_PROGRAM); TC_LOG_DEBUG("session", "[Battlenet::LogonRequest] %s is using unsupported component program %s!", GetClientInfo().c_str(), component.Program.c_str()); } else if (!sComponentMgr->HasPlatform(component.Platform)) { logonResponse->SetAuthResult(AUTH_INVALID_OS); TC_LOG_DEBUG("session", "[Battlenet::LogonRequest] %s is using unsupported component platform %s!", GetClientInfo().c_str(), component.Platform.c_str()); } else { if (component.Program != "WoW" || AuthHelper::IsBuildSupportingBattlenet(component.Build)) logonResponse->SetAuthResult(AUTH_REGION_BAD_VERSION); else logonResponse->SetAuthResult(AUTH_USE_GRUNT_LOGON); TC_LOG_DEBUG("session", "[Battlenet::LogonRequest] %s is using unsupported component version %u!", GetClientInfo().c_str(), component.Build); } AsyncWrite(logonResponse); return; } if (component.Platform == "base") _build = component.Build; } std::string login = logonRequest.Login; _locale = logonRequest.Locale; _os = logonRequest.Platform; Utf8ToUpperOnlyLatin(login); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_BNET_ACCOUNT_INFO); stmt->setString(0, login); _queryCallback = std::bind(&Battlenet::Session::HandleLogonRequestCallback, this, std::placeholders::_1); _queryFuture = LoginDatabase.AsyncQuery(stmt); } void Battlenet::Session::HandleLogonRequestCallback(PreparedQueryResult result) { if (!result) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_UNKNOWN_ACCOUNT); AsyncWrite(logonResponse); TC_LOG_DEBUG("session", "[Battlenet::LogonRequest] %s is trying to log in from unknown account!", GetClientInfo().c_str()); return; } Field* fields = result->Fetch(); _accountInfo->LoadResult(fields); std::string pStr = fields[8].GetString(); std::string databaseV = fields[9].GetString(); std::string databaseS = fields[10].GetString(); _gameAccounts.resize(result->GetRowCount()); uint32 i = 0; do { _gameAccounts[i++].LoadResult(result->Fetch() + 11); } while (result->NextRow()); std::string ip_address = GetRemoteIpAddress().to_string(); // If the IP is 'locked', check that the player comes indeed from the correct IP address if (_accountInfo->IsLockedToIP) { TC_LOG_DEBUG("session", "[Battlenet::LogonRequest] Account '%s' is locked to IP - '%s' is logging in from '%s'", _accountInfo->Login.c_str(), _accountInfo->LastIP.c_str(), ip_address.c_str()); if (_accountInfo->LastIP != ip_address) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_ACCOUNT_LOCKED); AsyncWrite(logonResponse); return; } } else { TC_LOG_DEBUG("session", "[Battlenet::LogonRequest] Account '%s' is not locked to ip", _accountInfo->Login.c_str()); if (_accountInfo->LockCountry.empty() || _accountInfo->LockCountry == "00") TC_LOG_DEBUG("session", "[Battlenet::LogonRequest] Account '%s' is not locked to country", _accountInfo->Login.c_str()); else if (!_accountInfo->LockCountry.empty() && !_ipCountry.empty()) { TC_LOG_DEBUG("session", "[Battlenet::LogonRequest] Account '%s' is locked to country: '%s' Player country is '%s'", _accountInfo->Login.c_str(), _accountInfo->LockCountry.c_str(), _ipCountry.c_str()); if (_ipCountry != _accountInfo->LockCountry) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_ACCOUNT_LOCKED); AsyncWrite(logonResponse); return; } } } // If the account is banned, reject the logon attempt if (_accountInfo->IsBanned) { if (_accountInfo->IsPermanenetlyBanned) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(LOGIN_BANNED); AsyncWrite(logonResponse); TC_LOG_DEBUG("session", "'%s:%d' [Battlenet::LogonRequest] Banned account %s tried to login!", ip_address.c_str(), GetRemotePort(), _accountInfo->Login.c_str()); return; } else { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(LOGIN_SUSPENDED); AsyncWrite(logonResponse); TC_LOG_DEBUG("session", "'%s:%d' [Battlenet::LogonRequest] Temporarily banned account %s tried to login!", ip_address.c_str(), GetRemotePort(), _accountInfo->Login.c_str()); return; } } SHA256Hash sha; sha.UpdateData(_accountInfo->Login); sha.Finalize(); I.SetBinary(sha.GetDigest(), sha.GetLength()); ModuleInfo* password = sModuleMgr->CreateModule(_os, "Password"); ModuleInfo* thumbprint = sModuleMgr->CreateModule(_os, "Thumbprint"); if (databaseV.size() != size_t(BufferSizes::SRP_6_V) * 2 || databaseS.size() != size_t(BufferSizes::SRP_6_S) * 2) _SetVSFields(pStr); else { s.SetHexStr(databaseS.c_str()); v.SetHexStr(databaseV.c_str()); } b.SetRand(128 * 8); B = ((v * k) + g.ModExp(b, N)) % N; BigNumber unk; unk.SetRand(128 * 8); BitStream passwordData; uint8 state = 0; passwordData.WriteBytes(&state, 1); passwordData.WriteBytes(I.AsByteArray(32).get(), 32); passwordData.WriteBytes(s.AsByteArray(32).get(), 32); passwordData.WriteBytes(B.AsByteArray(128).get(), 128); passwordData.WriteBytes(unk.AsByteArray(128).get(), 128); password->DataSize = passwordData.GetSize(); password->Data = new uint8[password->DataSize]; memcpy(password->Data, passwordData.GetBuffer(), password->DataSize); _modulesWaitingForData.push(MODULE_PASSWORD); Authentication::ProofRequest* proofRequest = new Authentication::ProofRequest(); proofRequest->Modules.push_back(password); // if has authenticator, send Token module proofRequest->Modules.push_back(thumbprint); AsyncWrite(proofRequest); } void Battlenet::Session::HandleResumeRequest(Authentication::ResumeRequest const& resumeRequest) { if (_queryCallback) { Authentication::ResumeResponse* logonResponse = new Authentication::ResumeResponse(); logonResponse->SetAuthResult(AUTH_LOGON_TOO_FAST); AsyncWrite(logonResponse); TC_LOG_DEBUG("session", "[Battlenet::ResumeRequest] %s attempted to log too quick after previous attempt!", GetClientInfo().c_str()); return; } std::string login = resumeRequest.Login; _locale = resumeRequest.Locale; _os = resumeRequest.Platform; auto baseComponent = std::find_if(resumeRequest.Components.begin(), resumeRequest.Components.end(), [](Component const& c) { return c.Program == "base"; }); if (baseComponent != resumeRequest.Components.end()) _build = baseComponent->Build; Utf8ToUpperOnlyLatin(login); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_BNET_RECONNECT_INFO); stmt->setString(0, login); stmt->setString(1, resumeRequest.GameAccountName); _queryCallback = std::bind(&Battlenet::Session::HandleResumeRequestCallback, this, std::placeholders::_1); _queryFuture = LoginDatabase.AsyncQuery(stmt); } void Battlenet::Session::HandleResumeRequestCallback(PreparedQueryResult result) { if (!result) { Authentication::ResumeResponse* resumeResponse = new Authentication::ResumeResponse(); resumeResponse->SetAuthResult(AUTH_UNKNOWN_ACCOUNT); AsyncWrite(resumeResponse); return; } Field* fields = result->Fetch(); _accountInfo->LoadResult(fields); K.SetHexStr(fields[8].GetString().c_str()); _gameAccounts.resize(1); _gameAccountInfo = &_gameAccounts[0]; _gameAccountInfo->LoadResult(fields + 9); ModuleInfo* thumbprint = sModuleMgr->CreateModule(_os, "Thumbprint"); ModuleInfo* resume = sModuleMgr->CreateModule(_os, "Resume"); BitStream resumeData; uint8 state = 0; _reconnectProof.SetRand(16 * 8); resumeData.WriteBytes(&state, 1); resumeData.WriteBytes(_reconnectProof.AsByteArray().get(), 16); resume->DataSize = resumeData.GetSize(); resume->Data = new uint8[resume->DataSize]; memcpy(resume->Data, resumeData.GetBuffer(), resume->DataSize); _modulesWaitingForData.push(MODULE_RESUME); Authentication::ProofRequest* proofRequest = new Authentication::ProofRequest(); proofRequest->Modules.push_back(thumbprint); proofRequest->Modules.push_back(resume); AsyncWrite(proofRequest); } void Battlenet::Session::HandleProofResponse(Authentication::ProofResponse const& proofResponse) { if (_modulesWaitingForData.size() < proofResponse.Modules.size()) { Authentication::LogonResponse* complete = new Authentication::LogonResponse(); complete->SetAuthResult(AUTH_CORRUPTED_MODULE); AsyncWrite(complete); return; } ServerPacket* response = nullptr; for (size_t i = 0; i < proofResponse.Modules.size(); ++i) { if (!(this->*(ModuleHandlers[_modulesWaitingForData.front()]))(proofResponse.Modules[i], &response)) break; _modulesWaitingForData.pop(); } if (!response) { response = new Authentication::LogonResponse(); static_cast<Authentication::LogonResponse*>(response)->SetAuthResult(AUTH_INTERNAL_ERROR); } AsyncWrite(response); } void Battlenet::Session::HandlePing(Connection::Ping const& /*ping*/) { AsyncWrite(new Connection::Pong()); } void Battlenet::Session::HandleEnableEncryption(Connection::EnableEncryption& enableEncryption) { _crypt.Init(&K); _crypt.DecryptRecv(enableEncryption.GetRemainingData(), enableEncryption.GetRemainingSize()); } void Battlenet::Session::HandleLogoutRequest(Connection::LogoutRequest const& /*logoutRequest*/) { PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_BNET_SESSION_KEY); stmt->setString(0, ""); stmt->setBool(1, false); stmt->setUInt32(2, _accountInfo->Id); LoginDatabase.Execute(stmt); } void Battlenet::Session::HandleConnectionClosing(Connection::ConnectionClosing const& /*connectionClosing*/) { } void Battlenet::Session::HandleListSubscribeRequest(WoWRealm::ListSubscribeRequest const& /*listSubscribeRequest*/) { if (_subscribedToRealmListUpdates || _queryCallback) return; PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_BNET_CHARACTER_COUNTS); stmt->setUInt32(0, _gameAccountInfo->Id); _queryCallback = std::bind(&Battlenet::Session::HandleListSubscribeRequestCallback, this, std::placeholders::_1); _queryFuture = LoginDatabase.AsyncQuery(stmt); } void Battlenet::Session::HandleListSubscribeRequestCallback(PreparedQueryResult result) { WoWRealm::ListSubscribeResponse* listSubscribeResponse = new WoWRealm::ListSubscribeResponse(); if (result) { do { Field* fields = result->Fetch(); uint32 build = fields[4].GetUInt32(); listSubscribeResponse->CharacterCounts.push_back({ RealmId(fields[2].GetUInt8(), fields[3].GetUInt8(), fields[1].GetUInt32(), (_build != build ? build : 0)), fields[0].GetUInt8() }); } while (result->NextRow()); } for (RealmList::RealmMap::value_type const& i : sRealmList->GetRealms()) listSubscribeResponse->RealmData.push_back(BuildListUpdate(&i.second)); listSubscribeResponse->RealmData.push_back(new WoWRealm::ListComplete()); AsyncWrite(listSubscribeResponse); _subscribedToRealmListUpdates = true; } void Battlenet::Session::HandleListUnsubscribe(WoWRealm::ListUnsubscribe const& /*listUnsubscribe*/) { _subscribedToRealmListUpdates = false; } void Battlenet::Session::HandleJoinRequestV2(WoWRealm::JoinRequestV2 const& joinRequest) { WoWRealm::JoinResponseV2* joinResponse = new WoWRealm::JoinResponseV2(); Realm const* realm = sRealmList->GetRealm(joinRequest.Realm); if (!realm || realm->Flags & (REALM_FLAG_INVALID | REALM_FLAG_OFFLINE) || realm->Id.Build != _build) { joinResponse->Response = WoWRealm::JoinResponseV2::FAILURE; AsyncWrite(joinResponse); return; } joinResponse->ServerSeed = rand32(); uint8 sessionKey[40]; HmacSha1 hmac(K.GetNumBytes(), K.AsByteArray().get()); hmac.UpdateData((uint8*)"WoW\0", 4); hmac.UpdateData((uint8*)&joinRequest.ClientSeed, 4); hmac.UpdateData((uint8*)&joinResponse->ServerSeed, 4); hmac.Finalize(); memcpy(sessionKey, hmac.GetDigest(), hmac.GetLength()); HmacSha1 hmac2(K.GetNumBytes(), K.AsByteArray().get()); hmac2.UpdateData((uint8*)"WoW\0", 4); hmac2.UpdateData((uint8*)&joinResponse->ServerSeed, 4); hmac2.UpdateData((uint8*)&joinRequest.ClientSeed, 4); hmac2.Finalize(); memcpy(sessionKey + hmac.GetLength(), hmac2.GetDigest(), hmac2.GetLength()); LoginDatabase.DirectPExecute("UPDATE account SET sessionkey = '%s', last_ip = '%s', last_login = NOW(), locale = %u, failed_logins = 0, os = '%s' WHERE id = %u", ByteArrayToHexStr(sessionKey, 40, true).c_str(), GetRemoteIpAddress().to_string().c_str(), GetLocaleByName(_locale), _os.c_str(), _gameAccountInfo->Id); if(realm->HasIpv4Address()) joinResponse->IPv4.push_back(realm->GetAddressForClient(GetRemoteIpAddress())); if(realm->HasIpv6Address()) joinResponse->IPv6.push_back(realm->GetIpv6AddressForClient(GetRemoteIpAddress())); AsyncWrite(joinResponse); } void Battlenet::Session::HandleSocialNetworkCheckConnected(Friends::SocialNetworkCheckConnected const& socialNetworkCheckConnected) { Friends::SocialNetworkCheckConnectedResult* socialNetworkCheckConnectedResult = new Friends::SocialNetworkCheckConnectedResult(); socialNetworkCheckConnectedResult->SocialNetworkId = socialNetworkCheckConnected.SocialNetworkId; AsyncWrite(socialNetworkCheckConnectedResult); } void Battlenet::Session::HandleGetStreamItemsRequest(Cache::GetStreamItemsRequest const& getStreamItemsRequest) { if (ModuleInfo* module = sModuleMgr->CreateModule(getStreamItemsRequest.Locale, getStreamItemsRequest.ItemName)) { Cache::GetStreamItemsResponse* getStreamItemsResponse = new Cache::GetStreamItemsResponse(); getStreamItemsResponse->Index = getStreamItemsRequest.Index; getStreamItemsResponse->Modules.push_back(module); AsyncWrite(getStreamItemsResponse); } } inline std::string PacketToStringHelper(Battlenet::ClientPacket const* packet) { if (sLog->ShouldLog("session.packets", LOG_LEVEL_TRACE)) return packet->ToString(); return sPacketManager.GetClientPacketName(packet->GetHeader()); } inline std::string PacketToStringHelper(Battlenet::ServerPacket const* packet) { if (sLog->ShouldLog("session.packets", LOG_LEVEL_TRACE)) return packet->ToString(); return sPacketManager.GetServerPacketName(packet->GetHeader()); } void Battlenet::Session::ReadHandler() { BitStream stream(std::move(GetReadBuffer())); _crypt.DecryptRecv(stream.GetBuffer(), stream.GetSize()); while (!stream.IsRead()) { try { PacketHeader header; header.Opcode = stream.Read<uint32>(6); if (stream.Read<bool>(1)) header.Channel = stream.Read<int32>(4); if (header.Channel != AUTHENTICATION && (header.Channel != CONNECTION || header.Opcode != Connection::CMSG_PING) && !_authed) { TC_LOG_DEBUG("session.packets", "%s Received not allowed %s. Client has not authed yet.", GetClientInfo().c_str(), header.ToString().c_str()); CloseSocket(); return; } if (ClientPacket* packet = sPacketManager.CreateClientPacket(header, stream)) { if (sPacketManager.IsHandled(header)) TC_LOG_DEBUG("session.packets", "%s Received %s", GetClientInfo().c_str(), PacketToStringHelper(packet).c_str()); packet->CallHandler(this); delete packet; } else if (sPacketManager.GetClientPacketName(header)) { LogUnhandledPacket(header); break; } else { TC_LOG_DEBUG("session.packets", "%s Received unknown %s", GetClientInfo().c_str(), header.ToString().c_str()); break; } stream.AlignToNextByte(); } catch (BitStreamPositionException const& e) { TC_LOG_ERROR("session.packets", "%s Exception thrown during packet processing %s", GetClientInfo().c_str(), e.what()); CloseSocket(); return; } } GetReadBuffer().Resize(size_t(BufferSizes::Read)); AsyncRead(); } void Battlenet::Session::Start() { std::string ip_address = GetRemoteIpAddress().to_string(); TC_LOG_TRACE("session", "Accepted connection from %s", ip_address.c_str()); if (_queryCallback) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_LOGON_TOO_FAST); AsyncWrite(logonResponse); TC_LOG_DEBUG("session", "[Session::Start] %s attempted to log too quick after previous attempt!", GetClientInfo().c_str()); return; } // Verify that this IP is not in the ip_banned table LoginDatabase.Execute(LoginDatabase.GetPreparedStatement(LOGIN_DEL_EXPIRED_IP_BANS)); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_INFO); stmt->setString(0, ip_address); stmt->setUInt32(1, inet_addr(ip_address.c_str())); _queryCallback = std::bind(&Battlenet::Session::CheckIpCallback, this, std::placeholders::_1); _queryFuture = LoginDatabase.AsyncQuery(stmt); } void Battlenet::Session::CheckIpCallback(PreparedQueryResult result) { if (result) { bool banned = false; do { Field* fields = result->Fetch(); if (fields[0].GetUInt64() != 0) banned = true; if (!fields[1].GetString().empty()) _ipCountry = fields[1].GetString(); } while (result->NextRow()); if (banned) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_INTERNAL_ERROR); AsyncWrite(logonResponse); TC_LOG_DEBUG("session", "[Battlenet::LogonRequest] Banned ip '%s:%d' tries to login!", GetRemoteIpAddress().to_string().c_str(), GetRemotePort()); return; } } AsyncRead(); } bool Battlenet::Session::Update() { if (!BattlenetSocket::Update()) return false; if (_queryFuture.valid() && _queryFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { auto callback = std::move(_queryCallback); callback(_queryFuture.get()); } return true; } void Battlenet::Session::AsyncWrite(ServerPacket* packet) { if (!IsOpen()) { delete packet; return; } TC_LOG_DEBUG("session.packets", "%s Sending %s", GetClientInfo().c_str(), PacketToStringHelper(packet).c_str()); packet->Write(); MessageBuffer buffer; buffer.Write(packet->GetData(), packet->GetSize()); delete packet; std::unique_lock<std::mutex> guard(_writeLock); _crypt.EncryptSend(buffer.GetReadPointer(), buffer.GetActiveSize()); QueuePacket(std::move(buffer), guard); } inline void ReplaceResponse(Battlenet::ServerPacket** oldResponse, Battlenet::ServerPacket* newResponse) { if (*oldResponse) delete *oldResponse; *oldResponse = newResponse; } bool Battlenet::Session::HandlePasswordModule(BitStream* dataStream, ServerPacket** response) { if (dataStream->GetSize() != 1 + 128 + 32 + 128) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_CORRUPTED_MODULE); ReplaceResponse(response, logonResponse); return false; } if (dataStream->Read<uint8>(8) != 2) // State { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_CORRUPTED_MODULE); ReplaceResponse(response, logonResponse); return false; } BigNumber A, clientM1, clientChallenge; A.SetBinary(dataStream->ReadBytes(128).get(), 128); clientM1.SetBinary(dataStream->ReadBytes(32).get(), 32); clientChallenge.SetBinary(dataStream->ReadBytes(128).get(), 128); if (A.IsZero()) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_CORRUPTED_MODULE); ReplaceResponse(response, logonResponse); return false; } SHA256Hash sha; sha.UpdateBigNumbers(&A, &B, NULL); sha.Finalize(); BigNumber u; u.SetBinary(sha.GetDigest(), sha.GetLength()); BigNumber S = ((A * v.ModExp(u, N)) % N).ModExp(b, N); uint8 S_bytes[128]; memcpy(S_bytes, S.AsByteArray(128).get(), 128); uint8 part1[64]; uint8 part2[64]; for (int i = 0; i < 64; ++i) { part1[i] = S_bytes[i * 2]; part2[i] = S_bytes[i * 2 + 1]; } SHA256Hash part1sha, part2sha; part1sha.UpdateData(part1, 64); part1sha.Finalize(); part2sha.UpdateData(part2, 64); part2sha.Finalize(); uint8 sessionKey[SHA256_DIGEST_LENGTH * 2]; for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i) { sessionKey[i * 2] = part1sha.GetDigest()[i]; sessionKey[i * 2 + 1] = part2sha.GetDigest()[i]; } K.SetBinary(sessionKey, SHA256_DIGEST_LENGTH * 2); BigNumber M1; uint8 hash[SHA256_DIGEST_LENGTH]; sha.Initialize(); sha.UpdateBigNumbers(&N, NULL); sha.Finalize(); memcpy(hash, sha.GetDigest(), sha.GetLength()); sha.Initialize(); sha.UpdateBigNumbers(&g, NULL); sha.Finalize(); for (int i = 0; i < sha.GetLength(); ++i) hash[i] ^= sha.GetDigest()[i]; SHA256Hash shaI; shaI.UpdateData(ByteArrayToHexStr(I.AsByteArray().get(), 32)); shaI.Finalize(); // Concat all variables for M1 hash sha.Initialize(); sha.UpdateData(hash, SHA256_DIGEST_LENGTH); sha.UpdateData(shaI.GetDigest(), shaI.GetLength()); sha.UpdateBigNumbers(&s, &A, &B, &K, NULL); sha.Finalize(); M1.SetBinary(sha.GetDigest(), sha.GetLength()); if (memcmp(M1.AsByteArray().get(), clientM1.AsByteArray().get(), 32)) { PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_BNET_FAILED_LOGINS); stmt->setString(0, _accountInfo->Login); LoginDatabase.Execute(stmt); Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_UNKNOWN_ACCOUNT); ReplaceResponse(response, logonResponse); TC_LOG_DEBUG("session", "[Battlenet::Password] %s attempted to log in with invalid password!", GetClientInfo().c_str()); return false; } if (_gameAccounts.empty()) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(LOGIN_NO_GAME_ACCOUNT); ReplaceResponse(response, logonResponse); TC_LOG_DEBUG("session", "[Battlenet::Password] %s does not have any linked game accounts!", GetClientInfo().c_str()); return false; } //set expired game account bans to inactive LoginDatabase.Execute(LoginDatabase.GetPreparedStatement(LOGIN_UPD_EXPIRED_ACCOUNT_BANS)); BigNumber M; sha.Initialize(); sha.UpdateBigNumbers(&A, &M1, &K, NULL); sha.Finalize(); M.SetBinary(sha.GetDigest(), sha.GetLength()); BigNumber serverProof; serverProof.SetRand(128 * 8); // just send garbage, server signature check is patched out in client BitStream stream; ModuleInfo* password = sModuleMgr->CreateModule(_os, "Password"); uint8 state = 3; stream.WriteBytes(&state, 1); stream.WriteBytes(M.AsByteArray(32).get(), 32); stream.WriteBytes(serverProof.AsByteArray(128).get(), 128); password->DataSize = stream.GetSize(); password->Data = new uint8[password->DataSize]; memcpy(password->Data, stream.GetBuffer(), password->DataSize); Authentication::ProofRequest* proofRequest = new Authentication::ProofRequest(); proofRequest->Modules.push_back(password); if (_gameAccounts.size() > 1) { BitStream accounts; state = 0; accounts.WriteBytes(&state, 1); accounts.Write(_gameAccounts.size(), 8); for (GameAccountInfo const& gameAccount : _gameAccounts) { accounts.Write(2, 8); accounts.WriteString(gameAccount.DisplayName, 8); } ModuleInfo* selectGameAccount = sModuleMgr->CreateModule(_os, "SelectGameAccount"); selectGameAccount->DataSize = accounts.GetSize(); selectGameAccount->Data = new uint8[selectGameAccount->DataSize]; memcpy(selectGameAccount->Data, accounts.GetBuffer(), selectGameAccount->DataSize); proofRequest->Modules.push_back(selectGameAccount); _modulesWaitingForData.push(MODULE_SELECT_GAME_ACCOUNT); } else { _gameAccountInfo = &_gameAccounts[0]; if (_gameAccountInfo->IsBanned) { delete proofRequest; Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); if (_gameAccountInfo->IsPermanenetlyBanned) { logonResponse->SetAuthResult(LOGIN_BANNED); TC_LOG_DEBUG("session", "'%s:%d' [Battlenet::Password] Banned account %s tried to login!", GetRemoteIpAddress().to_string().c_str(), GetRemotePort(), _accountInfo->Login.c_str()); } else { logonResponse->SetAuthResult(LOGIN_SUSPENDED); TC_LOG_DEBUG("session", "'%s:%d' [Battlenet::Password] Temporarily banned account %s tried to login!", GetRemoteIpAddress().to_string().c_str(), GetRemotePort(), _accountInfo->Login.c_str()); } ReplaceResponse(response, logonResponse); return false; } proofRequest->Modules.push_back(sModuleMgr->CreateModule(_os, "RiskFingerprint")); _modulesWaitingForData.push(MODULE_RISK_FINGERPRINT); } ReplaceResponse(response, proofRequest); return true; } bool Battlenet::Session::HandleSelectGameAccountModule(BitStream* dataStream, ServerPacket** response) { if (dataStream->Read<uint8>(8) != 1) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_CORRUPTED_MODULE); ReplaceResponse(response, logonResponse); return false; } dataStream->Read<uint8>(8); std::string account = dataStream->ReadString(8); if (account.empty()) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(LOGIN_NO_GAME_ACCOUNT); ReplaceResponse(response, logonResponse); return false; } for (std::size_t i = 0; i < _gameAccounts.size(); ++i) { if (_gameAccounts[i].DisplayName == account) { _gameAccountInfo = &_gameAccounts[i]; break; } } if (!_gameAccountInfo) { Authentication::LogonResponse* complete = new Authentication::LogonResponse(); complete->SetAuthResult(LOGIN_NO_GAME_ACCOUNT); ReplaceResponse(response, complete); TC_LOG_DEBUG("session", "[Battlenet::SelectGameAccount] %s attempted to log in with invalid game account name %s!", GetClientInfo().c_str(), account.c_str()); return false; } if (_gameAccountInfo->IsBanned) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); if (_gameAccountInfo->IsPermanenetlyBanned) { logonResponse->SetAuthResult(LOGIN_BANNED); TC_LOG_DEBUG("session", "'%s:%d' [Battlenet::SelectGameAccount] Banned account %s tried to login!", GetRemoteIpAddress().to_string().c_str(), GetRemotePort(), _accountInfo->Login.c_str()); } else { logonResponse->SetAuthResult(LOGIN_SUSPENDED); TC_LOG_DEBUG("session", "'%s:%d' [Battlenet::SelectGameAccount] Temporarily banned account %s tried to login!", GetRemoteIpAddress().to_string().c_str(), GetRemotePort(), _accountInfo->Login.c_str()); } ReplaceResponse(response, logonResponse); return false; } Authentication::ProofRequest* proofRequest = new Authentication::ProofRequest(); proofRequest->Modules.push_back(sModuleMgr->CreateModule(_os, "RiskFingerprint")); ReplaceResponse(response, proofRequest); _modulesWaitingForData.push(MODULE_RISK_FINGERPRINT); return true; } bool Battlenet::Session::HandleRiskFingerprintModule(BitStream* dataStream, ServerPacket** response) { Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); if (dataStream->Read<uint8>(8) == 1 && _accountInfo && _gameAccountInfo) { logonResponse->AccountId = _accountInfo->Id; logonResponse->GameAccountName = _gameAccountInfo->Name; logonResponse->GameAccountFlags = GAMEACCOUNT_FLAG_PROPASS_LOCK; logonResponse->FailedLogins = _accountInfo->FailedLogins; SQLTransaction trans = LoginDatabase.BeginTransaction(); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_BNET_LAST_LOGIN_INFO); stmt->setString(0, GetRemoteIpAddress().to_string()); stmt->setUInt8(1, GetLocaleByName(_locale)); stmt->setString(2, _os); stmt->setUInt32(3, _accountInfo->Id); trans->Append(stmt); stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_BNET_SESSION_KEY); stmt->setString(0, K.AsHexStr()); stmt->setBool(1, true); stmt->setUInt32(2, _accountInfo->Id); trans->Append(stmt); LoginDatabase.CommitTransaction(trans); _authed = true; sSessionMgr.AddSession(this); } else logonResponse->SetAuthResult(AUTH_BAD_VERSION_HASH); ReplaceResponse(response, logonResponse); return true; } bool Battlenet::Session::HandleResumeModule(BitStream* dataStream, ServerPacket** response) { if (dataStream->Read<uint8>(8) != 1) { Authentication::ResumeResponse* resumeResponse = new Authentication::ResumeResponse(); resumeResponse->SetAuthResult(AUTH_CORRUPTED_MODULE); ReplaceResponse(response, resumeResponse); return false; } static uint8 const ResumeClient = 0; static uint8 const ResumeServer = 1; std::unique_ptr<uint8[]> clientChallenge = dataStream->ReadBytes(16); std::unique_ptr<uint8[]> clientProof = dataStream->ReadBytes(32); std::unique_ptr<uint8[]> serverChallenge = _reconnectProof.AsByteArray(16); std::unique_ptr<uint8[]> sessionKey = K.AsByteArray(64); HmacSha256 clientPart(64, sessionKey.get()); clientPart.UpdateData(&ResumeClient, 1); clientPart.UpdateData(clientChallenge.get(), 16); clientPart.UpdateData(serverChallenge.get(), 16); clientPart.Finalize(); HmacSha256 serverPart(64, sessionKey.get()); serverPart.UpdateData(&ResumeServer, 1); serverPart.UpdateData(serverChallenge.get(), 16); serverPart.UpdateData(clientChallenge.get(), 16); serverPart.Finalize(); uint8 newSessionKey[64]; memcpy(&newSessionKey[0], clientPart.GetDigest(), clientPart.GetLength()); memcpy(&newSessionKey[32], serverPart.GetDigest(), serverPart.GetLength()); K.SetBinary(newSessionKey, 64); HmacSha256 proof(64, newSessionKey); proof.UpdateData(&ResumeClient, 1); proof.UpdateData(clientChallenge.get(), 16); proof.UpdateData(serverChallenge.get(), 16); proof.Finalize(); if (memcmp(proof.GetDigest(), clientProof.get(), serverPart.GetLength())) { PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_BNET_FAILED_LOGINS); stmt->setString(0, _accountInfo->Login); LoginDatabase.Execute(stmt); TC_LOG_DEBUG("session", "[Battlenet::Resume] %s attempted to reconnect with invalid password!", GetClientInfo().c_str()); Authentication::ResumeResponse* resumeResponse = new Authentication::ResumeResponse(); resumeResponse->SetAuthResult(AUTH_UNKNOWN_ACCOUNT); ReplaceResponse(response, resumeResponse); return false; } PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_BNET_SESSION_KEY); stmt->setString(0, K.AsHexStr()); stmt->setBool(1, true); stmt->setUInt32(2, _accountInfo->Id); LoginDatabase.Execute(stmt); HmacSha256 serverProof(64, newSessionKey); serverProof.UpdateData(&ResumeServer, 1); serverProof.UpdateData(serverChallenge.get(), 16); serverProof.UpdateData(clientChallenge.get(), 16); serverProof.Finalize(); ModuleInfo* resume = sModuleMgr->CreateModule(_os, "Resume"); BitStream resumeData; uint8 state = 2; resumeData.WriteBytes(&state, 1); resumeData.WriteBytes(serverProof.GetDigest(), serverProof.GetLength()); resume->DataSize = resumeData.GetSize(); resume->Data = new uint8[resume->DataSize]; memcpy(resume->Data, resumeData.GetBuffer(), resume->DataSize); Authentication::ResumeResponse* resumeResponse = new Authentication::ResumeResponse(); resumeResponse->Modules.push_back(resume); ReplaceResponse(response, resumeResponse); _authed = true; sSessionMgr.AddSession(this); return true; } bool Battlenet::Session::UnhandledModule(BitStream* /*dataStream*/, ServerPacket** response) { TC_LOG_ERROR("session.packets", "Unhandled module."); Authentication::LogonResponse* logonResponse = new Authentication::LogonResponse(); logonResponse->SetAuthResult(AUTH_CORRUPTED_MODULE); ReplaceResponse(response, logonResponse); return false; } void Battlenet::Session::UpdateRealms(std::vector<Realm const*>& realms, std::vector<RealmId>& deletedRealms) { for (Realm const* realm : realms) AsyncWrite(BuildListUpdate(realm)); for (RealmId& deleted : deletedRealms) { WoWRealm::ListUpdate* listUpdate = new WoWRealm::ListUpdate(); listUpdate->UpdateState = WoWRealm::ListUpdate::DELETED; listUpdate->Id = deleted; AsyncWrite(listUpdate); } } Battlenet::WoWRealm::ListUpdate* Battlenet::Session::BuildListUpdate(Realm const* realm) const { uint32 flag = realm->Flags & ~REALM_FLAG_SPECIFYBUILD; RealmBuildInfo const* buildInfo = AuthHelper::GetBuildInfo(realm->Id.Build); if (realm->Id.Build != _build) { flag |= REALM_FLAG_INVALID; if (buildInfo) flag |= REALM_FLAG_SPECIFYBUILD; // tell the client what build the realm is for } WoWRealm::ListUpdate* listUpdate = new WoWRealm::ListUpdate(); listUpdate->Timezone = realm->Timezone; listUpdate->Population = realm->PopulationLevel; listUpdate->Lock = (realm->AllowedSecurityLevel > _gameAccountInfo->SecurityLevel) ? 1 : 0; listUpdate->Type = realm->Type; listUpdate->Name = realm->Name; if (flag & REALM_FLAG_SPECIFYBUILD) { std::ostringstream version; version << buildInfo->MajorVersion << '.' << buildInfo->MinorVersion << '.' << buildInfo->BugfixVersion << '.' << buildInfo->Build; listUpdate->Version = version.str(); // Prioritise ipv4, for compatibility if(realm->HasIpv4Address()) listUpdate->Address = realm->GetAddressForClient(GetRemoteIpAddress()); else listUpdate->Address = realm->GetIpv6AddressForClient(GetRemoteIpAddress()); } listUpdate->Flags = flag; listUpdate->Id = realm->Id; return listUpdate; } std::string Battlenet::Session::GetClientInfo() const { std::ostringstream stream; stream << '[' << GetRemoteIpAddress() << ':' << GetRemotePort(); if (_accountInfo && !_accountInfo->Login.empty()) stream << ", Account: " << _accountInfo->Login; if (_gameAccountInfo) stream << ", Game account: " << _gameAccountInfo->Name; stream << ']'; return stream.str(); }
TonyHoyle/TrinityCore
src/server/bnetserver/Server/Session.cpp
C++
gpl-2.0
44,221
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function from django.db import models from django.apps import apps from empresa.models import Empresa import json import os import tempfile import datetime import requests class Parking(models.Model): empresa = models.OneToOneField(Empresa) nombre = models.CharField(max_length=40) plazas = models.IntegerField() def __unicode__(self): return "{} ({})".format(self.nombre, self.empresa) def tupla_tarifa(self): "Obtener un tarifario dada una recta definida por puntos" # creamos una lista de listas lista = map(list, self.tarifa_set.values_list('precio', 'hora')) # agregamos el rango final de tiempo sacado de la siguiente linea n = len(lista) for i in range(n-1): lista[i].append(lista[i+1][1]) # el rango final ponemos que es 24h lista[n-1].append(datetime.timedelta(days=1)) # devolvemos [precio, hora_start, hora_end_no_inclusive] return lista def tabla_tarifa(self): "Tarifario con hh:mm para visualizar" for precio, min0, min1 in self.tupla_tarifa(): t = min1 - datetime.timedelta(seconds=1) yield min0, t, precio def get_dia(self): return float(self.tarifa_set.last().precio) def get_tarifa(self, td): "Obtener una tarifa del tarifario" # calculo de dias completos precio_dias = td.days * self.get_dia() # calculo de la fraccion de dia td = datetime.timedelta(seconds=td.seconds) for precio, min0, min1 in self.tupla_tarifa(): if min0 <= td < min1: return precio_dias + float(precio) def barreras_entrada(self): return self.barrera_set.filter(entrada=True) def barreras_salida(self): return self.barrera_set.filter(entrada=False) def nodos_remotos(self): return self.nodoremoto_set.all() @property def entrada_set(self): Entrada = apps.get_model('tickets.Entrada') return Entrada.objects.por_parking(self) @property def coches_hoy(self): return self.entrada_set.de_hoy().count() @property def coches_dentro(self): return self.entrada_set.de_hoy().dentro().count() class Expendedor(models.Model): parking = models.ForeignKey(Parking) nombre = models.CharField(max_length=40) mac = models.CharField(max_length=17) camera_command = models.CharField(max_length=255, blank=True, null=True, help_text="Comando para la camara, " "con {} donde queramos poner el output filename") def saca_foto(self): contenido = None if self.camera_command: filename = tempfile.mktemp() ret = os.system(self.camera_command.format(filename)) if ret == 0: contenido = open(filename).read() if os.path.isfile(filename): os.unlink(filename) return contenido def __unicode__(self): return "{} de {}".format(self.nombre, self.parking.nombre) class Meta: verbose_name = 'expendedor' verbose_name_plural = 'expendedores' class Barrera(models.Model): parking = models.ForeignKey(Parking) nombre = models.CharField(max_length=40) slug = models.CharField(max_length=40, unique=True) entrada = models.BooleanField() abre_url = models.URLField(max_length=100, blank=True, null=True, help_text="si hay url es que esta activo") abre_post = models.CharField(max_length=100, blank=True, null=True, help_text="post data en formato json") abresiempre_url = models.URLField(max_length=100, blank=True, null=True, help_text="si hay url es que esta activo") abresiempre_post = models.CharField(max_length=100, blank=True, null=True, help_text="post data en formato json") cierra_url = models.URLField(max_length=100, blank=True, null=True, help_text="si hay url es que esta activo") cierra_post = models.CharField(max_length=100, blank=True, null=True, help_text="post data en formato json") def abre(self): if self.abre_post: r = requests.post(self.abre_url, data=json.loads(self.abre_post)) else: r = requests.get(self.abre_url) return r.status_code == 200 def abresiempre(self): if self.abresiempre_post: r = requests.post(self.abresiempre_url, data=json.loads(self.abresiempre_post)) else: r = requests.get(self.abresiempre_url) return r.status_code == 200 def cierra(self): if self.cierra_post: r = requests.post(self.cierra_url, data=json.loads(self.cierra_post)) else: r = requests.get(self.cierra_url) return r.status_code == 200 def __unicode__(self): return "{} ({} de {})".format(self.slug, "entrada" if self.entrada else "salida", self.parking.nombre) class Meta: verbose_name = 'barrera' verbose_name_plural = 'barreras' class Tarifa(models.Model): parking = models.ForeignKey(Parking) precio = models.DecimalField(max_digits=5, decimal_places=2) hora = models.DurationField(help_text="hora a partir de la cual aplica este precio") def __unicode__(self): return "{} = {:.2f} €".format(self.hora, self.precio) class Meta: ordering = ('hora', ) class NodoRemoto(models.Model): parking = models.ForeignKey(Parking) host_name = models.CharField(max_length = 100, blank = True, null = True, help_text = 'Nombre del Host') url = models.CharField(max_length = 100, blank=True, null=True, help_text = ' url del demonio nameko' ) nombre = models.CharField(max_length=100, blank=True, null=True, help_text = 'Nombre del demonio nameko') def __unicode__(self): return "{} [{}]".format(self.nombre, self.url) def comandos(self): return self.comandoremoto_set.all() class Meta: verbose_name = 'Nodo Remoto' verbose_name_plural = 'Nodos Remotos' class ComandoRemoto(models.Model): nombre = models.CharField(max_length = 100, blank=True, null=True, help_text = 'nombre del comando') comando = models.CharField(max_length = 100, blank=True, null=True, help_text= 'comando') nodoremoto = models.ForeignKey(NodoRemoto) def __unicode__(self): return "{}: {}.{}()".format(self.nombre, self.nodoremoto, self.comando) class Meta: verbose_name = 'comando Remoto' verbose_name_plural = 'Comandos Remotos' # from django.db.models.signals import pre_save # from django.dispatch import receiver # @receiver(pre_save, sender=Tarifa) # def anula_date(sender, instance, using, **kwargs): # if isinstance(instance, datetime.datetime): # instance.hora = instance.hora.replace(year=1970, month=1, day=1) class Visor(models.Model): url = models.URLField(default="http://192.168.1.1:8000") descripcion = models.CharField(default="visor colocado en ...", max_length=200) parking = models.ForeignKey(Parking) def mostrar_importe(self, importe): imprte_str = "{:.2f}".format(importe) # print("importe " + imprte_str) try: r = requests.post(self.url, json={"importe": importe}) except: return False r = requests.post(self.url, json={"importe": importe}) return r.status_code == 200 def __str__(self): return self.descripcion class Meta: verbose_name_plural = 'Visores'
amd77/parker
inventario/models.py
Python
gpl-2.0
7,559
<section id="footer"> <div class="footer-top"> <div class="container"> <div class="container-inner"> <div class="row-fluid"> <div class="span12"> <div id="pavcarousel5" class="carousel slide pavcarousel hidden-phone"> <div class="carousel-inner"> <div class="item active"> <div class="row-fluid"> <div class="span2"> <div class="item-inner"> <a href="http://demopavothemes.com/pav_wines/index.php?route=product/manufacturer/info&amp;manufacturer_id=6"><img src="images/logo06-130x50.png" alt="chanel" class="img-responsive"></a> </div> </div> <div class="span2"> <div class="item-inner"> <a href="http://demopavothemes.com/pav_wines/index.php?route=product/manufacturer/info&amp;manufacturer_id=10"><img src="images/logo05-130x50.png" alt="beatles" class="img-responsive"></a> </div> </div> <div class="span2"> <div class="item-inner"> <a href="http://demopavothemes.com/pav_wines/index.php?route=product/manufacturer/info&amp;manufacturer_id=9"><img src="images/logo04-130x50.png" alt="ata" class="img-responsive"></a> </div> </div> <div class="span2"> <div class="item-inner"> <a href="http://demopavothemes.com/pav_wines/index.php?route=product/manufacturer/info&amp;manufacturer_id=8"><img src="images/logo03-130x50.png" alt="aigner" class="img-responsive"></a> </div> </div> <div class="span2"> <div class="item-inner"> <a href="http://demopavothemes.com/pav_wines/index.php?route=product/manufacturer/info&amp;manufacturer_id=5"><img src="images/logo02-130x50.png" alt="adidas" class="img-responsive"></a> </div> </div> <div class="span2"> <div class="item-inner"> <a href="http://demopavothemes.com/pav_wines/index.php?route=product/manufacturer/info&amp;manufacturer_id=7"><img src="images/logo01-130x50.png" alt="lacoste" class="img-responsive"></a> </div> </div> </div> </div> <div class="item "> <div class="row-fluid"> <div class="span2"> <div class="item-inner"> <img src="images/logo02-130x50.png" alt="pinterest" class="img-responsive"> </div> </div> <div class="span2"> <div class="item-inner"> <img src="images/logo01-130x50.png" alt="stylitics" class="img-responsive"> </div> </div> </div> </div> </div> <div class="carousel-controls"> <a class="carousel-control left" href="#pavcarousel5" data-slide="prev">‹</a> <a class="carousel-control right" href="#pavcarousel5" data-slide="next">›</a> </div> </div> </div> <script type="text/javascript"><!-- $('#pavcarousel5').carousel({interval:false}); --></script> </div> </div> </div> </div> <div class="footer-center"> <div class="container"> <div class="container-inner"> <div class="row-fluid"> <!-- <div class="column span3"> <div class="box"> <h3>Information</h3> <ul class="list"> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=information/information&amp;information_id=4">About Us</a></li> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=information/information&amp;information_id=6">Delivery Information</a></li> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=information/information&amp;information_id=3">Privacy Policy</a></li> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=information/information&amp;information_id=5">Terms &amp; Conditions</a></li> </ul> </div> </div> --> <div class="column span3"> <div class="box social"> <h3>Follow us on</h3> <ul> <li class="facebook"><span>icon</span><a href="#">Find us on Facbook</a></li> <li class="twitter"><span>icon</span><a href="#">Follow us on Twitter</a></li> <li class="vimeo"><span>icon</span><a href="#">Subscribe our channel</a></li> <li class="rss"><span>icon</span><a href="#">RSS Feed</a></li> </ul> </div> </div> <div class="column span2"> <div class="box"> <h3>Customer Service</h3> <ul class="list"> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=information/contact">Contact Us</a></li> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=account/return/insert">Returns</a></li> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=information/sitemap">Site Map</a></li> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=account/voucher">Gift Vouchers</a></li> </ul> </div> </div> <div class="column span2"> <div class="box"> <h3>Extras</h3> <ul class="list"> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=product/manufacturer">Brands</a></li> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=account/voucher">Gift Vouchers</a></li> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=affiliate/account">Affiliates</a></li> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=product/special">Specials</a></li> </ul> </div> </div> <div class="column span2"> <div class="box"> <h3>My Account</h3> <ul class="list"> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=account/account">My Account</a></li> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=account/order">Order History</a></li> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=account/wishlist">Wish List</a></li> <li><a href="http://demopavothemes.com/pav_wines/index.php?route=account/newsletter">Newsletter</a></li> </ul> </div> </div> <div class="column span3"> <div class="box "> <!--<h3>Contact Us</h3>--> <h3>Our brands address</h3> <p><img alt="" src="images/our-brands-address.png"></p> </div> </div> </div> </div></div> </div> <div class="footer-bottom"> <div class="container"> <div class="container-inner"> <div class="row-fluid"> <div class="span3"><div class="box pav-custom "> <div class="box-content"><h3>Our Stores</h3> <div class="content-stores"><span class="pull-left"><img alt="" src="images/our-stores.png"></span> <div class="text-srores">Lorem ipsum dolor sit amet etiam convallis ipsum justo laoreet elit ..</div> </div> </div> </div></div> <div class="span3"><div class="box pav-custom "> <div class="box-content"><h3>Payment accept</h3> <p><img alt="" src="images/paypal.png"></p> </div> </div></div> <div class="span3"><div class="box pav-custom "> <div class="box-content"><h3>Order online</h3> <p>Phone: +123 456 789</p> <p>Fax: +123 456 788</p> <p>Email: pavotheme@gmail.com</p> </div> </div></div> <div class="span3"><div class="box pav-custom "> <div class="box-content"><h3>Newsletter</h3> <p>Sign Up for Our Newsletter:</p> <div class="newsletter-submit"><input alt="username" class="inputbox" name="email" size="31" value="Type your email" type="text"><input class="button" name="Submit" value="Sign up" type="submit"></div> </div> </div></div> </div> </div> </div> </div> </section> <div id="powered"> <div class="container"> <div class="container-inner"> <div class="copyright"> copy rights © 2014. </div> </div> </div> </div>
warblersoftware/gold1
footer.php
PHP
gpl-2.0
7,776
<?php /** * Replies Loop * * @package bbPress * @subpackage Theme */ ?> <?php do_action( 'bbp_template_before_replies_loop' ); ?> <ul id="topic-<?php bbp_topic_id(); ?>-replies" class="forums bbp-replies"> <li class="bbp-body"> <?php if ( bbp_thread_replies() ) : ?> <?php bbp_list_replies(); ?> <?php else : ?> <?php while ( bbp_replies() ) : bbp_the_reply(); ?> <?php bbp_get_template_part( 'loop', 'single-reply' ); ?> <?php endwhile; ?> <?php endif; ?> </li><!-- .bbp-body --> </ul><!-- #topic-<?php bbp_topic_id(); ?>-replies --> <?php do_action( 'bbp_template_after_replies_loop' ); ?>
satoshishimazaki/notice-board3
wp-content/plugins/bbpress/templates/default/bbpress/loop-replies.php
PHP
gpl-2.0
634
<?php /*///////////////////////////////////////////////////// * Creates Admin Panel in dashboard settings page * Includes admin-panel.php /////////////////////////////////////////////////////*/ add_action( 'init', '_kcAdminOptions' ); function _kcAdminOptions(){ global $post_settings, $post_types_options, $plugins_options, $post_video_options, $kc_fields; if ( ! ( current_user_can( 'administrator' ) || current_user_can( 'developer' )) ) return; require_once( KC_DIR . '/admin-panel.php' ); $prefix = 'kc_'; $kc_fields = array( array( 'id' => $prefix.'options', 'type' => 'section', 'label' => __( 'Share Options', KC_LOCALE ) ), array( 'desc' => 'Short Tweet text. (Required: The sites url or shortlink if desired)', 'id' => $prefix.'twitter_text', 'type' => 'text', 'label' => __( 'Twitter Share Text', KC_LOCALE ) ), array( 'desc' => 'Tumblr share text.', 'id' => $prefix.'tumblr_text', 'type' => 'text', 'label' => __( 'Tumblr Share Text', KC_LOCALE ) ), array( 'id' => $prefix.'contact_options', 'type' => 'section', 'label' => __( 'Contact Us Options', KC_LOCALE ) ), array( 'desc' => 'Email to send contact form information to.', 'id' => $prefix.'email_url', 'type' => 'text', 'label' => __( 'Contact Us Email', KC_LOCALE ) ), array( 'id' => $prefix.'ga_options', 'type' => 'section', 'label' => __( 'Google Analytics Options', KC_LOCALE ) ), array( 'desc' => 'Paste Google Analytics script here.', 'id' => $prefix.'ga_tag', 'type' => 'textarea', 'placeholder' => '<script>GA CODE</script>', 'label' => __( 'Google Analytics Script', KC_LOCALE ) ) ); } ?>
StefanDindyal/wordpresser
wp-content/themes/kissesandcurses/inc/settings-panel/admin-options.php
PHP
gpl-2.0
1,741
/** * CKFinder * ======== * http://ckfinder.com * Copyright (C) 2007-2013, CKSource - Frederico Knabben. All rights reserved. * * The software, this file and its contents are subject to the CKFinder * License. Please read the license.txt file before using, installing, copying, * modifying or distribute this file or part of its contents. The contents of * this file is part of the Source Code of CKFinder. */ /** * CKFinder for Java - server connector. */ package com.ckfinder.connector;
uttmkl/etno
sites/all/modules/CKFinder/ckfinder/_sources/CKFinder for Java/CKFinder/src/main/java/com/ckfinder/connector/package-info.java
Java
gpl-2.0
500
/** \file "Object/inst/channel_collection_type_manager.hh" Template class for instance_collection's type manager. $Id: channel_collection_type_manager.hh,v 1.3 2007/04/15 05:52:17 fang Exp $ */ #ifndef __HAC_OBJECT_INST_CHANNEL_COLLECTION_TYPE_MANAGER_H__ #define __HAC_OBJECT_INST_CHANNEL_COLLECTION_TYPE_MANAGER_H__ #include <iosfwd> #include "Object/type/canonical_type_fwd.hh" // for conditional #include "util/persistent_fwd.hh" #include "util/boolean_types.hh" #include "util/memory/pointer_classes_fwd.hh" #include "Object/devel_switches.hh" namespace HAC { namespace entity { class const_param_expr_list; using std::istream; using std::ostream; using util::good_bool; using util::bad_bool; using util::persistent_object_manager; using util::memory::count_ptr; class footprint; template <class> struct class_traits; //============================================================================= /** Generic instance collection type manager for classes with full type references as type information. Not appropriate for built-in types. */ template <class Tag> class channel_collection_type_manager { private: typedef channel_collection_type_manager<Tag> this_type; typedef class_traits<Tag> traits_type; protected: typedef typename traits_type::instance_collection_generic_type instance_collection_generic_type; typedef typename traits_type::instance_collection_parameter_type instance_collection_parameter_type; typedef typename traits_type::type_ref_ptr_type type_ref_ptr_type; typedef typename traits_type::resolved_type_ref_type resolved_type_ref_type; /** The type parameter is ONLY a definition. */ instance_collection_parameter_type type_parameter; struct dumper; void collect_transient_info_base(persistent_object_manager&) const; void write_object_base(const persistent_object_manager&, ostream&) const; void load_object_base(const persistent_object_manager&, istream&); public: const instance_collection_parameter_type& __get_raw_type(void) const { return this->type_parameter; } resolved_type_ref_type get_resolved_canonical_type(void) const; /** No-op, channels don't have process footprints. */ good_bool complete_type_definition_footprint( const count_ptr<const const_param_expr_list>&) const { return good_bool(true); } bool is_complete_type(void) const { return this->type_parameter; } bool is_relaxed_type(void) const { return false; } /// built-in channels don't have process footprints static good_bool create_definition_footprint( const instance_collection_parameter_type&, const footprint& /* top */) { return good_bool(true); } protected: /** NOTE: called during connection checking. */ bool must_be_collectibly_type_equivalent(const this_type&) const; bad_bool check_type(const instance_collection_parameter_type&) const; /** \param t type must be resolved constant. \pre first time called for the collection. */ good_bool commit_type_first_time(const instance_collection_parameter_type& t); }; // end struct channel_collection_type_manager //============================================================================= } // end namespace entity } // end namespace HAC #endif // __HAC_OBJECT_INST_CHANNEL_COLLECTION_TYPE_MANAGER_H__
fangism/hackt
src/Object/inst/channel_collection_type_manager.hh
C++
gpl-2.0
3,301
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package clay; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * * @author MultiTool Need spring force of repulsion, spring force of attraction also need binding radius and un-binding (bond breaking) radius. */ public class Things { public static int NDims = 2; /* **************************************************************************** */ public static class Point { double[] V = new double[NDims]; /* **************************************************************************** */ public double Magnitude() {// pythagoras double dif, sumsq = 0.0; for (int dcnt = 0; dcnt < NDims; dcnt++) { dif = this.V[dcnt]; sumsq += dif * dif; } return Math.sqrt(sumsq); } /* **************************************************************************** */ public double DeltaMag(Point other) {// pythagoras double dif, sumsq = 0.0; for (int dcnt = 0; dcnt < NDims; dcnt++) { dif = this.V[dcnt] - other.V[dcnt]; sumsq += dif * dif; } return Math.sqrt(sumsq); } /* **************************************************************************** */ public void DeltaVec(Point origin, Point diff) { for (int dcnt = 0; dcnt < NDims; dcnt++) { diff.V[dcnt] = this.V[dcnt] - origin.V[dcnt]; } } /* **************************************************************************** */ public void AddVec(Point other) { for (int dcnt = 0; dcnt < NDims; dcnt++) { this.V[dcnt] += other.V[dcnt]; } } /* **************************************************************************** */ public void Unitize() { double length = this.Magnitude(); for (int dcnt = 0; dcnt < NDims; dcnt++) { this.V[dcnt] = this.V[dcnt] / length; } } /* **************************************************************************** */ public void Multiply(double magnitude) { for (int dcnt = 0; dcnt < NDims; dcnt++) { this.V[dcnt] *= magnitude; } } /* **************************************************************************** */ public void Clear() { for (int dcnt = 0; dcnt < NDims; dcnt++) { this.V[dcnt] = 0.0; } } /* **************************************************************************** */ public void Copy(Point other) { System.arraycopy(other.V, 0, this.V, 0, NDims); } } /* **************************************************************************** */ public static class SpringVec extends Point { public int GenStamp; } /* **************************************************************************** */ public static class Link { public Atom mine; public Link parallel; public static double RestingRadius = 10; public static double Radius = 5.0; public static double BindingRadius = 5.0; public static double BreakingRadius = BindingRadius + 1.0; public SpringVec Spring; // should we have two links between atoms or one? // with a planet/grav model, two gravity wells would fit // a spring is symmetrical. public void InterLink(Link other) { other.parallel = this; this.parallel = other; other.Spring = this.Spring = new SpringVec();// to do: rewrite this for single two-way links rather than twin links. } public Atom GetOtherAtom() { return this.parallel.mine; } public void CalcForceVector(Point Delta) { Point diffv; double distortion, dif; Atom me = this.mine; Atom you = this.GetOtherAtom(); diffv = new Point(); me.Loc.DeltaVec(you.Loc, diffv); dif = diffv.Magnitude(); distortion = dif - Link.RestingRadius;// distortion is displacement from resting length of spring diffv.Unitize(); diffv.Multiply(-distortion);// to do: since this force is applied once to each atom, the displacement back to resting is wrongly doubled // other issue is that we are wastefully calculating the dif vector twice, once for each end of the link pair. // a = f/m // the link pair COULD have a common storage object that keeps reusable info such as vector. baroque. // get locations of both of my ends // get my distortion from my resting length // normalize my direction vector, multiply by magnitude of distortion. } } /* **************************************************************************** */ public static class Atom { // public double Radius = 5.0; // public double BindingRadius = 5.0; // public double BreakingRadius = BindingRadius + 1.0; public Point Loc = new Point(); public Point LocNext = new Point(); public Point Vel = new Point(); public Map<Atom, Link> Bindings; public Atom() { this.Bindings = new HashMap<>(); } public void Bind(Atom other) { Link OtherLnk = new Link(); OtherLnk.mine = other; Link MeLnk = new Link(); MeLnk.mine = this; MeLnk.InterLink(OtherLnk); this.Bindings.put(other, MeLnk); other.Bindings.put(this, OtherLnk); } public void Rollover() { this.Loc.Copy(this.LocNext); } /* **************************************************************************** */ public void Seek_Bindings(Atom[] Atoms) { Atom you;// ultimately replace this with 2d array-based collision detection. double dif; int NumAtoms = Atoms.length; for (int acnt1 = 0; acnt1 < NumAtoms; acnt1++) { you = Atoms[acnt1]; if (this != you) { if (!this.Bindings.containsKey(you)) {// Find out if you are already connected to me. dif = this.Loc.DeltaMag(you.Loc); if (dif < Link.BindingRadius) {// if not bound, then bind this.Bind(you); } } } } } /* **************************************************************************** */ public void Seek_Unbindings() { Atom YouAtom; Link MeLnk; double dif; Iterator it = this.Bindings.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); MeLnk = (Link) pair.getValue(); // System.out.println(pair.getKey() + " = " + pair.getValue()); //YouAtom = MeLnk.GetOtherAtom(); YouAtom = (Atom) pair.getKey(); dif = this.Loc.DeltaMag(YouAtom.Loc); if (dif > Link.BreakingRadius) {// if bound, then break // here we remove from my table via iterator, and from your table via remove(key) YouAtom.Bindings.remove(this); it.remove(); MeLnk.mine = null; MeLnk.parallel.mine = null; } } } } /* **************************************************************************** */ public int NumAtoms = 100; public Atom[] Atoms; public int GenCnt = 0; /* **************************************************************************** */ public Things() { Atoms = new Atom[NumAtoms]; } /* **************************************************************************** */ public void React() { GenCnt++; Atom me; Link MeLnk; Point DiffV = new Point(); for (int acnt0 = 0; acnt0 < NumAtoms; acnt0++) { me = this.Atoms[acnt0]; me.LocNext.Clear(); Map<Atom, Link> yall = me.Bindings; int younum = yall.size(); for (int acnt1 = 0; acnt1 < younum; acnt1++) { MeLnk = yall.get(acnt1); if (MeLnk.Spring.GenStamp < GenCnt) { MeLnk.CalcForceVector(DiffV);// f=ma but m is always 1 for now MeLnk.Spring.Copy(DiffV); MeLnk.Spring.GenStamp = GenCnt; } // to do: gotta fix this so force is going opposite directions for each end of the spring me.LocNext.AddVec(MeLnk.Spring);// Accumulate all displacements into my next move. //you = MeLnk.GetOtherAtom(); dif = me.Loc.DeltaMag(you.Loc); // do physics here // spring physics, then define new locations and speeds // phys 0: go through all my neighbors and see which springs are bent. apply force to myself accordingly for each spring. // phys 1: after all personal next locs are calculated, then rollover for everybody. } } } /* **************************************************************************** */ public void Rebind() { Atom me; for (int acnt0 = 0; acnt0 < NumAtoms; acnt0++) { me = this.Atoms[acnt0]; /* I can scan all nbrs for new bindings. Though I only need to scan my own connections for UNbindings. so I'm already pointing to the link in question when/if I want to break it. */ me.Seek_Unbindings(); me.Seek_Bindings(this.Atoms); } } } /* Set<String> keys = hm.keySet(); for(String key: keys){ System.out.println("Value of "+key+" is: "+hm.get(key)); } Enumeration e = ht.elements(); while (e.hasMoreElements()){ System.out.println(e.nextElement()); } public static void printMap(Map mp) {// http://stackoverflow.com/questions/1066589/iterate-through-a-hashmap Iterator it = mp.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); System.out.println(pair.getKey() + " = " + pair.getValue()); it.remove(); // avoids a ConcurrentModificationException } } for (Map.Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); // ... } for (Object value : map.values()) { // ... } */
MultiTool/Clay
src/clay/Things.java
Java
gpl-2.0
9,794
#include "stdafx.h" #include <textserv.h> #pragma comment(lib, "riched20.lib") // These constants are for backward compatibility. They are the // sizes used for initialization and reset in RichEdit 1.0 namespace DirectUICore { const LONG cInitTextMax = (32 * 1024) - 1; EXTERN_C const IID IID_ITextServices = { // 8d33f740-cf58-11ce-a89d-00aa006cadc5 0x8d33f740, 0xcf58, 0x11ce, {0xa8, 0x9d, 0x00, 0xaa, 0x00, 0x6c, 0xad, 0xc5} }; EXTERN_C const IID IID_ITextHost = { /* c5bdd8d0-d26e-11ce-a89e-00aa006cadc5 */ 0xc5bdd8d0, 0xd26e, 0x11ce, {0xa8, 0x9e, 0x00, 0xaa, 0x00, 0x6c, 0xad, 0xc5} }; #ifndef LY_PER_INCH #define LY_PER_INCH 1440 #endif #ifndef HIMETRIC_PER_INCH #define HIMETRIC_PER_INCH 2540 #endif class CTxtWinHost : public ITextHost { public: CTxtWinHost(); BOOL Init(CRichEditUI *re , const CREATESTRUCT *pcs); virtual ~CTxtWinHost(); ITextServices* GetTextServices(void) { return pserv; } void SetClientRect(RECT *prc); RECT* GetClientRect() { return &rcClient; } BOOL GetWordWrap(void) { return fWordWrap; } void SetWordWrap(BOOL fWordWrap); BOOL GetReadOnly(); void SetReadOnly(BOOL fReadOnly); void SetFont(HFONT hFont); void SetColor(DWORD dwColor); SIZEL* GetExtent(); void SetExtent(SIZEL *psizelExtent); void LimitText(LONG nChars); BOOL IsCaptured(); BOOL GetAllowBeep(); void SetAllowBeep(BOOL fAllowBeep); WORD GetDefaultAlign(); void SetDefaultAlign(WORD wNewAlign); BOOL GetRichTextFlag(); void SetRichTextFlag(BOOL fNew); LONG GetDefaultLeftIndent(); void SetDefaultLeftIndent(LONG lNewIndent); BOOL SetSaveSelection(BOOL fSaveSelection); HRESULT OnTxInPlaceDeactivate(); HRESULT OnTxInPlaceActivate(LPCRECT prcClient); BOOL GetActiveState(void) { return fInplaceActive; } BOOL DoSetCursor(RECT *prc, POINT *pt); void SetTransparent(BOOL fTransparent); void GetControlRect(LPRECT prc); LONG SetAccelPos(LONG laccelpos); WCHAR SetPasswordChar(WCHAR chPasswordChar); void SetDisabled(BOOL fOn); LONG SetSelBarWidth(LONG lSelBarWidth); BOOL GetTimerState(); void SetCharFormat(CHARFORMAT2W &c); void SetParaFormat(PARAFORMAT2 &p); // ----------------------------- // IUnknown interface // ----------------------------- virtual HRESULT _stdcall QueryInterface(REFIID riid, void **ppvObject); virtual ULONG _stdcall AddRef(void); virtual ULONG _stdcall Release(void); // ----------------------------- // ITextHost interface // ----------------------------- virtual HDC TxGetDC(); virtual INT TxReleaseDC(HDC hdc); virtual BOOL TxShowScrollBar(INT fnBar, BOOL fShow); virtual BOOL TxEnableScrollBar (INT fuSBFlags, INT fuArrowflags); virtual BOOL TxSetScrollRange(INT fnBar, LONG nMinPos, INT nMaxPos, BOOL fRedraw); virtual BOOL TxSetScrollPos (INT fnBar, INT nPos, BOOL fRedraw); virtual void TxInvalidateRect(LPCRECT prc, BOOL fMode); virtual void TxViewChange(BOOL fUpdate); virtual BOOL TxCreateCaret(HBITMAP hbmp, INT xWidth, INT yHeight); virtual BOOL TxShowCaret(BOOL fShow); virtual BOOL TxSetCaretPos(INT x, INT y); virtual BOOL TxSetTimer(UINT idTimer, UINT uTimeout); virtual void TxKillTimer(UINT idTimer); virtual void TxScrollWindowEx (INT dx, INT dy, LPCRECT lprcScroll, LPCRECT lprcClip, HRGN hrgnUpdate, LPRECT lprcUpdate, UINT fuScroll); virtual void TxSetCapture(BOOL fCapture); virtual void TxSetFocus(); virtual void TxSetCursor(HCURSOR hcur, BOOL fText); virtual BOOL TxScreenToClient (LPPOINT lppt); virtual BOOL TxClientToScreen (LPPOINT lppt); virtual HRESULT TxActivate( LONG * plOldState ); virtual HRESULT TxDeactivate( LONG lNewState ); virtual HRESULT TxGetClientRect(LPRECT prc); virtual HRESULT TxGetViewInset(LPRECT prc); virtual HRESULT TxGetCharFormat(const CHARFORMATW **ppCF ); virtual HRESULT TxGetParaFormat(const PARAFORMAT **ppPF); virtual COLORREF TxGetSysColor(int nIndex); virtual HRESULT TxGetBackStyle(TXTBACKSTYLE *pstyle); virtual HRESULT TxGetMaxLength(DWORD *plength); virtual HRESULT TxGetScrollBars(DWORD *pdwScrollBar); virtual HRESULT TxGetPasswordChar(TCHAR *pch); virtual HRESULT TxGetAcceleratorPos(LONG *pcp); virtual HRESULT TxGetExtent(LPSIZEL lpExtent); virtual HRESULT OnTxCharFormatChange (const CHARFORMATW * pcf); virtual HRESULT OnTxParaFormatChange (const PARAFORMAT * ppf); virtual HRESULT TxGetPropertyBits(DWORD dwMask, DWORD *pdwBits); virtual HRESULT TxNotify(DWORD iNotify, void *pv); virtual HIMC TxImmGetContext(void); virtual void TxImmReleaseContext(HIMC himc); virtual HRESULT TxGetSelectionBarWidth (LONG *lSelBarWidth); private: CRichEditUI *m_re; ULONG cRefs; // Reference Count ITextServices *pserv; // pointer to Text Services object // Properties DWORD dwStyle; // style bits unsigned fEnableAutoWordSel :1; // enable Word style auto word selection? unsigned fWordWrap :1; // Whether control should word wrap unsigned fAllowBeep :1; // Whether beep is allowed unsigned fRich :1; // Whether control is rich text unsigned fSaveSelection :1; // Whether to save the selection when inactive unsigned fInplaceActive :1; // Whether control is inplace active unsigned fTransparent :1; // Whether control is transparent unsigned fTimer :1; // A timer is set unsigned fCaptured :1; LONG lSelBarWidth; // Width of the selection bar LONG cchTextMost; // maximum text size DWORD dwEventMask; // DoEvent mask to pass on to parent window LONG icf; LONG ipf; RECT rcClient; // Client Rect for this control SIZEL sizelExtent; // Extent array CHARFORMAT2W cf; // Default character format PARAFORMAT2 pf; // Default paragraph format LONG laccelpos; // Accelerator position WCHAR chPasswordChar; // Password character }; // Convert Pixels on the X axis to Himetric LONG DXtoHimetricX(LONG dx, LONG xPerInch) { return (LONG) MulDiv(dx, HIMETRIC_PER_INCH, xPerInch); } // Convert Pixels on the Y axis to Himetric LONG DYtoHimetricY(LONG dy, LONG yPerInch) { return (LONG) MulDiv(dy, HIMETRIC_PER_INCH, yPerInch); } HRESULT InitDefaultCharFormat(CRichEditUI* re, CHARFORMAT2W* pcf, HFONT hfont) { memset(pcf, 0, sizeof(CHARFORMAT2W)); LOGFONT lf; if( !hfont ) hfont = re->GetManager()->GetFont(re->GetFont()); ::GetObject(hfont, sizeof(LOGFONT), &lf); DWORD dwColor = re->GetTextColor(); pcf->cbSize = sizeof(CHARFORMAT2W); pcf->crTextColor = RGB(GetBValue(dwColor), GetGValue(dwColor), GetRValue(dwColor)); LONG yPixPerInch = GetDeviceCaps(re->GetManager()->GetPaintDC(), LOGPIXELSY); pcf->yHeight = -lf.lfHeight * LY_PER_INCH / yPixPerInch; pcf->yOffset = 0; pcf->dwEffects = 0; pcf->dwMask = CFM_SIZE | CFM_OFFSET | CFM_FACE | CFM_CHARSET | CFM_COLOR | CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE; if(lf.lfWeight >= FW_BOLD) pcf->dwEffects |= CFE_BOLD; if(lf.lfItalic) pcf->dwEffects |= CFE_ITALIC; if(lf.lfUnderline) pcf->dwEffects |= CFE_UNDERLINE; pcf->bCharSet = lf.lfCharSet; pcf->bPitchAndFamily = lf.lfPitchAndFamily; #ifdef _UNICODE _tcscpy(pcf->szFaceName, lf.lfFaceName); #else //need to thunk pcf->szFaceName to a standard char string.in this case it's easy because our thunk is also our copy MultiByteToWideChar(CP_ACP, 0, lf.lfFaceName, LF_FACESIZE, pcf->szFaceName, LF_FACESIZE) ; #endif return S_OK; } HRESULT InitDefaultParaFormat(CRichEditUI* re, PARAFORMAT2* ppf) { memset(ppf, 0, sizeof(PARAFORMAT2)); ppf->cbSize = sizeof(PARAFORMAT2); ppf->dwMask = PFM_ALL; ppf->wAlignment = PFA_LEFT; ppf->cTabCount = 1; ppf->rgxTabs[0] = lDefaultTab; return S_OK; } HRESULT CreateHost(CRichEditUI *re, const CREATESTRUCT *pcs, CTxtWinHost **pptec) { HRESULT hr = E_FAIL; //GdiSetBatchLimit(1); CTxtWinHost *phost = new CTxtWinHost(); if(phost) { if (phost->Init(re, pcs)) { *pptec = phost; hr = S_OK; } } if (FAILED(hr)) { delete phost; } return TRUE; } CTxtWinHost::CTxtWinHost() : m_re(NULL) { ::ZeroMemory(&cRefs, sizeof(CTxtWinHost) - offsetof(CTxtWinHost, cRefs)); cchTextMost = cInitTextMax; laccelpos = -1; } CTxtWinHost::~CTxtWinHost() { pserv->OnTxInPlaceDeactivate(); pserv->Release(); } ////////////////////// Create/Init/Destruct Commands /////////////////////// BOOL CTxtWinHost::Init(CRichEditUI *re, const CREATESTRUCT *pcs) { IUnknown *pUnk; HRESULT hr; m_re = re; // Initialize Reference count cRefs = 1; // Create and cache CHARFORMAT for this control if(FAILED(InitDefaultCharFormat(re, &cf, NULL))) goto err; // Create and cache PARAFORMAT for this control if(FAILED(InitDefaultParaFormat(re, &pf))) goto err; // edit controls created without a window are multiline by default // so that paragraph formats can be dwStyle = ES_MULTILINE; // edit controls are rich by default fRich = re->IsRich(); cchTextMost = re->GetLimitText(); if (pcs ) { dwStyle = pcs->style; if ( !(dwStyle & (ES_AUTOHSCROLL | WS_HSCROLL)) ) { fWordWrap = TRUE; } } if( !(dwStyle & ES_LEFT) ) { if(dwStyle & ES_CENTER) pf.wAlignment = PFA_CENTER; else if(dwStyle & ES_RIGHT) pf.wAlignment = PFA_RIGHT; } fInplaceActive = TRUE; // Create Text Services component if(FAILED(CreateTextServices(NULL, this, &pUnk))) goto err; hr = pUnk->QueryInterface(IID_ITextServices,(void **)&pserv); // Whether the previous call succeeded or failed we are done // with the private interface. pUnk->Release(); if(FAILED(hr)) { goto err; } // Set window text if(pcs && pcs->lpszName) { #ifdef _UNICODE if(FAILED(pserv->TxSetText((TCHAR *)pcs->lpszName))) goto err; #else size_t iLen = _tcslen(pcs->lpszName); LPWSTR lpText = new WCHAR[iLen + 1]; ::ZeroMemory(lpText, (iLen + 1) * sizeof(WCHAR)); ::MultiByteToWideChar(CP_ACP, 0, pcs->lpszName, -1, (LPWSTR)lpText, iLen) ; if(FAILED(pserv->TxSetText((LPWSTR)lpText))) { delete[] lpText; goto err; } delete[] lpText; #endif } return TRUE; err: return FALSE; } ///////////////////////////////// IUnknown //////////////////////////////// HRESULT CTxtWinHost::QueryInterface(REFIID riid, void **ppvObject) { HRESULT hr = E_NOINTERFACE; *ppvObject = NULL; if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_ITextHost)) { AddRef(); *ppvObject = (ITextHost *) this; hr = S_OK; } return hr; } ULONG CTxtWinHost::AddRef(void) { return ++cRefs; } ULONG CTxtWinHost::Release(void) { ULONG c_Refs = --cRefs; if (c_Refs == 0) { delete this; } return c_Refs; } ///////////////////////////////// Far East Support ////////////////////////////////////// HIMC CTxtWinHost::TxImmGetContext(void) { return NULL; } void CTxtWinHost::TxImmReleaseContext(HIMC himc) { //::ImmReleaseContext( hwnd, himc ); } //////////////////////////// ITextHost Interface //////////////////////////// HDC CTxtWinHost::TxGetDC() { return m_re->GetManager()->GetPaintDC(); } int CTxtWinHost::TxReleaseDC(HDC hdc) { return 1; } BOOL CTxtWinHost::TxShowScrollBar(INT fnBar, BOOL fShow) { CScrollBarUI* pVerticalScrollBar = m_re->GetVerticalScrollBar(); CScrollBarUI* pHorizontalScrollBar = m_re->GetHorizontalScrollBar(); if( fnBar == SB_VERT && pVerticalScrollBar ) { pVerticalScrollBar->SetVisible(fShow == TRUE); } else if( fnBar == SB_HORZ && pHorizontalScrollBar ) { pHorizontalScrollBar->SetVisible(fShow == TRUE); } else if( fnBar == SB_BOTH ) { if( pVerticalScrollBar ) pVerticalScrollBar->SetVisible(fShow == TRUE); if( pHorizontalScrollBar ) pHorizontalScrollBar->SetVisible(fShow == TRUE); } return TRUE; } BOOL CTxtWinHost::TxEnableScrollBar (INT fuSBFlags, INT fuArrowflags) { if( fuSBFlags == SB_VERT ) { m_re->EnableScrollBar(true, m_re->GetHorizontalScrollBar() != NULL); m_re->GetVerticalScrollBar()->SetVisible(fuArrowflags != ESB_DISABLE_BOTH); } else if( fuSBFlags == SB_HORZ ) { m_re->EnableScrollBar(m_re->GetVerticalScrollBar() != NULL, true); m_re->GetHorizontalScrollBar()->SetVisible(fuArrowflags != ESB_DISABLE_BOTH); } else if( fuSBFlags == SB_BOTH ) { m_re->EnableScrollBar(true, true); m_re->GetVerticalScrollBar()->SetVisible(fuArrowflags != ESB_DISABLE_BOTH); m_re->GetHorizontalScrollBar()->SetVisible(fuArrowflags != ESB_DISABLE_BOTH); } return TRUE; } BOOL CTxtWinHost::TxSetScrollRange(INT fnBar, LONG nMinPos, INT nMaxPos, BOOL fRedraw) { CScrollBarUI* pVerticalScrollBar = m_re->GetVerticalScrollBar(); CScrollBarUI* pHorizontalScrollBar = m_re->GetHorizontalScrollBar(); if( fnBar == SB_VERT && pVerticalScrollBar ) { if( nMaxPos - nMinPos - rcClient.bottom + rcClient.top <= 0 ) { pVerticalScrollBar->SetVisible(false); } else { pVerticalScrollBar->SetVisible(true); pVerticalScrollBar->SetScrollRange(nMaxPos - nMinPos - rcClient.bottom + rcClient.top); } } else if( fnBar == SB_HORZ && pHorizontalScrollBar ) { if( nMaxPos - nMinPos - rcClient.right + rcClient.left <= 0 ) { pHorizontalScrollBar->SetVisible(false); } else { pHorizontalScrollBar->SetVisible(true); pHorizontalScrollBar->SetScrollRange(nMaxPos - nMinPos - rcClient.right + rcClient.left); } } return TRUE; } BOOL CTxtWinHost::TxSetScrollPos (INT fnBar, INT nPos, BOOL fRedraw) { CScrollBarUI* pVerticalScrollBar = m_re->GetVerticalScrollBar(); CScrollBarUI* pHorizontalScrollBar = m_re->GetHorizontalScrollBar(); if( fnBar == SB_VERT && pVerticalScrollBar ) { pVerticalScrollBar->SetScrollPos(nPos); } else if( fnBar == SB_HORZ && pHorizontalScrollBar ) { pHorizontalScrollBar->SetScrollPos(nPos); } return TRUE; } void CTxtWinHost::TxInvalidateRect(LPCRECT prc, BOOL fMode) { if( prc == NULL ) { m_re->GetManager()->Invalidate(rcClient); return; } RECT rc = *prc; m_re->GetManager()->Invalidate(rc); } void CTxtWinHost::TxViewChange(BOOL fUpdate) { if( m_re->OnTxViewChanged() ) m_re->Invalidate(); } BOOL CTxtWinHost::TxCreateCaret(HBITMAP hbmp, INT xWidth, INT yHeight) { return ::CreateCaret(m_re->GetManager()->GetPaintWindow(), hbmp, xWidth, yHeight); } BOOL CTxtWinHost::TxShowCaret(BOOL fShow) { if(fShow) return ::ShowCaret(m_re->GetManager()->GetPaintWindow()); else return ::HideCaret(m_re->GetManager()->GetPaintWindow()); } BOOL CTxtWinHost::TxSetCaretPos(INT x, INT y) { return ::SetCaretPos(x, y); } BOOL CTxtWinHost::TxSetTimer(UINT idTimer, UINT uTimeout) { fTimer = TRUE; return m_re->GetManager()->SetTimer(m_re, idTimer, uTimeout) == TRUE; } void CTxtWinHost::TxKillTimer(UINT idTimer) { m_re->GetManager()->KillTimer(m_re, idTimer); fTimer = FALSE; } void CTxtWinHost::TxScrollWindowEx (INT dx, INT dy, LPCRECT lprcScroll, LPCRECT lprcClip, HRGN hrgnUpdate, LPRECT lprcUpdate, UINT fuScroll) { return; } void CTxtWinHost::TxSetCapture(BOOL fCapture) { if (fCapture) m_re->GetManager()->SetCapture(); else m_re->GetManager()->ReleaseCapture(); fCaptured = fCapture; } void CTxtWinHost::TxSetFocus() { m_re->SetFocus(); } void CTxtWinHost::TxSetCursor(HCURSOR hcur, BOOL fText) { ::SetCursor(hcur); } BOOL CTxtWinHost::TxScreenToClient(LPPOINT lppt) { return ::ScreenToClient(m_re->GetManager()->GetPaintWindow(), lppt); } BOOL CTxtWinHost::TxClientToScreen(LPPOINT lppt) { return ::ClientToScreen(m_re->GetManager()->GetPaintWindow(), lppt); } HRESULT CTxtWinHost::TxActivate(LONG *plOldState) { return S_OK; } HRESULT CTxtWinHost::TxDeactivate(LONG lNewState) { return S_OK; } HRESULT CTxtWinHost::TxGetClientRect(LPRECT prc) { *prc = rcClient; GetControlRect(prc); return NOERROR; } HRESULT CTxtWinHost::TxGetViewInset(LPRECT prc) { prc->left = prc->right = prc->top = prc->bottom = 0; return NOERROR; } HRESULT CTxtWinHost::TxGetCharFormat(const CHARFORMATW **ppCF) { *ppCF = &cf; return NOERROR; } HRESULT CTxtWinHost::TxGetParaFormat(const PARAFORMAT **ppPF) { *ppPF = &pf; return NOERROR; } COLORREF CTxtWinHost::TxGetSysColor(int nIndex) { return ::GetSysColor(nIndex); } HRESULT CTxtWinHost::TxGetBackStyle(TXTBACKSTYLE *pstyle) { *pstyle = !fTransparent ? TXTBACK_OPAQUE : TXTBACK_TRANSPARENT; return NOERROR; } HRESULT CTxtWinHost::TxGetMaxLength(DWORD *pLength) { *pLength = cchTextMost; return NOERROR; } HRESULT CTxtWinHost::TxGetScrollBars(DWORD *pdwScrollBar) { *pdwScrollBar = dwStyle & (WS_VSCROLL | WS_HSCROLL | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_DISABLENOSCROLL); return NOERROR; } HRESULT CTxtWinHost::TxGetPasswordChar(TCHAR *pch) { #ifdef _UNICODE *pch = chPasswordChar; #else ::WideCharToMultiByte(CP_ACP, 0, &chPasswordChar, 1, pch, 1, NULL, NULL) ; #endif return NOERROR; } HRESULT CTxtWinHost::TxGetAcceleratorPos(LONG *pcp) { *pcp = laccelpos; return S_OK; } HRESULT CTxtWinHost::OnTxCharFormatChange(const CHARFORMATW *pcf) { return S_OK; } HRESULT CTxtWinHost::OnTxParaFormatChange(const PARAFORMAT *ppf) { return S_OK; } HRESULT CTxtWinHost::TxGetPropertyBits(DWORD dwMask, DWORD *pdwBits) { DWORD dwProperties = 0; if (fRich) { dwProperties = TXTBIT_RICHTEXT; } if (dwStyle & ES_MULTILINE) { dwProperties |= TXTBIT_MULTILINE; } if (dwStyle & ES_READONLY) { dwProperties |= TXTBIT_READONLY; } if (dwStyle & ES_PASSWORD) { dwProperties |= TXTBIT_USEPASSWORD; } if (!(dwStyle & ES_NOHIDESEL)) { dwProperties |= TXTBIT_HIDESELECTION; } if (fEnableAutoWordSel) { dwProperties |= TXTBIT_AUTOWORDSEL; } if (fWordWrap) { dwProperties |= TXTBIT_WORDWRAP; } if (fAllowBeep) { dwProperties |= TXTBIT_ALLOWBEEP; } if (fSaveSelection) { dwProperties |= TXTBIT_SAVESELECTION; } *pdwBits = dwProperties & dwMask; return NOERROR; } HRESULT CTxtWinHost::TxNotify(DWORD iNotify, void *pv) { if( iNotify == EN_REQUESTRESIZE ) { RECT rc; REQRESIZE *preqsz = (REQRESIZE *)pv; GetControlRect(&rc); rc.bottom = rc.top + preqsz->rc.bottom; rc.right = rc.left + preqsz->rc.right; SetClientRect(&rc); return S_OK; } m_re->OnTxNotify(iNotify, pv); return S_OK; } HRESULT CTxtWinHost::TxGetExtent(LPSIZEL lpExtent) { *lpExtent = sizelExtent; return S_OK; } HRESULT CTxtWinHost::TxGetSelectionBarWidth (LONG *plSelBarWidth) { *plSelBarWidth = lSelBarWidth; return S_OK; } void CTxtWinHost::SetWordWrap(BOOL fWordWrap) { fWordWrap = fWordWrap; pserv->OnTxPropertyBitsChange(TXTBIT_WORDWRAP, fWordWrap ? TXTBIT_WORDWRAP : 0); } BOOL CTxtWinHost::GetReadOnly() { return (dwStyle & ES_READONLY) != 0; } void CTxtWinHost::SetReadOnly(BOOL fReadOnly) { if (fReadOnly) { dwStyle |= ES_READONLY; } else { dwStyle &= ~ES_READONLY; } pserv->OnTxPropertyBitsChange(TXTBIT_READONLY, fReadOnly ? TXTBIT_READONLY : 0); } void CTxtWinHost::SetFont(HFONT hFont) { if( hFont == NULL ) return; LOGFONT lf; ::GetObject(hFont, sizeof(LOGFONT), &lf); LONG yPixPerInch = ::GetDeviceCaps(m_re->GetManager()->GetPaintDC(), LOGPIXELSY); cf.yHeight = -lf.lfHeight * LY_PER_INCH / yPixPerInch; if(lf.lfWeight >= FW_BOLD) cf.dwEffects |= CFE_BOLD; if(lf.lfItalic) cf.dwEffects |= CFE_ITALIC; if(lf.lfUnderline) cf.dwEffects |= CFE_UNDERLINE; cf.bCharSet = lf.lfCharSet; cf.bPitchAndFamily = lf.lfPitchAndFamily; #ifdef _UNICODE _tcscpy(cf.szFaceName, lf.lfFaceName); #else //need to thunk pcf->szFaceName to a standard char string.in this case it's easy because our thunk is also our copy MultiByteToWideChar(CP_ACP, 0, lf.lfFaceName, LF_FACESIZE, cf.szFaceName, LF_FACESIZE) ; #endif pserv->OnTxPropertyBitsChange(TXTBIT_CHARFORMATCHANGE, TXTBIT_CHARFORMATCHANGE); } void CTxtWinHost::SetColor(DWORD dwColor) { cf.crTextColor = RGB(GetBValue(dwColor), GetGValue(dwColor), GetRValue(dwColor)); pserv->OnTxPropertyBitsChange(TXTBIT_CHARFORMATCHANGE, TXTBIT_CHARFORMATCHANGE); } SIZEL* CTxtWinHost::GetExtent() { return &sizelExtent; } void CTxtWinHost::SetExtent(SIZEL *psizelExtent) { sizelExtent = *psizelExtent; pserv->OnTxPropertyBitsChange(TXTBIT_EXTENTCHANGE, TXTBIT_EXTENTCHANGE); } void CTxtWinHost::LimitText(LONG nChars) { cchTextMost = nChars; if( cchTextMost <= 0 ) cchTextMost = cInitTextMax; pserv->OnTxPropertyBitsChange(TXTBIT_MAXLENGTHCHANGE, TXTBIT_MAXLENGTHCHANGE); } BOOL CTxtWinHost::IsCaptured() { return fCaptured; } BOOL CTxtWinHost::GetAllowBeep() { return fAllowBeep; } void CTxtWinHost::SetAllowBeep(BOOL fAllowBeep) { fAllowBeep = fAllowBeep; pserv->OnTxPropertyBitsChange(TXTBIT_ALLOWBEEP, fAllowBeep ? TXTBIT_ALLOWBEEP : 0); } WORD CTxtWinHost::GetDefaultAlign() { return pf.wAlignment; } void CTxtWinHost::SetDefaultAlign(WORD wNewAlign) { pf.wAlignment = wNewAlign; // Notify control of property change pserv->OnTxPropertyBitsChange(TXTBIT_PARAFORMATCHANGE, 0); } BOOL CTxtWinHost::GetRichTextFlag() { return fRich; } void CTxtWinHost::SetRichTextFlag(BOOL fNew) { fRich = fNew; pserv->OnTxPropertyBitsChange(TXTBIT_RICHTEXT, fNew ? TXTBIT_RICHTEXT : 0); } LONG CTxtWinHost::GetDefaultLeftIndent() { return pf.dxOffset; } void CTxtWinHost::SetDefaultLeftIndent(LONG lNewIndent) { pf.dxOffset = lNewIndent; pserv->OnTxPropertyBitsChange(TXTBIT_PARAFORMATCHANGE, 0); } void CTxtWinHost::SetClientRect(RECT *prc) { rcClient = *prc; LONG xPerInch = ::GetDeviceCaps(m_re->GetManager()->GetPaintDC(), LOGPIXELSX); LONG yPerInch = ::GetDeviceCaps(m_re->GetManager()->GetPaintDC(), LOGPIXELSY); sizelExtent.cx = DXtoHimetricX(rcClient.right - rcClient.left, xPerInch); sizelExtent.cy = DYtoHimetricY(rcClient.bottom - rcClient.top, yPerInch); pserv->OnTxPropertyBitsChange(TXTBIT_VIEWINSETCHANGE, TXTBIT_VIEWINSETCHANGE); } BOOL CTxtWinHost::SetSaveSelection(BOOL f_SaveSelection) { BOOL fResult = f_SaveSelection; fSaveSelection = f_SaveSelection; // notify text services of property change pserv->OnTxPropertyBitsChange(TXTBIT_SAVESELECTION, fSaveSelection ? TXTBIT_SAVESELECTION : 0); return fResult; } HRESULT CTxtWinHost::OnTxInPlaceDeactivate() { HRESULT hr = pserv->OnTxInPlaceDeactivate(); if (SUCCEEDED(hr)) { fInplaceActive = FALSE; } return hr; } HRESULT CTxtWinHost::OnTxInPlaceActivate(LPCRECT prcClient) { fInplaceActive = TRUE; HRESULT hr = pserv->OnTxInPlaceActivate(prcClient); if (FAILED(hr)) { fInplaceActive = FALSE; } return hr; } BOOL CTxtWinHost::DoSetCursor(RECT *prc, POINT *pt) { RECT rc = prc ? *prc : rcClient; // Is this in our rectangle? if (PtInRect(&rc, *pt)) { RECT *prcClient = (!fInplaceActive || prc) ? &rc : NULL; pserv->OnTxSetCursor(DVASPECT_CONTENT, -1, NULL, NULL, m_re->GetManager()->GetPaintDC(), NULL, prcClient, pt->x, pt->y); return TRUE; } return FALSE; } void CTxtWinHost::GetControlRect(LPRECT prc) { prc->top = rcClient.top; prc->bottom = rcClient.bottom; prc->left = rcClient.left; prc->right = rcClient.right; } void CTxtWinHost::SetTransparent(BOOL f_Transparent) { fTransparent = f_Transparent; // notify text services of property change pserv->OnTxPropertyBitsChange(TXTBIT_BACKSTYLECHANGE, 0); } LONG CTxtWinHost::SetAccelPos(LONG l_accelpos) { LONG laccelposOld = l_accelpos; laccelpos = l_accelpos; // notify text services of property change pserv->OnTxPropertyBitsChange(TXTBIT_SHOWACCELERATOR, 0); return laccelposOld; } WCHAR CTxtWinHost::SetPasswordChar(WCHAR ch_PasswordChar) { WCHAR chOldPasswordChar = chPasswordChar; chPasswordChar = ch_PasswordChar; // notify text services of property change pserv->OnTxPropertyBitsChange(TXTBIT_USEPASSWORD, (chPasswordChar != 0) ? TXTBIT_USEPASSWORD : 0); return chOldPasswordChar; } void CTxtWinHost::SetDisabled(BOOL fOn) { cf.dwMask |= CFM_COLOR | CFM_DISABLED; cf.dwEffects |= CFE_AUTOCOLOR | CFE_DISABLED; if( !fOn ) { cf.dwEffects &= ~CFE_DISABLED; } pserv->OnTxPropertyBitsChange(TXTBIT_CHARFORMATCHANGE, TXTBIT_CHARFORMATCHANGE); } LONG CTxtWinHost::SetSelBarWidth(LONG l_SelBarWidth) { LONG lOldSelBarWidth = lSelBarWidth; lSelBarWidth = l_SelBarWidth; if (lSelBarWidth) { dwStyle |= ES_SELECTIONBAR; } else { dwStyle &= (~ES_SELECTIONBAR); } pserv->OnTxPropertyBitsChange(TXTBIT_SELBARCHANGE, TXTBIT_SELBARCHANGE); return lOldSelBarWidth; } BOOL CTxtWinHost::GetTimerState() { return fTimer; } void CTxtWinHost::SetCharFormat(CHARFORMAT2W &c) { cf = c; } void CTxtWinHost::SetParaFormat(PARAFORMAT2 &p) { pf = p; } ///////////////////////////////////////////////////////////////////////////////////// // // CRichEditUI::CRichEditUI() : m_pTwh(NULL), m_bVScrollBarFixing(false), m_bWantTab(true), m_bWantReturn(true), m_bWantCtrlReturn(true), m_bRich(true), m_bReadOnly(false), m_bWordWrap(false), m_dwTextColor(0), m_iFont(-1), m_iLimitText(cInitTextMax), m_lTwhStyle(ES_MULTILINE) { } CRichEditUI::~CRichEditUI() { if( m_pTwh ) { m_pTwh->Release(); m_pManager->RemoveMessageFilter(this); } } LPCTSTR CRichEditUI::GetClass() const { return _T("RichEditUI"); } LPVOID CRichEditUI::GetInterface(LPCTSTR pstrName) { if( _tcscmp(pstrName, _T("RichEdit")) == 0 ) return static_cast<CRichEditUI*>(this); return CContainerUI::GetInterface(pstrName); } UINT CRichEditUI::GetControlFlags() const { if( !IsEnabled() ) return CControlUI::GetControlFlags(); return UIFLAG_SETCURSOR | UIFLAG_TABSTOP; } bool CRichEditUI::IsWantTab() { return m_bWantTab; } void CRichEditUI::SetWantTab(bool bWantTab) { m_bWantTab = bWantTab; } bool CRichEditUI::IsWantReturn() { return m_bWantReturn; } void CRichEditUI::SetWantReturn(bool bWantReturn) { m_bWantReturn = bWantReturn; } bool CRichEditUI::IsWantCtrlReturn() { return m_bWantCtrlReturn; } void CRichEditUI::SetWantCtrlReturn(bool bWantCtrlReturn) { m_bWantCtrlReturn = bWantCtrlReturn; } bool CRichEditUI::IsRich() { return m_bRich; } void CRichEditUI::SetRich(bool bRich) { m_bRich = bRich; if( m_pTwh ) m_pTwh->SetRichTextFlag(bRich); } bool CRichEditUI::IsReadOnly() { return m_bReadOnly; } void CRichEditUI::SetReadOnly(bool bReadOnly) { m_bReadOnly = bReadOnly; if( m_pTwh ) m_pTwh->SetReadOnly(bReadOnly); } bool CRichEditUI::GetWordWrap() { return m_bWordWrap; } void CRichEditUI::SetWordWrap(bool bWordWrap) { m_bWordWrap = bWordWrap; if( m_pTwh ) m_pTwh->SetWordWrap(bWordWrap); } int CRichEditUI::GetFont() { return m_iFont; } void CRichEditUI::SetFont(int index) { m_iFont = index; if( m_pTwh ) { m_pTwh->SetFont(GetManager()->GetFont(m_iFont)); } } void CRichEditUI::SetFont(LPCTSTR pStrFontName, int nSize, bool bBold, bool bUnderline, bool bItalic) { if( m_pTwh ) { LOGFONT lf = { 0 }; ::GetObject(::GetStockObject(DEFAULT_GUI_FONT), sizeof(LOGFONT), &lf); _tcscpy(lf.lfFaceName, pStrFontName); lf.lfCharSet = DEFAULT_CHARSET; lf.lfHeight = -nSize; if( bBold ) lf.lfWeight += FW_BOLD; if( bUnderline ) lf.lfUnderline = TRUE; if( bItalic ) lf.lfItalic = TRUE; HFONT hFont = ::CreateFontIndirect(&lf); if( hFont == NULL ) return; m_pTwh->SetFont(hFont); ::DeleteObject(hFont); } } LONG CRichEditUI::GetWinStyle() { return m_lTwhStyle; } void CRichEditUI::SetWinStyle(LONG lStyle) { m_lTwhStyle = lStyle; } DWORD CRichEditUI::GetTextColor() { return m_dwTextColor; } void CRichEditUI::SetTextColor(DWORD dwTextColor) { m_dwTextColor = dwTextColor; if( m_pTwh ) { m_pTwh->SetColor(dwTextColor); } } int CRichEditUI::GetLimitText() { return m_iLimitText; } void CRichEditUI::SetLimitText(int iChars) { m_iLimitText = iChars; if( m_pTwh ) { m_pTwh->LimitText(m_iLimitText); } } long CRichEditUI::GetTextLength(DWORD dwFlags) const { GETTEXTLENGTHEX textLenEx; textLenEx.flags = dwFlags; #ifdef _UNICODE textLenEx.codepage = 1200; #else textLenEx.codepage = CP_ACP; #endif LRESULT lResult; TxSendMessage(EM_GETTEXTLENGTHEX, (WPARAM)&textLenEx, 0, &lResult); return (long)lResult; } CStdString CRichEditUI::GetText() const { long lLen = GetTextLength(GTL_DEFAULT); LPTSTR lpText = NULL; GETTEXTEX gt; gt.flags = GT_DEFAULT; #ifdef _UNICODE gt.cb = sizeof(TCHAR) * (lLen + 1) ; gt.codepage = 1200; lpText = new TCHAR[lLen + 1]; ::ZeroMemory(lpText, (lLen + 1) * sizeof(TCHAR)); #else gt.cb = sizeof(TCHAR) * lLen * 2 + 1; gt.codepage = CP_ACP; lpText = new TCHAR[lLen * 2 + 1]; ::ZeroMemory(lpText, (lLen * 2 + 1) * sizeof(TCHAR)); #endif gt.lpDefaultChar = NULL; gt.lpUsedDefChar = NULL; TxSendMessage(EM_GETTEXTEX, (WPARAM)&gt, (LPARAM)lpText, 0); CStdString sText(lpText); delete[] lpText; return sText; } void CRichEditUI::SetText(LPCTSTR pstrText) { m_sText = pstrText; if( !m_pTwh ) return; SetSel(0, -1); ReplaceSel(pstrText, FALSE); } bool CRichEditUI::GetModify() const { if( !m_pTwh ) return false; LRESULT lResult; TxSendMessage(EM_GETMODIFY, 0, 0, &lResult); return (BOOL)lResult == TRUE; } void CRichEditUI::SetModify(bool bModified) const { TxSendMessage(EM_SETMODIFY, bModified, 0, 0); } void CRichEditUI::GetSel(CHARRANGE &cr) const { TxSendMessage(EM_EXGETSEL, 0, (LPARAM)&cr, 0); } void CRichEditUI::GetSel(long& nStartChar, long& nEndChar) const { CHARRANGE cr; TxSendMessage(EM_EXGETSEL, 0, (LPARAM)&cr, 0); nStartChar = cr.cpMin; nEndChar = cr.cpMax; } int CRichEditUI::SetSel(CHARRANGE &cr) { LRESULT lResult; TxSendMessage(EM_EXSETSEL, 0, (LPARAM)&cr, &lResult); return (int)lResult; } int CRichEditUI::SetSel(long nStartChar, long nEndChar) { CHARRANGE cr; cr.cpMin = nStartChar; cr.cpMax = nEndChar; LRESULT lResult; TxSendMessage(EM_EXSETSEL, 0, (LPARAM)&cr, &lResult); return (int)lResult; } void CRichEditUI::ReplaceSel(LPCTSTR lpszNewText, bool bCanUndo) { #ifdef _UNICODE TxSendMessage(EM_REPLACESEL, (WPARAM) bCanUndo, (LPARAM)lpszNewText, 0); #else int iLen = _tcslen(lpszNewText); LPWSTR lpText = new WCHAR[iLen + 1]; ::ZeroMemory(lpText, (iLen + 1) * sizeof(WCHAR)); ::MultiByteToWideChar(CP_ACP, 0, lpszNewText, -1, (LPWSTR)lpText, iLen) ; TxSendMessage(EM_REPLACESEL, (WPARAM) bCanUndo, (LPARAM)lpText, 0); delete[] lpText; #endif } void CRichEditUI::ReplaceSelW(LPCWSTR lpszNewText, bool bCanUndo) { TxSendMessage(EM_REPLACESEL, (WPARAM) bCanUndo, (LPARAM)lpszNewText, 0); } CStdString CRichEditUI::GetSelText() const { if( !m_pTwh ) return CStdString(); CHARRANGE cr; cr.cpMin = cr.cpMax = 0; TxSendMessage(EM_EXGETSEL, 0, (LPARAM)&cr, 0); LPWSTR lpText = NULL; lpText = new WCHAR[cr.cpMax - cr.cpMin + 1]; ::ZeroMemory(lpText, (cr.cpMax - cr.cpMin + 1) * sizeof(WCHAR)); TxSendMessage(EM_GETSELTEXT, 0, (LPARAM)lpText, 0); CStdString sText; sText = (LPCWSTR)lpText; delete[] lpText; return sText; } int CRichEditUI::SetSelAll() { return SetSel(0, -1); } int CRichEditUI::SetSelNone() { return SetSel(-1, 0); } bool CRichEditUI::GetZoom(int& nNum, int& nDen) const { LRESULT lResult; TxSendMessage(EM_GETZOOM, (WPARAM)&nNum, (LPARAM)&nDen, &lResult); return (BOOL)lResult == TRUE; } bool CRichEditUI::SetZoom(int nNum, int nDen) { if (nNum < 0 || nNum > 64) return false; if (nDen < 0 || nDen > 64) return false; LRESULT lResult; TxSendMessage(EM_SETZOOM, nNum, nDen, &lResult); return (BOOL)lResult == TRUE; } bool CRichEditUI::SetZoomOff() { LRESULT lResult; TxSendMessage(EM_SETZOOM, 0, 0, &lResult); return (BOOL)lResult == TRUE; } WORD CRichEditUI::GetSelectionType() const { LRESULT lResult; TxSendMessage(EM_SELECTIONTYPE, 0, 0, &lResult); return (WORD)lResult; } bool CRichEditUI::GetAutoURLDetect() const { LRESULT lResult; TxSendMessage(EM_GETAUTOURLDETECT, 0, 0, &lResult); return (BOOL)lResult == TRUE; } bool CRichEditUI::SetAutoURLDetect(bool bAutoDetect) { LRESULT lResult; TxSendMessage(EM_AUTOURLDETECT, bAutoDetect, 0, &lResult); return (BOOL)lResult == FALSE; } DWORD CRichEditUI::GetEventMask() const { LRESULT lResult; TxSendMessage(EM_GETEVENTMASK, 0, 0, &lResult); return (DWORD)lResult; } DWORD CRichEditUI::SetEventMask(DWORD dwEventMask) { LRESULT lResult; TxSendMessage(EM_SETEVENTMASK, 0, dwEventMask, &lResult); return (DWORD)lResult; } CStdString CRichEditUI::GetTextRange(long nStartChar, long nEndChar) const { TEXTRANGEW tr = { 0 }; tr.chrg.cpMin = nStartChar; tr.chrg.cpMax = nEndChar; LPWSTR lpText = NULL; lpText = new WCHAR[nEndChar - nStartChar + 1]; ::ZeroMemory(lpText, (nEndChar - nStartChar + 1) * sizeof(WCHAR)); tr.lpstrText = lpText; TxSendMessage(EM_GETTEXTRANGE, 0, (LPARAM)&tr, 0); CStdString sText; sText = (LPCWSTR)lpText; delete[] lpText; return sText; } void CRichEditUI::HideSelection(bool bHide, bool bChangeStyle) { TxSendMessage(EM_HIDESELECTION, bHide, bChangeStyle, 0); } void CRichEditUI::ScrollCaret() { TxSendMessage(EM_SCROLLCARET, 0, 0, 0); } int CRichEditUI::InsertText(long nInsertAfterChar, LPCTSTR lpstrText, bool bCanUndo) { int nRet = SetSel(nInsertAfterChar, nInsertAfterChar); ReplaceSel(lpstrText, bCanUndo); return nRet; } int CRichEditUI::AppendText(LPCTSTR lpstrText, bool bCanUndo) { int nRet = SetSel(-1, -1); ReplaceSel(lpstrText, bCanUndo); return nRet; } DWORD CRichEditUI::GetDefaultCharFormat(CHARFORMAT2 &cf) const { cf.cbSize = sizeof(CHARFORMAT2); LRESULT lResult; TxSendMessage(EM_GETCHARFORMAT, 0, (LPARAM)&cf, &lResult); return (DWORD)lResult; } bool CRichEditUI::SetDefaultCharFormat(CHARFORMAT2 &cf) { if( !m_pTwh ) return false; cf.cbSize = sizeof(CHARFORMAT2); LRESULT lResult; TxSendMessage(EM_SETCHARFORMAT, 0, (LPARAM)&cf, &lResult); if( (BOOL)lResult == TRUE ) { CHARFORMAT2W cfw; cfw.cbSize = sizeof(CHARFORMAT2W); TxSendMessage(EM_GETCHARFORMAT, 1, (LPARAM)&cfw, 0); m_pTwh->SetCharFormat(cfw); return true; } return false; } DWORD CRichEditUI::GetSelectionCharFormat(CHARFORMAT2 &cf) const { cf.cbSize = sizeof(CHARFORMAT2); LRESULT lResult; TxSendMessage(EM_GETCHARFORMAT, 1, (LPARAM)&cf, &lResult); return (DWORD)lResult; } bool CRichEditUI::SetSelectionCharFormat(CHARFORMAT2 &cf) { if( !m_pTwh ) return false; cf.cbSize = sizeof(CHARFORMAT2); LRESULT lResult; TxSendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf, &lResult); return (BOOL)lResult == TRUE; } bool CRichEditUI::SetWordCharFormat(CHARFORMAT2 &cf) { if( !m_pTwh ) return false; cf.cbSize = sizeof(CHARFORMAT2); LRESULT lResult; TxSendMessage(EM_SETCHARFORMAT, SCF_SELECTION|SCF_WORD, (LPARAM)&cf, &lResult); return (BOOL)lResult == TRUE; } DWORD CRichEditUI::GetParaFormat(PARAFORMAT2 &pf) const { pf.cbSize = sizeof(PARAFORMAT2); LRESULT lResult; TxSendMessage(EM_GETPARAFORMAT, 0, (LPARAM)&pf, &lResult); return (DWORD)lResult; } bool CRichEditUI::SetParaFormat(PARAFORMAT2 &pf) { if( !m_pTwh ) return false; pf.cbSize = sizeof(PARAFORMAT2); LRESULT lResult; TxSendMessage(EM_SETPARAFORMAT, 0, (LPARAM)&pf, &lResult); if( (BOOL)lResult == TRUE ) { m_pTwh->SetParaFormat(pf); return true; } return false; } bool CRichEditUI::Redo() { if( !m_pTwh ) return false; LRESULT lResult; TxSendMessage(EM_REDO, 0, 0, &lResult); return (BOOL)lResult == TRUE; } bool CRichEditUI::Undo() { if( !m_pTwh ) return false; LRESULT lResult; TxSendMessage(EM_UNDO, 0, 0, &lResult); return (BOOL)lResult == TRUE; } void CRichEditUI::Clear() { TxSendMessage(WM_CLEAR, 0, 0, 0); } void CRichEditUI::Copy() { TxSendMessage(WM_COPY, 0, 0, 0); } void CRichEditUI::Cut() { TxSendMessage(WM_CUT, 0, 0, 0); } void CRichEditUI::Paste() { TxSendMessage(WM_PASTE, 0, 0, 0); } int CRichEditUI::GetLineCount() const { if( !m_pTwh ) return 0; LRESULT lResult; TxSendMessage(EM_GETLINECOUNT, 0, 0, &lResult); return (int)lResult; } CStdString CRichEditUI::GetLine(int nIndex, int nMaxLength) const { LPWSTR lpText = NULL; lpText = new WCHAR[nMaxLength + 1]; ::ZeroMemory(lpText, (nMaxLength + 1) * sizeof(WCHAR)); *(LPWORD)lpText = (WORD)nMaxLength; TxSendMessage(EM_GETLINE, nIndex, (LPARAM)lpText, 0); CStdString sText; sText = (LPCWSTR)lpText; delete[] lpText; return sText; } int CRichEditUI::LineIndex(int nLine) const { LRESULT lResult; TxSendMessage(EM_LINEINDEX, nLine, 0, &lResult); return (int)lResult; } int CRichEditUI::LineLength(int nLine) const { LRESULT lResult; TxSendMessage(EM_LINELENGTH, nLine, 0, &lResult); return (int)lResult; } bool CRichEditUI::LineScroll(int nLines, int nChars) { LRESULT lResult; TxSendMessage(EM_LINESCROLL, nChars, nLines, &lResult); return (BOOL)lResult == TRUE; } CPoint CRichEditUI::GetCharPos(long lChar) const { CPoint pt; TxSendMessage(EM_POSFROMCHAR, (WPARAM)&pt, (LPARAM)lChar, 0); return pt; } long CRichEditUI::LineFromChar(long nIndex) const { if( !m_pTwh ) return 0L; LRESULT lResult; TxSendMessage(EM_EXLINEFROMCHAR, 0, nIndex, &lResult); return (long)lResult; } CPoint CRichEditUI::PosFromChar(UINT nChar) const { POINTL pt; TxSendMessage(EM_POSFROMCHAR, (WPARAM)&pt, nChar, 0); return CPoint(pt.x, pt.y); } int CRichEditUI::CharFromPos(CPoint pt) const { POINTL ptl = {pt.x, pt.y}; if( !m_pTwh ) return 0; LRESULT lResult; TxSendMessage(EM_CHARFROMPOS, 0, (LPARAM)&ptl, &lResult); return (int)lResult; } void CRichEditUI::EmptyUndoBuffer() { TxSendMessage(EM_EMPTYUNDOBUFFER, 0, 0, 0); } UINT CRichEditUI::SetUndoLimit(UINT nLimit) { if( !m_pTwh ) return 0; LRESULT lResult; TxSendMessage(EM_SETUNDOLIMIT, (WPARAM) nLimit, 0, &lResult); return (UINT)lResult; } long CRichEditUI::StreamIn(int nFormat, EDITSTREAM &es) { if( !m_pTwh ) return 0L; LRESULT lResult; TxSendMessage(EM_STREAMIN, nFormat, (LPARAM)&es, &lResult); return (long)lResult; } long CRichEditUI::StreamOut(int nFormat, EDITSTREAM &es) { if( !m_pTwh ) return 0L; LRESULT lResult; TxSendMessage(EM_STREAMOUT, nFormat, (LPARAM)&es, &lResult); return (long)lResult; } void CRichEditUI::DoInit() { CREATESTRUCT cs; cs.style = m_lTwhStyle; cs.x = 0; cs.y = 0; cs.cy = 0; cs.cx = 0; cs.lpszName = m_sText.GetData(); CreateHost(this, &cs, &m_pTwh); if( m_pTwh ) { m_pTwh->SetTransparent(TRUE); LRESULT lResult; m_pTwh->GetTextServices()->TxSendMessage(EM_SETLANGOPTIONS, 0, 0, &lResult); m_pTwh->OnTxInPlaceActivate(NULL); m_pManager->AddMessageFilter(this); } } HRESULT CRichEditUI::TxSendMessage(UINT msg, WPARAM wparam, LPARAM lparam, LRESULT *plresult) const { if( m_pTwh ) { if( msg == WM_KEYDOWN && TCHAR(wparam) == VK_RETURN ) { if( !m_bWantReturn || (::GetKeyState(VK_CONTROL) < 0 && !m_bWantCtrlReturn) ) { if( m_pManager != NULL ) m_pManager->SendNotify((CControlUI*)this, _T("return")); return S_OK; } } return m_pTwh->GetTextServices()->TxSendMessage(msg, wparam, lparam, plresult); } return S_FALSE; } IDropTarget* CRichEditUI::GetTxDropTarget() { IDropTarget *pdt = NULL; if( m_pTwh->GetTextServices()->TxGetDropTarget(&pdt) == NOERROR ) return pdt; return NULL; } bool CRichEditUI::OnTxViewChanged() { return true; } void CRichEditUI::OnTxNotify(DWORD iNotify, void *pv) { } // ¶àÐзÇrich¸ñʽµÄricheditÓÐÒ»¸ö¹ö¶¯Ìõbug£¬ÔÚ×îºóÒ»ÐÐÊÇ¿ÕÐÐʱ£¬LineDownºÍSetScrollPosÎÞ·¨¹ö¶¯µ½×îºó // ÒýÈëiPos¾ÍÊÇΪÁËÐÞÕýÕâ¸öbug void CRichEditUI::SetScrollPos(SIZE szPos) { int cx = 0; int cy = 0; if( m_pVerticalScrollBar && m_pVerticalScrollBar->IsVisible() ) { int iLastScrollPos = m_pVerticalScrollBar->GetScrollPos(); m_pVerticalScrollBar->SetScrollPos(szPos.cy); cy = m_pVerticalScrollBar->GetScrollPos() - iLastScrollPos; } if( m_pHorizontalScrollBar && m_pHorizontalScrollBar->IsVisible() ) { int iLastScrollPos = m_pHorizontalScrollBar->GetScrollPos(); m_pHorizontalScrollBar->SetScrollPos(szPos.cx); cx = m_pHorizontalScrollBar->GetScrollPos() - iLastScrollPos; } if( cy != 0 ) { int iPos = 0; if( m_pTwh && !m_bRich && m_pVerticalScrollBar && m_pVerticalScrollBar->IsVisible() ) iPos = m_pVerticalScrollBar->GetScrollPos(); WPARAM wParam = MAKEWPARAM(SB_THUMBPOSITION, m_pVerticalScrollBar->GetScrollPos()); TxSendMessage(WM_VSCROLL, wParam, 0L, 0); if( m_pTwh && !m_bRich && m_pVerticalScrollBar && m_pVerticalScrollBar->IsVisible() ) { if( cy > 0 && m_pVerticalScrollBar->GetScrollPos() <= iPos ) m_pVerticalScrollBar->SetScrollPos(iPos); } } if( cx != 0 ) { WPARAM wParam = MAKEWPARAM(SB_THUMBPOSITION, m_pHorizontalScrollBar->GetScrollPos()); TxSendMessage(WM_HSCROLL, wParam, 0L, 0); } } void CRichEditUI::LineUp() { TxSendMessage(WM_VSCROLL, SB_LINEUP, 0L, 0); } void CRichEditUI::LineDown() { int iPos = 0; if( m_pTwh && !m_bRich && m_pVerticalScrollBar && m_pVerticalScrollBar->IsVisible() ) iPos = m_pVerticalScrollBar->GetScrollPos(); TxSendMessage(WM_VSCROLL, SB_LINEDOWN, 0L, 0); if( m_pTwh && !m_bRich && m_pVerticalScrollBar && m_pVerticalScrollBar->IsVisible() ) { if( m_pVerticalScrollBar->GetScrollPos() <= iPos ) m_pVerticalScrollBar->SetScrollPos(m_pVerticalScrollBar->GetScrollRange()); } } void CRichEditUI::PageUp() { TxSendMessage(WM_VSCROLL, SB_PAGEUP, 0L, 0); } void CRichEditUI::PageDown() { TxSendMessage(WM_VSCROLL, SB_PAGEDOWN, 0L, 0); } void CRichEditUI::HomeUp() { TxSendMessage(WM_VSCROLL, SB_TOP, 0L, 0); } void CRichEditUI::EndDown() { TxSendMessage(WM_VSCROLL, SB_BOTTOM, 0L, 0); } void CRichEditUI::LineLeft() { TxSendMessage(WM_HSCROLL, SB_LINELEFT, 0L, 0); } void CRichEditUI::LineRight() { TxSendMessage(WM_HSCROLL, SB_LINERIGHT, 0L, 0); } void CRichEditUI::PageLeft() { TxSendMessage(WM_HSCROLL, SB_PAGELEFT, 0L, 0); } void CRichEditUI::PageRight() { TxSendMessage(WM_HSCROLL, SB_PAGERIGHT, 0L, 0); } void CRichEditUI::HomeLeft() { TxSendMessage(WM_HSCROLL, SB_LEFT, 0L, 0); } void CRichEditUI::EndRight() { TxSendMessage(WM_HSCROLL, SB_RIGHT, 0L, 0); } void CRichEditUI::DoEvent(TEventUI& event) { if( !IsMouseEnabled() && event.Type > UIEVENT__MOUSEBEGIN && event.Type < UIEVENT__MOUSEEND ) { if( m_pParent != NULL ) m_pParent->DoEvent(event); else CControlUI::DoEvent(event); return; } if( event.Type == UIEVENT_SETCURSOR && IsEnabled() ) { if( m_pTwh && m_pTwh->DoSetCursor(NULL, &event.ptMouse) ) { return; } } if( event.Type == UIEVENT_SETFOCUS ) { if( m_pTwh ) { m_pTwh->OnTxInPlaceActivate(NULL); m_pTwh->GetTextServices()->TxSendMessage(WM_SETFOCUS, 0, 0, 0); } } if( event.Type == UIEVENT_KILLFOCUS ) { if( m_pTwh ) { m_pTwh->OnTxInPlaceActivate(NULL); m_pTwh->GetTextServices()->TxSendMessage(WM_KILLFOCUS, 0, 0, 0); } } if( event.Type == UIEVENT_TIMER ) { if( m_pTwh ) { m_pTwh->GetTextServices()->TxSendMessage(WM_TIMER, event.wParam, event.lParam, 0); } } if( event.Type == UIEVENT_SCROLLWHEEL ) { if( (event.wKeyState & MK_CONTROL) != 0 ) { return; } } if( event.Type == UIEVENT_BUTTONDOWN || event.Type == UIEVENT_DBLCLICK ) { return; } if( event.Type == UIEVENT_MOUSEMOVE ) { return; } if( event.Type == UIEVENT_BUTTONUP ) { return; } if( event.Type == UIEVENT_MOUSEENTER ) { return; } if( event.Type == UIEVENT_MOUSELEAVE ) { return; } if( event.Type > UIEVENT__KEYBEGIN && event.Type < UIEVENT__KEYEND ) { return; } CContainerUI::DoEvent(event); } SIZE CRichEditUI::EstimateSize(SIZE szAvailable) { //return CSize(m_rcItem); // ÕâÖÖ·½Ê½ÔÚµÚÒ»´ÎÉèÖôóС֮ºó¾Í´óС²»±äÁË return CContainerUI::EstimateSize(szAvailable); } void CRichEditUI::SetPos(RECT rc) { CControlUI::SetPos(rc); rc = m_rcItem; rc.left += m_rcInset.left; rc.top += m_rcInset.top; rc.right -= m_rcInset.right; rc.bottom -= m_rcInset.bottom; bool bVScrollBarVisiable = false; if( m_pVerticalScrollBar && m_pVerticalScrollBar->IsVisible() ) { bVScrollBarVisiable = true; rc.right -= m_pVerticalScrollBar->GetFixedWidth(); } if( m_pHorizontalScrollBar && m_pHorizontalScrollBar->IsVisible() ) { rc.bottom -= m_pHorizontalScrollBar->GetFixedHeight(); } if( m_pTwh ) { m_pTwh->SetClientRect(&rc); if( bVScrollBarVisiable && (!m_pVerticalScrollBar->IsVisible() || m_bVScrollBarFixing) ) { LONG lWidth = rc.right - rc.left + m_pVerticalScrollBar->GetFixedWidth(); LONG lHeight = 0; SIZEL szExtent = { -1, -1 }; m_pTwh->GetTextServices()->TxGetNaturalSize( DVASPECT_CONTENT, GetManager()->GetPaintDC(), NULL, NULL, TXTNS_FITTOCONTENT, &szExtent, &lWidth, &lHeight); if( lHeight > rc.bottom - rc.top ) { m_pVerticalScrollBar->SetVisible(true); m_pVerticalScrollBar->SetScrollPos(0); m_bVScrollBarFixing = true; } else { if( m_bVScrollBarFixing ) { m_pVerticalScrollBar->SetVisible(false); m_bVScrollBarFixing = false; } } } } if( m_pVerticalScrollBar != NULL && m_pVerticalScrollBar->IsVisible() ) { RECT rcScrollBarPos = { rc.right, rc.top, rc.right + m_pVerticalScrollBar->GetFixedWidth(), rc.bottom}; m_pVerticalScrollBar->SetPos(rcScrollBarPos); } if( m_pHorizontalScrollBar != NULL && m_pHorizontalScrollBar->IsVisible() ) { RECT rcScrollBarPos = { rc.left, rc.bottom, rc.right, rc.bottom + m_pHorizontalScrollBar->GetFixedHeight()}; m_pHorizontalScrollBar->SetPos(rcScrollBarPos); } for( int it = 0; it < m_items.GetSize(); it++ ) { CControlUI* pControl = static_cast<CControlUI*>(m_items[it]); if( !pControl->IsVisible() ) continue; if( pControl->IsFloat() ) { SetFloatPos(it); } else { pControl->SetPos(rc); // ËùÓзÇfloat×ӿؼþ·Å´óµ½Õû¸ö¿Í»§Çø } } } void CRichEditUI::DoPaint(HDC hDC, const RECT& rcPaint) { RECT rcTemp = { 0 }; if( !::IntersectRect(&rcTemp, &rcPaint, &m_rcItem) ) return; CRenderClip clip; CRenderClip::GenerateClip(hDC, rcTemp, clip); CControlUI::DoPaint(hDC, rcPaint); if( m_pTwh ) { RECT rc; m_pTwh->GetControlRect(&rc); // Remember wparam is actually the hdc and lparam is the update // rect because this message has been preprocessed by the window. m_pTwh->GetTextServices()->TxDraw( DVASPECT_CONTENT, // Draw Aspect /*-1*/0, // Lindex NULL, // Info for drawing optimazation NULL, // target device information hDC, // Draw device HDC NULL, // Target device HDC (RECTL*)&rc, // Bounding client rectangle NULL, // Clipping rectangle for metafiles (RECT*)&rcPaint, // Update rectangle NULL, // Call back function NULL, // Call back parameter 0); // What view of the object if( m_bVScrollBarFixing ) { LONG lWidth = rc.right - rc.left + m_pVerticalScrollBar->GetFixedWidth(); LONG lHeight = 0; SIZEL szExtent = { -1, -1 }; m_pTwh->GetTextServices()->TxGetNaturalSize( DVASPECT_CONTENT, GetManager()->GetPaintDC(), NULL, NULL, TXTNS_FITTOCONTENT, &szExtent, &lWidth, &lHeight); if( lHeight <= rc.bottom - rc.top ) { NeedUpdate(); } } } if( m_items.GetSize() > 0 ) { RECT rc = m_rcItem; rc.left += m_rcInset.left; rc.top += m_rcInset.top; rc.right -= m_rcInset.right; rc.bottom -= m_rcInset.bottom; if( m_pVerticalScrollBar && m_pVerticalScrollBar->IsVisible() ) rc.right -= m_pVerticalScrollBar->GetFixedWidth(); if( m_pHorizontalScrollBar && m_pHorizontalScrollBar->IsVisible() ) rc.bottom -= m_pHorizontalScrollBar->GetFixedHeight(); if( !::IntersectRect(&rcTemp, &rcPaint, &rc) ) { for( int it = 0; it < m_items.GetSize(); it++ ) { CControlUI* pControl = static_cast<CControlUI*>(m_items[it]); if( !pControl->IsVisible() ) continue; if( !::IntersectRect(&rcTemp, &rcPaint, &pControl->GetPos()) ) continue; if( pControl ->IsFloat() ) { if( !::IntersectRect(&rcTemp, &m_rcItem, &pControl->GetPos()) ) continue; pControl->DoPaint(hDC, rcPaint); } } } else { CRenderClip childClip; CRenderClip::GenerateClip(hDC, rcTemp, childClip); for( int it = 0; it < m_items.GetSize(); it++ ) { CControlUI* pControl = static_cast<CControlUI*>(m_items[it]); if( !pControl->IsVisible() ) continue; if( !::IntersectRect(&rcTemp, &rcPaint, &pControl->GetPos()) ) continue; if( pControl ->IsFloat() ) { if( !::IntersectRect(&rcTemp, &m_rcItem, &pControl->GetPos()) ) continue; CRenderClip::UseOldClipBegin(hDC, childClip); pControl->DoPaint(hDC, rcPaint); CRenderClip::UseOldClipEnd(hDC, childClip); } else { if( !::IntersectRect(&rcTemp, &rc, &pControl->GetPos()) ) continue; pControl->DoPaint(hDC, rcPaint); } } } } if( m_pVerticalScrollBar != NULL && m_pVerticalScrollBar->IsVisible() ) { if( ::IntersectRect(&rcTemp, &rcPaint, &m_pVerticalScrollBar->GetPos()) ) { m_pVerticalScrollBar->DoPaint(hDC, rcPaint); } } if( m_pHorizontalScrollBar != NULL && m_pHorizontalScrollBar->IsVisible() ) { if( ::IntersectRect(&rcTemp, &rcPaint, &m_pHorizontalScrollBar->GetPos()) ) { m_pHorizontalScrollBar->DoPaint(hDC, rcPaint); } } } void CRichEditUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue) { if( _tcscmp(pstrName, _T("vscrollbar")) == 0 ) { if( _tcscmp(pstrValue, _T("true")) == 0 ) m_lTwhStyle |= ES_DISABLENOSCROLL | WS_VSCROLL; } if( _tcscmp(pstrName, _T("autovscroll")) == 0 ) { if( _tcscmp(pstrValue, _T("true")) == 0 ) m_lTwhStyle |= ES_AUTOVSCROLL; } else if( _tcscmp(pstrName, _T("hscrollbar")) == 0 ) { if( _tcscmp(pstrValue, _T("true")) == 0 ) m_lTwhStyle |= ES_DISABLENOSCROLL | WS_HSCROLL; } if( _tcscmp(pstrName, _T("autohscroll")) == 0 ) { if( _tcscmp(pstrValue, _T("true")) == 0 ) m_lTwhStyle |= ES_AUTOHSCROLL; } else if( _tcscmp(pstrName, _T("wanttab")) == 0 ) { SetWantTab(_tcscmp(pstrValue, _T("true")) == 0); } else if( _tcscmp(pstrName, _T("wantreturn")) == 0 ) { SetWantReturn(_tcscmp(pstrValue, _T("true")) == 0); } else if( _tcscmp(pstrName, _T("wantctrlreturn")) == 0 ) { SetWantCtrlReturn(_tcscmp(pstrValue, _T("true")) == 0); } else if( _tcscmp(pstrName, _T("rich")) == 0 ) { SetRich(_tcscmp(pstrValue, _T("true")) == 0); } else if( _tcscmp(pstrName, _T("multiline")) == 0 ) { if( _tcscmp(pstrValue, _T("false")) == 0 ) m_lTwhStyle &= ~ES_MULTILINE; } else if( _tcscmp(pstrName, _T("readonly")) == 0 ) { if( _tcscmp(pstrValue, _T("true")) == 0 ) { m_lTwhStyle |= ES_READONLY; m_bReadOnly = true; } } else if( _tcscmp(pstrName, _T("password")) == 0 ) { if( _tcscmp(pstrValue, _T("true")) == 0 ) m_lTwhStyle |= ES_PASSWORD; } else if( _tcscmp(pstrName, _T("align")) == 0 ) { if( _tcsstr(pstrValue, _T("left")) != NULL ) { m_lTwhStyle &= ~(ES_CENTER | ES_RIGHT); m_lTwhStyle |= ES_LEFT; } if( _tcsstr(pstrValue, _T("center")) != NULL ) { m_lTwhStyle &= ~(ES_LEFT | ES_RIGHT); m_lTwhStyle |= ES_CENTER; } if( _tcsstr(pstrValue, _T("right")) != NULL ) { m_lTwhStyle &= ~(ES_LEFT | ES_CENTER); m_lTwhStyle |= ES_RIGHT; } } else if( _tcscmp(pstrName, _T("font")) == 0 ) SetFont(_ttoi(pstrValue)); else if( _tcscmp(pstrName, _T("textcolor")) == 0 ) { while( *pstrValue > _T('\0') && *pstrValue <= _T(' ') ) pstrValue = ::CharNext(pstrValue); if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue); LPTSTR pstr = NULL; DWORD clrColor = _tcstoul(pstrValue, &pstr, 16); SetTextColor(clrColor); } else CContainerUI::SetAttribute(pstrName, pstrValue); } LRESULT CRichEditUI::MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, bool& bHandled) { if( !IsVisible() || !IsEnabled() ) return 0; if( !IsMouseEnabled() && uMsg >= WM_MOUSEFIRST && uMsg <= WM_MOUSELAST ) return 0; if( uMsg == WM_MOUSEWHEEL && (LOWORD(wParam) & MK_CONTROL) == 0 ) return 0; bool bWasHandled = true; if( (uMsg >= WM_MOUSEFIRST && uMsg <= WM_MOUSELAST) || uMsg == WM_SETCURSOR ) { if( !m_pTwh->IsCaptured() ) { switch (uMsg) { case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_LBUTTONDBLCLK: case WM_RBUTTONDOWN: case WM_RBUTTONUP: { POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; CControlUI* pHover = GetManager()->FindControl(pt); if(pHover != this) { bWasHandled = false; return 0; } } break; } } // Mouse message only go when captured or inside rect DWORD dwHitResult = m_pTwh->IsCaptured() ? HITRESULT_HIT : HITRESULT_OUTSIDE; if( dwHitResult == HITRESULT_OUTSIDE ) { RECT rc; m_pTwh->GetControlRect(&rc); POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; if( uMsg == WM_MOUSEWHEEL ) ::ScreenToClient(GetManager()->GetPaintWindow(), &pt); if( ::PtInRect(&rc, pt) && !GetManager()->IsCaptured() ) dwHitResult = HITRESULT_HIT; } if( dwHitResult != HITRESULT_HIT ) return 0; if( uMsg == WM_SETCURSOR ) bWasHandled = false; else if( uMsg == WM_LBUTTONDOWN || uMsg == WM_LBUTTONDBLCLK || uMsg == WM_RBUTTONDOWN ) { SetFocus(); } } #ifdef _UNICODE else if( uMsg >= WM_KEYFIRST && uMsg <= WM_KEYLAST ) { #else else if( (uMsg >= WM_KEYFIRST && uMsg <= WM_KEYLAST) || uMsg == WM_CHAR || uMsg == WM_IME_CHAR ) { #endif if( !IsFocused() ) return 0; } else if( uMsg == WM_CONTEXTMENU ) { POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; ::ScreenToClient(GetManager()->GetPaintWindow(), &pt); CControlUI* pHover = GetManager()->FindControl(pt); if(pHover != this) { bWasHandled = false; return 0; } } else { switch( uMsg ) { case WM_HELP: bWasHandled = false; break; default: return 0; } } LRESULT lResult = 0; HRESULT Hr = TxSendMessage(uMsg, wParam, lParam, &lResult); if( Hr == S_OK ) bHandled = bWasHandled; else if( (uMsg >= WM_KEYFIRST && uMsg <= WM_KEYLAST) || uMsg == WM_CHAR || uMsg == WM_IME_CHAR ) bHandled = bWasHandled; else if( uMsg >= WM_MOUSEFIRST && uMsg <= WM_MOUSELAST ) { if( m_pTwh->IsCaptured() ) bHandled = bWasHandled; } return lResult; } } // namespace DirectUICore
zxlooong/directui
DirectUICore/UIRichEdit.cpp
C++
gpl-2.0
58,623
<?php /** * Element: Version * Displays the version check * * @package NoNumber Framework * @version 14.6.9 * * @author Peter van Westen <peter@nonumber.nl> * @link http://www.nonumber.nl * @copyright Copyright © 2014 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ defined('_JEXEC') or die; class JFormFieldNN_Version extends JFormField { public $type = 'Version'; private $params = null; protected function getLabel() { return ''; } protected function getInput() { $this->params = $this->element->attributes(); $extension = $this->get('extension'); $xml = $this->get('xml'); if (!$xml && $this->form->getValue('element')) { if ($this->form->getValue('folder')) { $xml = 'plugins/' . $this->form->getValue('folder') . '/' . $this->form->getValue('element') . '/' . $this->form->getValue('element') . '.xml'; } else { $xml = 'administrator/modules/' . $this->form->getValue('element') . '/' . $this->form->getValue('element') . '.xml'; } if (!JFile::exists(JPATH_SITE . '/' . $xml)) { return ''; } } if (!strlen($extension) || !strlen($xml)) { return ''; } $authorise = JFactory::getUser()->authorise('core.manage', 'com_installer'); if (!$authorise) { return ''; } // Import library dependencies require_once JPATH_PLUGINS . '/system/nnframework/helpers/versions.php'; $versions = NNVersions::getInstance(); return $versions->getMessage($extension, $xml); } private function get($val, $default = '') { return (isset($this->params[$val]) && (string) $this->params[$val] != '') ? (string) $this->params[$val] : $default; } }
bundocba/unitedworld
plugins/system/nnframework/fields/version.php
PHP
gpl-2.0
1,735
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "math.h" #include "stdlib.h" #include "string.h" #include "fix_pour.h" #include "atom.h" #include "atom_vec.h" #include "force.h" #include "update.h" #include "comm.h" #include "modify.h" #include "fix_gravity.h" #include "domain.h" #include "region.h" #include "region_block.h" #include "region_cylinder.h" #include "random_park.h" #include "memory.h" #include "error.h" using namespace LAMMPS_NS; #define EPSILON 0.001 /* ---------------------------------------------------------------------- */ FixPour::FixPour(LAMMPS *lmp, int narg, char **arg) : Fix(lmp, narg, arg) { if (narg < 6) error->all("Illegal fix pour command"); time_depend = 1; if (!atom->radius_flag || !atom->rmass_flag) error->all("Fix pour requires atom attributes radius, rmass"); // required args ninsert = atoi(arg[3]); ntype = atoi(arg[4]); seed = atoi(arg[5]); if (seed <= 0) error->all("Illegal fix pour command"); PI = 4.0*atan(1.0); // option defaults int iregion = -1; radius_lo = radius_hi = 0.5; density_lo = density_hi = 1.0; volfrac = 0.25; maxattempt = 50; rate = 0.0; vxlo = vxhi = vylo = vyhi = vy = vz = 0.0; // optional args int iarg = 6; while (iarg < narg) { if (strcmp(arg[iarg],"region") == 0) { if (iarg+2 > narg) error->all("Illegal fix pour command"); iregion = domain->find_region(arg[iarg+1]); if (iregion == -1) error->all("Fix pour region ID does not exist"); iarg += 2; } else if (strcmp(arg[iarg],"diam") == 0) { if (iarg+4 > narg) error->all("Illegal fix pour command"); if(strcmp("uniform",arg[iarg+1])==0) radius_ran_style = RAN_STYLE_UNIFORM; else if(strcmp("gaussian",arg[iarg+1])==0) {error->all("Random style gaussian deactivated for radius in fix pour."); radius_ran_style = RAN_STYLE_GAUSSIAN;} else if(strcmp("lognormal",arg[iarg+1])==0) radius_ran_style = RAN_STYLE_LOGNORMAL; else if(strcmp("discrete",arg[iarg+1])==0) radius_ran_style = RAN_STYLE_DISCRETE; else error->all("Illegal fix pour command: Unknown random style"); radius_lo = 0.5 * atof(arg[iarg+2]); radius_hi = 0.5 * atof(arg[iarg+3]); iarg += 4; } else if (strcmp(arg[iarg],"dens") == 0) { if (iarg+4 > narg) error->all("Illegal fix pour command"); if(strcmp("uniform",arg[iarg+1])==0) density_ran_style = RAN_STYLE_UNIFORM; else if(strcmp("gaussian",arg[iarg+1])==0) density_ran_style = RAN_STYLE_GAUSSIAN; else if(strcmp("lognormal",arg[iarg+1])==0) density_ran_style = RAN_STYLE_LOGNORMAL; else if(strcmp("discrete",arg[iarg+1])==0) density_ran_style = RAN_STYLE_DISCRETE; else error->all("Illegal fix pour command: Unknown random style"); density_lo = atof(arg[iarg+2]); density_hi = atof(arg[iarg+3]); iarg += 4; } else if (strcmp(arg[iarg],"vol") == 0) { if (iarg+3 > narg) error->all("Illegal fix pour command"); volfrac = atof(arg[iarg+1]); maxattempt = atoi(arg[iarg+2]); iarg += 3; } else if (strcmp(arg[iarg],"rate") == 0) { if (iarg+2 > narg) error->all("Illegal fix pour command"); rate = atof(arg[iarg+1]); iarg += 2; } else if (strcmp(arg[iarg],"vel") == 0) { if (domain->dimension == 3) { if (iarg+7 > narg) error->all("Illegal fix pour command"); if(strcmp("uniform",arg[iarg+1])==0) vel_ran_style = RAN_STYLE_UNIFORM; else if(strcmp("gaussian",arg[iarg+1])==0) vel_ran_style = RAN_STYLE_GAUSSIAN; else if(strcmp("lognormal",arg[iarg+1])==0) vel_ran_style = RAN_STYLE_LOGNORMAL; else if(strcmp("discrete",arg[iarg+1])==0) vel_ran_style = RAN_STYLE_DISCRETE; else error->all("Illegal fix pour command: Unknown random style"); vxlo = atof(arg[iarg+2]); vxhi = atof(arg[iarg+3]); vylo = atof(arg[iarg+4]); vyhi = atof(arg[iarg+5]); vz = atof(arg[iarg+6]); if(vz>0.) error->all("fix pour: z-velocity must not not be <0."); iarg += 7; } else { if (iarg+5 > narg) error->all("Illegal fix pour command"); if(strcmp("uniform",arg[iarg+1])==0) vel_ran_style = RAN_STYLE_UNIFORM; else if(strcmp("gaussian",arg[iarg+1])==0) vel_ran_style = RAN_STYLE_GAUSSIAN; else if(strcmp("lognormal",arg[iarg+1])==0) vel_ran_style = RAN_STYLE_LOGNORMAL; else if(strcmp("discrete",arg[iarg+1])==0) vel_ran_style = RAN_STYLE_DISCRETE; else error->all("Illegal fix pour command: Unknown random style"); vxlo = atof(arg[iarg+2]); vxhi = atof(arg[iarg+3]); vy = atof(arg[iarg+4]); vz = 0.0; iarg += 5; } } else if (strcmp(arg[iarg],"template") == 0) iarg+=2; else error->all("Illegal fix pour command"); } // error checks on region and its extent being inside simulation box if (iregion == -1) error->all("Must specify a region in fix pour"); if (domain->regions[iregion]->bboxflag == 0) error->all("Fix pour region does not support a bounding box"); if (domain->regions[iregion]->dynamic_check()) error->all("Fix pour region cannot be dynamic"); if (strcmp(domain->regions[iregion]->style,"block") == 0) { region_style = 1; xlo = ((RegBlock *) domain->regions[iregion])->xlo; xhi = ((RegBlock *) domain->regions[iregion])->xhi; ylo = ((RegBlock *) domain->regions[iregion])->ylo; yhi = ((RegBlock *) domain->regions[iregion])->yhi; zlo = ((RegBlock *) domain->regions[iregion])->zlo; zhi = ((RegBlock *) domain->regions[iregion])->zhi; if (xlo < domain->boxlo[0] || xhi > domain->boxhi[0] || ylo < domain->boxlo[1] || yhi > domain->boxhi[1] || zlo < domain->boxlo[2] || zhi > domain->boxhi[2]) error->all("Insertion region extends outside simulation box"); } else if (strcmp(domain->regions[iregion]->style,"cylinder") == 0) { region_style = 2; char axis = ((RegCylinder *) domain->regions[iregion])->axis; xc = ((RegCylinder *) domain->regions[iregion])->c1; yc = ((RegCylinder *) domain->regions[iregion])->c2; rc = ((RegCylinder *) domain->regions[iregion])->radius; zlo = ((RegCylinder *) domain->regions[iregion])->lo; zhi = ((RegCylinder *) domain->regions[iregion])->hi; if (axis != 'z') error->all("Must use a z-axis cylinder with fix pour"); if (xc-rc < domain->boxlo[0] || xc+rc > domain->boxhi[0] || yc-rc < domain->boxlo[1] || yc+rc > domain->boxhi[1] || zlo < domain->boxlo[2] || zhi > domain->boxhi[2]) error->all("Insertion region extends outside simulation box"); } else error->all("Must use a block or cylinder region with fix pour"); if (region_style == 2 && domain->dimension == 2) error->all("Must use a block region with fix pour for 2d simulations"); // random number generator, same for all procs random = new RanPark(lmp,seed); // allgather arrays MPI_Comm_rank(world,&me); MPI_Comm_size(world,&nprocs); recvcounts = new int[nprocs]; displs = new int[nprocs]; if(strcmp(this->style,"pour")==0) { calc_nfreq(); force_reneighbor = 1; next_reneighbor = update->ntimestep + 1; nfirst = next_reneighbor; ninserted = 0; calc_nper(); } } /* ---------------------------------------------------------------------- */ void FixPour::calc_nfreq() { // nfreq = timesteps between insertions // should be time for a particle to fall from top of insertion region // to bottom, taking into account that the region may be moving // 1st insertion on next timestep double v_relative,delta; //double g = 1.; check_gravity(); double g = grav; //fprintf(screen,"grav=%f\n",grav); grav=-grav; if (domain->dimension == 3) { v_relative = - sqrt(vz*vz + 2.0*g*(shift_randompos(expectancy(radius_hi,radius_lo,radius_ran_style)))) - rate; delta = fmax(shift_randompos(expectancy(radius_hi,radius_lo,radius_ran_style)), zhi - zlo -shift_randompos(expectancy(radius_hi,radius_lo,radius_ran_style))) ; } else { v_relative = vy - rate; delta = yhi - ylo; } double t = (-v_relative - sqrt(v_relative*v_relative - 2.0*grav*delta)) / grav; nfreq = static_cast<int> (t/update->dt + 0.5); } /* ---------------------------------------------------------------------- */ void FixPour::calc_nper() { // nper = # to insert each time // depends on specified volume fraction // volume = volume of insertion region // volume_one = average volume of inserted particle // in 3d, insure dy >= 1, for quasi-2d simulations double volume,volume_one; if (domain->dimension == 3) { if (region_style == 1) { double dy = yhi - ylo; if (dy < 1.0) dy = 1.0; volume = (xhi-xlo) * dy * (zhi-zlo); } else volume = PI*rc*rc * (zhi-zlo); volume_one = volume_expectancy(radius_lo,radius_hi,radius_ran_style,3); } else //2D { volume = (xhi-xlo) * (yhi-ylo); volume_one = volume_expectancy(radius_lo,radius_hi,radius_ran_style,2); } nper = static_cast<int> (volfrac*volume/volume_one); if (nper==0)error->all("Insertion rate too low"); int nfinal = update->ntimestep + 1 + (ninsert-1)/nper * nfreq; // print stats if (me == 0) { if (screen) fprintf(screen, "Particle insertion: %d every %d steps, %d by step %d\n", nper,nfreq,ninsert,nfinal); if (logfile) fprintf(logfile, "Particle insertion: %d every %d steps, %d by step %d\n", nper,nfreq,ninsert,nfinal); } } /* ---------------------------------------------------------------------- */ FixPour::~FixPour() { delete random; delete [] recvcounts; delete [] displs; } /* ---------------------------------------------------------------------- */ int FixPour::setmask() { int mask = 0; mask |= PRE_EXCHANGE; return mask; } /* ---------------------------------------------------------------------- */ void FixPour::check_gravity() { // insure gravity fix exists // for 3d must point in -z, for 2d must point in -y // else insertion cannot work int ifix; for (ifix = 0; ifix < modify->nfix; ifix++) if (strcmp(modify->fix[ifix]->style,"gravity") == 0) break; if (ifix == modify->nfix) error->all("Must use fix gravity before using fix pour"); double xgrav = ((FixGravity *) modify->fix[ifix])->xgrav*((FixGravity *) modify->fix[ifix])->magnitude; double ygrav = ((FixGravity *) modify->fix[ifix])->ygrav*((FixGravity *) modify->fix[ifix])->magnitude; double zgrav = ((FixGravity *) modify->fix[ifix])->zgrav*((FixGravity *) modify->fix[ifix])->magnitude; if (domain->dimension == 3) { if (fabs(xgrav) > EPSILON || fabs(ygrav) > EPSILON || zgrav > EPSILON) error->all("Gravity must point in -z to use with fix pour in 3d"); grav=-zgrav; } else { if (fabs(xgrav) > EPSILON || ygrav > EPSILON || fabs(zgrav) > EPSILON) error->all("Gravity must point in -y to use with fix pour in 2d"); grav=-ygrav; } } /* ---------------------------------------------------------------------- */ void FixPour::init() { if (domain->triclinic) error->all("Cannot use fix pour with triclinic box"); check_gravity(); init_substyle(); } /* ---------------------------------------------------------------------- */ double FixPour::max_rad(int type) { if (type!=ntype) return 0.; if (radius_ran_style==RAN_STYLE_UNIFORM) { return radius_hi; } else if (radius_ran_style==RAN_STYLE_GAUSSIAN) { return radius_lo+3.*radius_hi; } else if (radius_ran_style==RAN_STYLE_LOGNORMAL) { error->all("Lognormal expectancy not implemented yet"); } else if (radius_ran_style==RAN_STYLE_DISCRETE) { error->all("Discrete expectancy not implemented yet"); } return 0.; } /* ---------------------------------------------------------------------- perform particle insertion ------------------------------------------------------------------------- */ void FixPour::pre_exchange() { int i; // just return if should not be called on this timestep if (next_reneighbor != update->ntimestep) return; // nnew = # to insert this timestep int nnew = nper; if (ninserted + nnew > ninsert) nnew = ninsert - ninserted; // lo/hi current = z (or y) bounds of insertion region this timestep if (domain->dimension == 3) { lo_current = zlo + (update->ntimestep - nfirst) * update->dt * rate; hi_current = zhi + (update->ntimestep - nfirst) * update->dt * rate; } else { lo_current = ylo + (update->ntimestep - nfirst) * update->dt * rate; hi_current = yhi + (update->ntimestep - nfirst) * update->dt * rate; } // ncount = # of my atoms that overlap the insertion region // nprevious = total of ncount across all procs int ncount = 0; for (i = 0; i < atom->nlocal; i++) if (overlap(i)) ncount++; int nprevious; MPI_Allreduce(&ncount,&nprevious,1,MPI_INT,MPI_SUM,world); // xmine is for my atoms // xnear is for atoms from all procs + atoms to be inserted double **xmine = memory->create_2d_double_array(ncount,5,"fix_pour:xmine"); double **xnear = memory->create_2d_double_array(nprevious+nnew*particles_per_insertion(),5,"fix_pour:xnear"); int nnear = nprevious; // setup for allgatherv int n = 5*ncount; MPI_Allgather(&n,1,MPI_INT,recvcounts,1,MPI_INT,world); displs[0] = 0; for (int iproc = 1; iproc < nprocs; iproc++) displs[iproc] = displs[iproc-1] + recvcounts[iproc-1]; // load up xmine array double **x = atom->x; double *radius = atom->radius; ncount = 0; for (i = 0; i < atom->nlocal; i++) if (overlap(i)) { xmine[ncount][0] = x[i][0]; xmine[ncount][1] = x[i][1]; xmine[ncount][2] = x[i][2]; xmine[ncount][3] = radius[i]; ncount++; } // perform allgatherv to acquire list of nearby particles on all procs double *ptr = NULL; if (ncount) ptr = xmine[0]; MPI_Allgatherv(ptr,5*ncount,MPI_DOUBLE, xnear[0],recvcounts,displs,MPI_DOUBLE,world); // insert new atoms into xnear list, one by one // check against all nearby atoms and previously inserted ones // if there is an overlap then try again at other z (3d) or y (2d) coord // else insert by adding to xnear list // max = maximum # of insertion attempts for all particles // h = height, biased to give uniform distribution in time of insertion int success; double coord[3],radtmp,rn,h; int attempt = 0; int max = nnew * maxattempt; int ntotal = nprevious+nnew; while (nnear < ntotal) { radtmp = rand_pour(radius_lo,radius_hi,radius_ran_style); success = 0; while (attempt < max) { rn = random->uniform(); h = (hi_current-shift_randompos(radtmp)) - rn * (hi_current-lo_current-2.*shift_randompos(radtmp)); attempt++; xyz_random(h,coord,radtmp); for (i = 0; i < nnear; i++) { if(overlaps_xnear_i(coord,radtmp,xnear,i)) break; } if (i == nnear) { success = 1; break; } } if (success) { nnear=insert_in_xnear(xnear,nnear,coord,radtmp); } else break; } // warn if not all insertions were performed ninserted += nnear-nprevious; if (nnear - nprevious < nnew && me == 0) error->warning("Less insertions than requested"); // check if new atom is in my sub-box or above it if I'm highest proc // if so, add to my list via create_atom() // initialize info about the atom // type, diameter, density set from fix parameters // group mask set to "all" plus fix group // z velocity set to what velocity would be if particle // had fallen from top of insertion region // this gives continuous stream of atoms // set npartner for new atom to 0 (assume not touching any others) AtomVec *avec = atom->avec; int j,m,flag; double denstmp,vxtmp,vytmp,vztmp; double g = grav; //double g = 1.; //originally double *sublo = domain->sublo; double *subhi = domain->subhi; int b_id; int nfix = modify->nfix; Fix **fix = modify->fix; for (i = nprevious; i < nnear; i++) { coord[0] = xnear[i][0]; coord[1] = xnear[i][1]; coord[2] = xnear[i][2]; radtmp = xnear[i][3]; b_id = static_cast<int>(xnear[i][4]); denstmp = rand_pour(density_lo,density_hi,density_ran_style)*density_scaling(); calc_insert_velocities(i,g,xnear,vxtmp,vytmp,vztmp); flag = 0; if (coord[0] >= sublo[0] && coord[0] < subhi[0] && coord[1] >= sublo[1] && coord[1] < subhi[1] && coord[2] >= sublo[2] && coord[2] < subhi[2]) flag = 1; else if (domain->dimension == 3 && coord[2] >= domain->boxhi[2] && comm->myloc[2] == comm->procgrid[2]-1 && coord[0] >= sublo[0] && coord[0] < subhi[0] && coord[1] >= sublo[1] && coord[1] < subhi[1]) flag = 1; else if (domain->dimension == 2 && coord[1] >= domain->boxhi[1] && comm->myloc[1] == comm->procgrid[1]-1 && coord[0] >= sublo[0] && coord[0] < subhi[0]) flag = 1; if (flag) { avec->create_atom(ntype,coord); m = atom->nlocal - 1; atom->type[m] = ntype; atom->radius[m] = radtmp; atom->density[m] = denstmp; atom->rmass[m] = 4.0*PI/3.0 * radtmp*radtmp*radtmp * denstmp; atom->mask[m] = 1 | groupbit; atom->v[m][0] = vxtmp; atom->v[m][1] = vytmp; atom->v[m][2] = vztmp; for (j = 0; j < nfix; j++) if (fix[j]->create_attribute) fix[j]->set_arrays(m); set_body_props(i,m,coord,denstmp,radtmp,vxtmp,vytmp,vztmp,b_id); } } // set tag # of new particles beyond all previous atoms // reset global natoms // if global map exists, reset it now instead of waiting for comm // since deleting atoms messes up ghosts if (atom->tag_enable) { atom->tag_extend(); atom->natoms += nnear - nprevious; if (atom->map_style) { atom->nghost = 0; atom->map_init(); atom->map_set(); } } finalize_insertion(); // free local memory memory->destroy_2d_double_array(xmine); memory->destroy_2d_double_array(xnear); // next timestep to insert if (ninserted < ninsert) next_reneighbor += nfreq; else next_reneighbor = 0; } /* ---------------------------------------------------------------------- insert particle in xnear list ------------------------------------------------------------------------- */ inline int FixPour::insert_in_xnear(double **xnear,int nnear,double *coord,double radtmp) { xnear[nnear][0] = coord[0]; xnear[nnear][1] = coord[1]; xnear[nnear][2] = coord[2]; xnear[nnear][3] = radtmp; xnear[nnear][4] = 0.; nnear++; return nnear; } /* ---------------------------------------------------------------------- check if particle inserted at coord would overlap particle xnear[i] ------------------------------------------------------------------------- */ inline bool FixPour::overlaps_xnear_i(double *coord,double radtmp,double **xnear,int i) { double delx,dely,delz,rsq,radsum; delx = coord[0] - xnear[i][0]; dely = coord[1] - xnear[i][1]; delz = coord[2] - xnear[i][2]; rsq = delx*delx + dely*dely + delz*delz; radsum = radtmp + xnear[i][3]; if (rsq <= radsum*radsum) return true; else return false; } /* ---------------------------------------------------------------------- how many particles are added to the xnear list in insert_in_xnear() ------------------------------------------------------------------------- */ inline int FixPour::particles_per_insertion() { return 1; } /* ---------------------------------------------------------------------- calculate inlet velocity of particle ------------------------------------------------------------------------- */ inline void FixPour::calc_insert_velocities(int i,double g,double **xnear,double &vxtmp,double &vytmp,double &vztmp) { if (domain->dimension == 3) { vxtmp = rand_pour(vxlo,vxhi,vel_ran_style); vytmp = rand_pour(vylo,vyhi,vel_ran_style); //vztmp = vz - sqrt(2.0*g*(hi_current-xnear[i][2])); vztmp = - sqrt(vz*vz + 2.0*g*(hi_current-xnear[i][2])); } else { vxtmp = rand_pour(vxlo,vxhi,vel_ran_style); vytmp = vy - sqrt(2.0*g*(hi_current-xnear[i][1])); vztmp = 0.0; } } /* ---------------------------------------------------------------------- check if particle i could overlap with a particle inserted into region return 1 if yes, 0 if no use maximum diameter for inserted particle ------------------------------------------------------------------------- */ int FixPour::overlap(int i) { double delta = radius_hi + atom->radius[i]; double **x = atom->x; if (domain->dimension == 3) { if (region_style == 1) { if (x[i][0] < xlo-delta || x[i][0] > xhi+delta || x[i][1] < ylo-delta || x[i][1] > yhi+delta || x[i][2] < lo_current-delta || x[i][2] > hi_current+delta) return 0; } else { if (x[i][2] < lo_current-delta || x[i][2] > hi_current+delta) return 0; double delx = x[i][0] - xc; double dely = x[i][1] - yc; double rsq = delx*delx + dely*dely; double r = rc + delta; if (rsq > r*r) return 0; } } else { if (x[i][0] < xlo-delta || x[i][0] > xhi+delta || x[i][1] < lo_current-delta || x[i][1] > hi_current+delta) return 0; } return 1; } /* ---------------------------------------------------------------------- */ double FixPour::rand_pour(double param1, double param2, int style) { if (style==RAN_STYLE_UNIFORM) { return param1 + random->uniform() * (param2-param1); } else if (style==RAN_STYLE_GAUSSIAN) { return param2 * random->gaussian() + param1; } else if (style==RAN_STYLE_LOGNORMAL) { error->all("Lognormal random not implemented yet"); } else if (style==RAN_STYLE_DISCRETE) { error->all("Discrete random not implemented yet"); } } /* ---------------------------------------------------------------------- */ //uniform: param 1 = low param 2 = high //gaussian: param 1 = mu param 2 = sigma double FixPour::expectancy(double param1, double param2, int style) { if (style==RAN_STYLE_UNIFORM) { return (param2+param1)/2.; } else if (style==RAN_STYLE_GAUSSIAN) { return param1; } else if (style==RAN_STYLE_LOGNORMAL) { error->all("Lognormal expectancy not implemented yet"); } else if (style==RAN_STYLE_DISCRETE) { error->all("Discrete expectancy not implemented yet"); } return 0.; } /* ---------------------------------------------------------------------- */ //uniform: param 1 = low param 2 = high //gaussian: param 1 = mu param 2 = sigma double FixPour::volume_expectancy(double param_1, double param_2, int style,int dim) { if (style==RAN_STYLE_UNIFORM) { if(dim==3) //3D { if(param_2/param_1<0.9999) error->all("fix pour: radius_hi must be larger than radius_lo"); if(param_2/param_1<1.0002) return (4.*PI/3.* param_2*param_2*param_2); else return (PI/3.0 * (pow(param_2,4.)-pow(param_1,4.))/(param_2-param_1)); } else //2D { if(param_2/param_1<0.9999) error->all("fix pour: radius_hi must be larger than radius_lo"); if(param_2/param_1<1.0002) return (4.*PI* param_2*param_2); return (PI/3.0 * (pow(param_2,3.)-pow(param_1,3.))/(param_2-param_1)); } } else if (style==RAN_STYLE_GAUSSIAN) { if(dim==3) //3D return (4.*PI/3.*param_1*(param_1*param_1+3.*param_2*param_2)); else //2D return ( PI * (param_1*param_1 + param_2*param_2)); } else if (style==RAN_STYLE_LOGNORMAL) error->all("Lognormal expectancy not implemented yet"); else if (style==RAN_STYLE_DISCRETE) error->all("Discrete expectancy not implemented yet"); return 0.; } /* ---------------------------------------------------------------------- */ inline double FixPour::density_scaling() { return 1.; } /* ---------------------------------------------------------------------- */ inline double FixPour::shift_randompos(double rt) { return rt; } /* ---------------------------------------------------------------------- */ void FixPour::xyz_random(double h, double *coord,double rt) { if (domain->dimension == 3) { if (region_style == 1) { coord[0] = xlo+shift_randompos(rt) + random->uniform() * (xhi-xlo-2.*shift_randompos(rt)); coord[1] = ylo+shift_randompos(rt) + random->uniform() * (yhi-ylo-2.*shift_randompos(rt)); coord[2] = h; } else { double r1,r2; while (1) { r1 = random->uniform() - 0.5; r2 = random->uniform() - 0.5; if (r1*r1 + r2*r2 < 0.25) break; } coord[0] = xc + 2.0*r1*(rc-shift_randompos(rt)); coord[1] = yc + 2.0*r2*(rc-shift_randompos(rt)); coord[2] = h; } } else { coord[0] = xlo+shift_randompos(rt) + random->uniform() * (xhi-xlo-2.*shift_randompos(rt)); coord[1] = h; coord[2] = 0.0; } } /* ---------------------------------------------------------------------- */ void FixPour::reset_dt() { error->all("Cannot change timestep with fix pour"); }
nchong/ic_liggghts
src/fix_pour.cpp
C++
gpl-2.0
25,668
require 'rails_helper' module NetworkInterfacesDatatableHelper def iface2array(iface) [].tap do |column| column << iface.host.location.try(:lid) column << iface.host.name column << iface.ip.to_s column << iface.mac.to_s column << iface.if_description column << iface.lastseen.to_s column << iface.created_at.to_date.to_s column << " " # dummy for action links end end def link_helper(text, url) text end end RSpec.describe NetworkInterfacesDatatable, type: :model do include NetworkInterfacesDatatableHelper include_context "network_interface variables" let(:view_context) { double("ActionView::Base") } let(:ifaces) { NetworkInterface.left_outer_joins( host: [ :location ] )} let(:datatable) { NetworkInterfacesDatatable.new(ifaces, view_context) } before(:each) do allow(view_context).to receive(:params).and_return(myparams) allow(view_context).to receive_messages( edit_network_interface_path: "", network_interface_path: "", host_path: "", show_link: "", edit_link: "", delete_link: "", ) allow(view_context).to receive(:link_to).with('pc4.my.domain', any_args).and_return('pc4.my.domain') allow(view_context).to receive(:link_to).with('pc5.my.domain', any_args).and_return('pc5.my.domain') allow(view_context).to receive(:link_to).with('abc.other.domain', any_args).and_return('abc.other.domain') end describe "without search params, start:0, length:10" do let(:myparams) { ActiveSupport::HashWithIndifferentAccess.new( columns: {"0"=> {search: {value: ""}}}, order: {"0"=>{column: "1", dir: "asc"}}, start: "0", length: "10", search: {value: "", regex: "false"} )} subject { datatable.to_json } it { expect(datatable).to be_a_kind_of NetworkInterfacesDatatable } it { expect(parse_json(subject, "recordsTotal")).to eq(4) } it { expect(parse_json(subject, "recordsFiltered")).to eq(4) } it { expect(parse_json(subject, "data/0")).to eq(iface2array(if1_host3)) } it { expect(parse_json(subject, "data/1")).to eq(iface2array(if2_host3)) } end describe "without search params, start:2, length:2" do let(:myparams) { ActiveSupport::HashWithIndifferentAccess.new( columns: {"0"=> {search: {value: ""}}}, order: {"0"=>{column: "1", dir: "asc"}}, start: "2", length: "2", search: {value: "", regex: "false"} )} subject { datatable.to_json } it { expect(parse_json(subject, "recordsTotal")).to eq(4) } it { expect(parse_json(subject, "recordsFiltered")).to eq(4) } it { expect(parse_json(subject, "data/0")).to eq(iface2array(if_host1)) } it { expect(parse_json(subject, "data/1")).to eq(iface2array(if_host2)) } end describe "with search: bbelfas" do let(:myparams) { ActiveSupport::HashWithIndifferentAccess.new( order: {"0"=>{column: "1", dir: "asc"}}, start: "0", length: "10", "search"=> {"value"=>"bbelfas", regex: "false"} )} subject { datatable.to_json } it { expect(parse_json(subject, "recordsTotal")).to eq(4) } it { expect(parse_json(subject, "recordsFiltered")).to eq(1) } it { expect(parse_json(subject, "data/0")).to eq(iface2array(if_host1)) } end describe "with search:198.51.100.7" do let(:myparams) { ActiveSupport::HashWithIndifferentAccess.new( order: {"0"=>{column: "2", dir: "desc"}}, start: "0", length: "10", "search" => {"value" => "198.51.100.7", regex: "false"} )} subject { datatable.to_json } it { expect(parse_json(subject, "recordsTotal")).to eq(4) } it { expect(parse_json(subject, "recordsFiltered")).to eq(1) } it { expect(parse_json(subject, "data/0")).to eq(iface2array(if_host2)) } end end
swobspace/boskop
spec/datatables/network_interfaces_spec.rb
Ruby
gpl-2.0
3,823
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Win32; using ReviveThis.AddIn.WinSock.Entities; using ReviveThis.AddIn.WinSock.Enums; using ReviveThis.Enums; using ReviveThis.Interfaces; using ReviveThis.Structs; namespace ReviveThis.AddIn.WinSock { #region [10] WinSock Layered Service Provider / CheckOther10Item [Export(typeof (IDetectionAddIn))] public class LayeredServiceProvider : IDetectionAddIn { #region private #region consts private const string REGISTRY_PATH_PARAMETERS = @"System\CurrentControlSet\Services\WinSock2\Parameters"; private const string CURRENT_NAMESPACE_CATALOG = @"Current_NameSpace_Catalog"; private const string CURRENT_PROTOCOL_CATALOG = @"Current_Protocol_Catalog"; private const string NUM_CATALOG_ENTRIES = "Num_Catalog_Entries"; private const string NUM_CATALOG_ENTRIES64 = "Num_Catalog_Entries64"; private const string NAMESPACE_LIBRARY_PATH = "LibraryPath"; private const string PROTOCOL_PACKED_CATALOG_ITEM = "PackedCatalogItem"; #endregion #region Safe Layered Service Providers private static string[] _safeLayeredServiceProviders; private static IEnumerable<string> SafeLayeredServiceProviders { get { if (_safeLayeredServiceProviders != null && _safeLayeredServiceProviders.Any()) return _safeLayeredServiceProviders; return _safeLayeredServiceProviders = new[] { //new Tuple<string, string, string>(PartialFileName , Description , Company), //new Tuple<string, string, string>(@"A2antispamlsp.dll", "a-squared Anti-Spam", "Emsi Software GmbH"), @"A2antispamlsp.dll", @"Adlsp.dll", @"Agbfilt.dll", @"Antiyfilter.dll", @"Ao2lsp.dll", @"Aphish.dll", @"Asdns.dll", @"Aslsp.dll", @"Asnsp.dll", @"Avgfwafu.dll", @"Avsda.dll", @"Betsp.dll", @"Biolsp.dll", @"Bmi_lsp.dll", @"Caslsp.dll", @"Cavemlsp.dll", @"Cdnns.dll", @"Connwsp.dll", @"Cplsp.dll", @"Csesck32.dll", @"Cslsp.dll", @"Cssp.al", @"Ctxlsp.dll", @"Ctxnsp.dll", @"Cwhook.dll", @"Cwlsp.dll", @"Dcsws2.dll", @"Disksearchservicestub.dll", @"Drwebsp.dll", @"Drwhook.dll", @"Espsock2.dll", @"Farlsp.dll", @"Fbm.dll", @"Fbm_lsp.dll", @"Fortilsp.dll", @"Fslsp.dll", @"Fwcwsp.dll", @"Fwtunnellsp.dll", @"Gapsp.dll", @"Googledesktopnetwork1.dll", @"Hclsock5.dll", @"Iapplsp.dll", @"Iapp_lsp.dll", @"Ickgw32i.dll", @"Ictload.dll", @"Idmmbc.dll", @"Iga.dll", @"Imon.dll", @"Imslsp.dll", @"Inetcntrl.dll", @"Ippsp.dll", @"Ipsp.dll", @"Iss_clsp.dll", @"Iss_slsp.dll", @"Kvwsp.dll", @"Kvwspxp.dll", @"Lslsimon.dll", @"Lsp32.dll", @"Lspcs.dll", @"Mclsp.dll", @"Mdnsnsp.dll", @"Msafd.dll", @"Msniffer.dll", @"Mswsock.dll", @"Mswsosp.dll", @"Mwtsp.dll", @"Mxavlsp.dll", @"Napinsp.dll", @"Nblsp.dll", @"Ndpwsspr.dll", @"Netd.dll", @"Nihlsp.dll", @"Nlaapi.dll", @"Nl_lsp.dll", @"Nnsp.dll", @"Normanpf.dll", @"Nutafun4.dll", @"Nvappfilter.dll", @"Nwws2nds.dll", @"Nwws2sap.dll", @"Nwws2slp.dll", @"Odsp.dll", @"Pavlsp.dll", @"Pclsp.dll", @"Pctlsp.dll", @"Pfftsp.dll", @"Pgplsp.dll", @"Pidlsp.dll", @"Pnrpnsp.dll", @"Prifw.dll", @"Proxy.dll", @"Prplsf.dll", @"Pxlsp.dll", @"Rnr20.dll", @"Rsvpsp.dll", @"S5spi.dll", @"Samnsp.dll", @"Sarah.dll", @"Scopinet.dll", @"Skysocks.dll", @"Sliplsp.dll", @"Smnsp.dll", @"Spacklsp.dll", @"Spampallsp.dll", @"Spi.dll", @"Spidll.dll", @"Spishare.dll", @"Spsublsp.dll", @"Sselsp.dll", @"Stplayer.dll", @"Syspy.dll", @"Tasi.dll", @"Tasp.dll", @"Tcpspylsp.dll", @"Ua_lsp.dll", @"Ufilter.dll", @"Vblsp.dll", @"Vetredir.dll", @"Vlsp.dll", @"Vnsp.dll", @"Wglsp.dll", @"Whllsp.dll", @"Whlnsp.dll", @"Winrnr.dll", @"Wins4f.dll", @"Winsflt.dll", @"WinSysAM.dll", @"Wps.dll", @"Wshbth.dll", @"Wspirda.dll", @"Wspwsp.dll", @"Xfilter.dll", @"xfire_lsp.dll", @"Xnetlsp.dll", @"Ypclsp.dll", @"Zklspr.dll", @"_Easywall.dll", @"_Handywall.dll", @"vsocklib.dll" //VSockets Library (VMWare, Inc.) }; } } #endregion private IEnumerable<IDetectionResultItem> CheckCommon(RegistryHive regHive, RegistryKey regKey, IEnumerable<string> subKeyNames, string catalogName = CURRENT_NAMESPACE_CATALOG, string fileNameKey = NAMESPACE_LIBRARY_PATH) { var results = new Collection<IDetectionResultItem>(); if (regKey == null) return results; var nameSpaceCatalog = regKey.GetValue(catalogName, null) as string; if (string.IsNullOrEmpty(nameSpaceCatalog)) { results.Add(new LayeredServiceProviderResult(LayeredServiceProviderType.EmptyEntry, new RegistryInformation { Hive = regHive, View = regKey.View, Path = regKey.Name, Name = CURRENT_NAMESPACE_CATALOG, Value = null })); } else { var lspDetected = subKeyNames.FirstOrDefault(f => f.Equals(nameSpaceCatalog, StringComparison.InvariantCultureIgnoreCase)) != null; if (!lspDetected) { results.Add(new LayeredServiceProviderResult(LayeredServiceProviderType.RegistryKeyNotFound, new RegistryInformation { Hive = regHive, View = regKey.View, Path = Path.Combine(regKey.Name, nameSpaceCatalog), Name = null, Value = null })); } else { using (var subKey = regKey.OpenSubKey(nameSpaceCatalog, false)) { if (subKey != null) { var numEntries = subKey.GetValue(NUM_CATALOG_ENTRIES, null) as Int32?; if (numEntries.HasValue && numEntries.Value > 0) { using (var catalogKey = subKey.OpenSubKey("Catalog_Entries", false)) { if (catalogKey != null) { var entries = catalogKey.GetSubKeyNames(); //check LSP chain gaps for (var i = 1; i < numEntries + 1; i++) { if (!entries.Contains(string.Format("{0:D12}", i))) { results.Add(new LayeredServiceProviderResult(LayeredServiceProviderType.MissingChainGap, new RegistryInformation { Hive = regHive, View = catalogKey.View, Path = catalogKey.Name, Name = i.ToString(CultureInfo.InvariantCulture), Value = numEntries.Value })); } } foreach (var entry in entries) { using (var entryKey = catalogKey.OpenSubKey(entry, false)) { if (entryKey != null) { var libPath = string.Empty; var kind = entryKey.GetValueKind(fileNameKey); switch (kind) { case RegistryValueKind.Binary: var libPathArray = entryKey.GetValue("PackedCatalogItem", null) as byte[]; if (libPathArray != null && libPathArray.Any()) { libPath = Encoding.UTF8.GetString(libPathArray, 0, Math.Min(Array.IndexOf<byte>(libPathArray, 0), libPathArray.Length)); } break; case RegistryValueKind.String: libPath = entryKey.GetValue(fileNameKey, null) as string; break; default: libPath = null; break; } if (!string.IsNullOrEmpty(libPath)) { libPath = Environment.ExpandEnvironmentVariables(libPath); var libFile = Path.GetFileName(libPath); if (!File.Exists(libPath)) { results.Add(new LayeredServiceProviderResult(LayeredServiceProviderType.MissingProvider, new RegistryInformation { Hive = regHive, View = entryKey.View, Path = entryKey.Name, Name = fileNameKey, Value = libPath, }, libPath)); } else { //var fileName = Path.GetFileName(libPath); //System.Diagnostics.Debug.WriteLine(libPath); if (libPath.IndexOf("webhdll.dll", StringComparison.InvariantCultureIgnoreCase) > -1) { results.Add(new LayeredServiceProviderResult(LayeredServiceProviderType.HijackedWebHancer, new RegistryInformation { Hive = regHive, View = entryKey.View, Path = entryKey.Name, Name = fileNameKey, Value = libPath, }, libPath)); } else if (libPath.IndexOf("newdot", StringComparison.InvariantCultureIgnoreCase) > -1) { results.Add(new LayeredServiceProviderResult(LayeredServiceProviderType.HijackedNewDotNet, new RegistryInformation { Hive = regHive, View = entryKey.View, Path = entryKey.Name, Name = fileNameKey, Value = libPath, }, libPath)); } else if (libPath.IndexOf("cnmib.dll", StringComparison.InvariantCultureIgnoreCase) > -1) { results.Add(new LayeredServiceProviderResult(LayeredServiceProviderType.HijackedCommonName, new RegistryInformation { Hive = regHive, View = entryKey.View, Path = entryKey.Name, Name = fileNameKey, Value = libPath, }, libPath)); } else if ( SafeLayeredServiceProviders.All( a => a.IndexOf(libFile, StringComparison.InvariantCultureIgnoreCase) == -1)) { results.Add(new LayeredServiceProviderResult(LayeredServiceProviderType.UnknownFile, new RegistryInformation { Hive = regHive, View = entryKey.View, Path = entryKey.Name, Name = fileNameKey, Value = libPath, }, libPath)); } } } else { results.Add(new LayeredServiceProviderResult(LayeredServiceProviderType.MissingLibrary, new RegistryInformation { Hive = regHive, View = entryKey.View, Path = entryKey.Name, Name = fileNameKey, Value = null, })); } } } } } } } else { results.Add(new LayeredServiceProviderResult(LayeredServiceProviderType.NoRegistryEntries, new RegistryInformation { Hive = regHive, View = subKey.View, Path = subKey.Name, Name = NUM_CATALOG_ENTRIES, Value = null })); } } else { results.Add(new LayeredServiceProviderResult(LayeredServiceProviderType.RegistryAccessError, new RegistryInformation { Hive = regHive, View = regKey.View, Path = Path.Combine(regKey.Name, nameSpaceCatalog), Name = null, Value = null })); } } } } return results; } private IEnumerable<IDetectionResultItem> CheckNameSpaceCatalogs(RegistryHive regHive, RegistryKey regKey, IEnumerable<string> subKeyNames) { return CheckCommon(regHive, regKey, subKeyNames); } private IEnumerable<IDetectionResultItem> CheckProtocolCatalogs(RegistryHive regHive, RegistryKey regKey, IEnumerable<string> subKeyNames) { return CheckCommon(regHive, regKey, subKeyNames, CURRENT_PROTOCOL_CATALOG, PROTOCOL_PACKED_CATALOG_ITEM); } #endregion public string Author { get { return "William David Cossey"; } } private Version _version; public Version Version { get { if (_version != null) return _version; return _version = new Version(1, 0, 0, 0); } } public string Name { get { return @"Layered Service Provider"; } } public string[] Description { get { return new[] { "Scans for broken WinSock \"Layered Service Provider(s)\" (also known as LSP's)." }; } } public ScanResultType ResultType { get { return ScanResultType.WinSockLayeredServiceProvider; } } public void Dispose() { //Nothing to dispose? } public async Task<ICollection<IDetectionResultItem>> Scan() { //await Task.FromResult(0); var result = new List<IDetectionResultItem>(); const RegistryHive regHive = RegistryHive.LocalMachine; using (var rootKey = RegistryKey.OpenBaseKey(regHive, RegistryView.Default)) { using (var regKey = rootKey.OpenSubKey(REGISTRY_PATH_PARAMETERS, false)) { if (regKey == null) return result; var subKeyNames = regKey.GetSubKeyNames().ToList(); result.AddRange(CheckNameSpaceCatalogs(regHive, regKey, subKeyNames)); result.AddRange(CheckProtocolCatalogs(regHive, regKey, subKeyNames)); } } return result; } } #endregion #region Original Visual Basic (6.0) Code Block /* Public Sub GetLSPCatalogNames() sKeyNameSpace = "System\CurrentControlSet\Services\WinSock2\Parameters" sKeyProtocol = "System\CurrentControlSet\Services\WinSock2\Parameters" sKeyNameSpace = sKeyNameSpace & "\" & RegGetString(HKEY_LOCAL_MACHINE, sKeyNameSpace, "Current_NameSpace_Catalog") sKeyProtocol = sKeyProtocol & "\" & RegGetString(HKEY_LOCAL_MACHINE, sKeyProtocol, "Current_Protocol_Catalog") End Sub */ #region Scan /* Public Sub CheckLSP() Dim lNumNameSpace&, lNumProtocol&, i&, j& ', sSafeFiles$ Dim sFile$, uData() As Byte, hKey&, sHit$, sDummy$ On Error GoTo Error: lNumNameSpace = RegGetDword(HKEY_LOCAL_MACHINE, sKeyNameSpace, "Num_Catalog_Entries") lNumProtocol = RegGetDword(HKEY_LOCAL_MACHINE, sKeyProtocol, "Num_Catalog_Entries") 'check for gaps in LSP chain For i = 1 To lNumNameSpace If RegKeyExists(HKEY_LOCAL_MACHINE, sKeyNameSpace & "\Catalog_Entries\" & String(12 - Len(CStr(i)), "0") & CStr(i)) Then 'all fine & peachy Else 'broken LSP detected! frmMain.lstResults.AddItem "O10 - Broken Internet access because of LSP chain gap (#" & CStr(i) & " in chain of " & CStr(lNumNameSpace) & " missing)" Exit Sub End If Next i For i = 1 To lNumProtocol If RegKeyExists(HKEY_LOCAL_MACHINE, sKeyProtocol & "\Catalog_Entries\" & String(12 - Len(CStr(i)), "0") & CStr(i)) Then 'all fine & dandy Else 'shit, not again! frmMain.lstResults.AddItem "O10 - Broken Internet access because of LSP chain gap (#" & CStr(i) & " in chain of " & CStr(lNumProtocol) & " missing)" Exit Sub End If Next i 'check all LSP providers are present For i = 1 To lNumNameSpace sFile = RegGetString(HKEY_LOCAL_MACHINE, sKeyNameSpace & "\Catalog_Entries\" & String(12 - Len(CStr(i)), "0") & CStr(i), "LibraryPath") sFile = LCase(Replace(sFile, "%SYSTEMROOT%", sWinDir, , , vbTextCompare)) sFile = LCase(Replace(sFile, "%windir%", sWinDir, , , vbTextCompare)) If sFile <> vbNullString Then If FileExists(sFile) Or _ FileExists(sWinDir & "\" & sFile) Or _ FileExists(sWinSysDir & "\" & sFile) Then 'file ok If InStr(sFile, "webhdll.dll") > 0 Then sHit = "O10 - Hijacked Internet access by WebHancer" If Not IsOnIgnoreList(sHit) Then frmMain.lstResults.AddItem sHit ElseIf InStr(sFile, "newdot") > 0 Then sHit = "O10 - Hijacked Internet access by New.Net" If Not IsOnIgnoreList(sHit) Then frmMain.lstResults.AddItem sHit ElseIf InStr(sFile, "cnmib.dll") > 0 Then sHit = "O10 - Hijacked Internet access by CommonName" If Not IsOnIgnoreList(sHit) Then frmMain.lstResults.AddItem sHit Else sDummy = Mid(sFile, InStrRev(sFile, "\") + 1) If InStr(1, sSafeLSPFiles, sDummy, vbTextCompare) = 0 Or bIgnoreAllWhitelists Then sHit = "O10 - Unknown file in Winsock LSP: " & sFile If Not IsOnIgnoreList(sHit) Then frmMain.lstResults.AddItem sHit End If End If Else 'damn, file is gone If InStr(1, sSafeLSPFiles, sFile, vbTextCompare) = 0 Or bIgnoreAllWhitelists Then frmMain.lstResults.AddItem "O10 - Broken Internet access because of LSP provider '" & sFile & "' missing" End If Exit Sub End If End If Next i For i = 1 To lNumProtocol sFile = RegGetFileFromBinary(HKEY_LOCAL_MACHINE, sKeyProtocol & "\Catalog_Entries\" & String(12 - Len(CStr(i)), "0") & CStr(i), "PackedCatalogItem") sFile = LCase(Replace(sFile, "%SYSTEMROOT%", sWinDir, , , vbTextCompare)) sFile = LCase(Replace(sFile, "%windir%", sWinDir, , , vbTextCompare)) If sFile <> vbNullString Then If FileExists(sFile) Or _ FileExists(sWinDir & "\" & sFile) Or _ FileExists(sWinSysDir & "\" & sFile) Then 'file ok If InStr(1, sFile, "webhdll.dll", vbTextCompare) > 0 Then sHit = "O10 - Hijacked Internet access by WebHancer" If Not IsOnIgnoreList(sHit) Then frmMain.lstResults.AddItem sHit ElseIf InStr(1, sFile, "newdot", vbTextCompare) > 0 Then sHit = "O10 - Hijacked Internet access by New.Net" If Not IsOnIgnoreList(sHit) Then frmMain.lstResults.AddItem sHit ElseIf InStr(1, sFile, "cnmib.dll", vbTextCompare) > 0 Then sHit = "O10 - Hijacked Internet access by CommonName" If Not IsOnIgnoreList(sHit) Then frmMain.lstResults.AddItem sHit Else sDummy = LCase(Mid(sFile, InStrRev(sFile, "\") + 1)) If InStr(1, sSafeLSPFiles, sDummy, vbTextCompare) = 0 Or bIgnoreAllWhitelists Then sHit = "O10 - Unknown file in Winsock LSP: " & sFile If Not IsOnIgnoreList(sHit) Then frmMain.lstResults.AddItem sHit End If End If Else 'damn - crossed again! If InStr(1, sSafeLSPFiles, sFile, vbTextCompare) = 0 Or bIgnoreAllWhitelists Then frmMain.lstResults.AddItem "O10 - Broken Internet access because of LSP provider '" & sFile & "' missing" End If Exit Sub End If End If Next i Exit Sub Error: RegCloseKey hKey ErrorMsg "modLSP_CheckLSP", Err.Number, Err.Description End Sub */ #endregion #region Repair #endregion #region Backup #endregion #endregion }
wdcossey/ReviveThis.Net
Add-In/Scan/ReviveThis.Net.AddIn.WinSock/LayeredServiceProvider.cs
C#
gpl-2.0
23,271
using System; using MrCMS.Messages; namespace MrCMS.Web.Apps.Commenting.MessageTemplates { public class GetDefaultCommentReportedMessageTemplate : GetDefaultTemplate<CommentReportedMessageTemplate> { public override CommentReportedMessageTemplate Get() { return new CommentReportedMessageTemplate { FromAddress = "test@example.com", FromName = "Site Owner", ToAddress = "{NotifyCommentAddedEmail}", ToName = "", Bcc = String.Empty, Cc = String.Empty, Subject = "A Comment Reported - #{Id}", Body = "<p>Comment #{Id} on <a href=\"{PageUrl}\">{PageName}</a> has been reported.</p><p><a href=\"{CommentModerationUrl}\">Comment Moderation</a></p><p>It has been reported by: {ReportedCommentDetails}</p>", IsHtml = true }; } } }
MrCMS/Commenting
MessageTemplates/GetDefaultCommentReportedMessageTemplate.cs
C#
gpl-2.0
940
<?php if ( is_user_logged_in() ) : ?> <fieldset> <label><?php _e( 'Your account', 'wp-job-manager' ); ?></label> <div class="field account-sign-in"> <?php $user = wp_get_current_user(); printf( __( 'You are currently signed in as <strong>%s</strong>.', 'wp-job-manager' ), $user->user_login ); ?> <a class="button" href="<?php echo apply_filters( 'submit_job_form_logout_url', wp_logout_url( get_permalink() ) ); ?>"><?php _e( 'Sign out', 'wp-job-manager' ); ?></a> </div> </fieldset> <?php else : $account_required = job_manager_user_requires_account(); $registration_enabled = job_manager_enable_registration(); $generate_username_from_email = job_manager_generate_username_from_email(); $login_url = listable_get_login_url(); $classes = listable_get_login_link_class( 'button' ); ?> <fieldset> <label><?php _e( 'Have an account?', 'wp-job-manager' ); ?></label> <div class="field account-sign-in <?php echo ( listable_using_lwa() ) ? 'lwa' : ''; ?>"> <a class="<?php echo $classes; ?>" href="<?php echo apply_filters( 'submit_job_form_login_url', $login_url ); ?>"><?php _e( 'Sign in', 'wp-job-manager' ); ?></a> <?php if ( $registration_enabled ) : ?> <?php printf( __( 'If you don&rsquo;t have an account you can %screate one below by entering your email address/username. Your account details will be confirmed via email.', 'wp-job-manager' ), $account_required ? '' : __( 'optionally', 'wp-job-manager' ) . ' ' ); ?> <?php elseif ( $account_required ) : ?> <?php echo apply_filters( 'submit_job_form_login_required_message', __('You must sign in to create a new listing.', 'wp-job-manager' ) ); ?> <?php endif; ?> </div> </fieldset> <?php if ( $registration_enabled ) : ?> <?php if ( ! $generate_username_from_email ) : ?> <fieldset> <label><?php _e( 'Username', 'wp-job-manager' ); ?> <?php echo apply_filters( 'submit_job_form_required_label', ( ! $account_required ) ? ' <small>' . __( '(optional)', 'wp-job-manager' ) . '</small>' : '' ); ?></label> <div class="field"> <input type="text" class="input-text" name="create_account_username" id="account_username" value="<?php echo empty( $_POST['create_account_username'] ) ? '' : esc_attr( sanitize_text_field( stripslashes( $_POST['create_account_username'] ) ) ); ?>" /> </div> </fieldset> <?php endif; ?> <fieldset> <label><?php _e( 'Your email', 'wp-job-manager' ); ?> <?php echo apply_filters( 'submit_job_form_required_label', ( ! $account_required ) ? ' <small>' . __( '(optional)', 'wp-job-manager' ) . '</small>' : '' ); ?></label> <div class="field"> <input type="email" class="input-text" name="create_account_email" id="account_email" placeholder="<?php esc_attr_e( 'you@yourdomain.com', 'wp-job-manager' ); ?>" value="<?php echo empty( $_POST['create_account_email'] ) ? '' : esc_attr( sanitize_text_field( stripslashes( $_POST['create_account_email'] ) ) ); ?>" /> </div> </fieldset> <?php do_action( 'job_manager_register_form' ); ?> <?php endif; ?> <?php endif; ?>
golfcoastmagazine/golfcoastmagazine
wp-content/themes/listable/job_manager/account-signin.php
PHP
gpl-2.0
3,081
## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # https://morningstarsecurity.com/research/whatweb ## Plugin.define do name "SDCMS" authors [ "Brendan Coles <bcoles@gmail.com>", # 2011-10-29 ] version "0.1" description "SDCMS - CMS - Requires ASP and Access/MsSql" website "http://www.sdcms.cn/" # Google results as at 2011-10-29 # # 410 for "Powered By SDCMS" # Dorks # dorks [ '"Powered By SDCMS"' ] # Matches # matches [ # Powered by link # Version Detection { :version=>/<br>Powered By <a href=['"]http:\/\/www\.sdcms\.cn['"] target=['"]_blank['"]>SDCMS ([^<]+)<\/a>/ }, # dl id="con_three_1" class="index_photo" { :text=>'<dl id="con_three_1" class="index_photo">' }, ] end
urbanadventurer/WhatWeb
plugins/sdcms.rb
Ruby
gpl-2.0
831
<?php /** * RSS2 Feed Template for displaying RSS2 Posts feed. * * @package WordPress */ header('Content-Type: ' . feed_content_type('rss-http') . '; charset=' . get_option('blog_charset'), true); $more = 1; echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" <?php /** * Fires at the end of the RSS root to add namespaces. * * @since 2.0.0 */ do_action( 'rss2_ns' ); ?> > <channel> <title><?php bloginfo_rss('name'); wp_title_rss(); ?></title> <atom:link href="<?php self_link(); ?>" rel="self" type="application/rss+xml" /> <link><?php bloginfo_rss('url') ?></link> <description><?php bloginfo_rss("description") ?></description> <lastBuildDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?></lastBuildDate> <language><?php bloginfo_rss( 'language' ); ?></language> <?php $duration = 'hourly'; /** * Filter how often to update the RSS feed. * * @since 2.1.0 * * @param string $duration The update period. * Default 'hourly'. Accepts 'hourly', 'daily', 'weekly', 'monthly', 'yearly'. */ ?> <sy:updatePeriod><?php echo apply_filters( 'rss_update_period', $duration ); ?></sy:updatePeriod> <?php $frequency = '1'; /** * Filter the RSS update frequency. * * @since 2.1.0 * * @param string $frequency An integer passed as a string representing the frequency * of RSS updates within the update period. Default '1'. */ ?> <sy:updateFrequency><?php echo apply_filters( 'rss_update_frequency', $frequency ); ?></sy:updateFrequency> <?php /** * Fires at the end of the RSS2 Feed Header. * * @since 2.0.0 */ do_action( 'rss2_head'); while( have_posts()) : the_post(); ?> <item> <title><?php the_title_rss() ?></title> <link><?php the_permalink_rss() ?></link> <comments><?php comments_link_feed(); ?></comments> <pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?></pubDate> <dc:creator><![CDATA[<?php the_author() ?>]]></dc:creator> <?php the_category_rss('rss2') ?> <guid isPermaLink="false"><?php the_guid(); ?></guid> <?php if (get_option('rss_use_excerpt')) : ?> <description><![CDATA[<?php the_excerpt_rss(); ?>]]></description> <?php else : ?> <description><![CDATA[<?php the_excerpt_rss(); ?>]]></description> <?php $content = get_the_content_feed('rss2'); ?> <?php if ( strlen( $content ) > 0 ) : ?> <content:encoded><![CDATA[<?php echo $content; ?>]]></content:encoded> <?php else : ?> <content:encoded><![CDATA[<?php the_excerpt_rss(); ?>]]></content:encoded> <?php endif; ?> <?php endif; ?> <wfw:commentRss><?php echo esc_url( get_post_comments_feed_link(null, 'rss2') ); ?></wfw:commentRss> <slash:comments><?php echo get_comments_number(); ?></slash:comments> <?php rss_enclosure(); ?> <?php /** * Fires at the end of each RSS2 feed item. * * @since 2.0.0 */ do_action( 'rss2_item' ); ?> </item> <?php endwhile; ?> </channel> </rss>
MESH-Dev/MESH
wp-includes/feed-rss2.php
PHP
gpl-2.0
3,351
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="LightButton.cs" company="LeagueSharp"> // Copyright (C) 2015 LeagueSharp // // 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/>. // </copyright> // <summary> // A custom implementation of <see cref="ADrawable{MenuButton}" /> // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace LeagueSharp.SDK.UI.Skins.Light { using LeagueSharp.SDK.Enumerations; using LeagueSharp.SDK.Utils; using SharpDX; using SharpDX.Direct3D9; /// <summary> /// A default implementation of <see cref="ADrawable{MenuButton}" /> /// </summary> public class LightButton : ADrawable<MenuButton> { #region Constants /// <summary> /// The text gap. /// </summary> private const int TextGap = 5; #endregion #region Static Fields /// <summary> /// The line. /// </summary> private static readonly Line Line = new Line(Drawing.Direct3DDevice) { GLLines = true }; #endregion #region Fields /// <summary> /// The button color. /// </summary> private readonly ColorBGRA buttonColor = new ColorBGRA(151, 151, 151, 255); /// <summary> /// The button hover color. /// </summary> private readonly ColorBGRA buttonHoverColor = new ColorBGRA(171, 171, 171, 200); #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="LightButton" /> class. /// </summary> /// <param name="component"> /// The menu component /// </param> public LightButton(MenuButton component) : base(component) { } #endregion #region Public Methods and Operators /// <summary> /// Calculate the Rectangle that defines the Button /// </summary> /// <param name="component">The <see cref="MenuButton" /></param> /// <returns> /// The <see cref="Rectangle" /> /// </returns> public Rectangle ButtonBoundaries(MenuButton component) { var buttonTextWidth = MenuSettings.Font.MeasureText(MenuManager.Instance.Sprite, component.ButtonText, 0).Width; return new Rectangle( (int)(component.Position.X + component.MenuWidth - buttonTextWidth - (2 * TextGap)), (int)component.Position.Y, (2 * TextGap) + buttonTextWidth, MenuSettings.ContainerHeight); } /// <summary> /// Disposes any resources used in this handler. /// </summary> public override void Dispose() { // Do nothing. } /// <summary> /// Draws a <see cref="MenuButton" /> /// </summary> public override void Draw() { var rectangleName = LightUtilities.GetContainerRectangle(this.Component) .GetCenteredText( null, MenuSettings.Font, MultiLanguage.Translation(this.Component.DisplayName), CenteredFlags.VerticalCenter); MenuSettings.Font.DrawText( MenuManager.Instance.Sprite, MultiLanguage.Translation(this.Component.DisplayName), (int)(this.Component.Position.X + MenuSettings.ContainerTextOffset), (int)rectangleName.Y, MenuSettings.TextColor); var buttonTextWidth = MenuSettings.Font.MeasureText(MenuManager.Instance.Sprite, this.Component.ButtonText, 0).Width; Line.Width = MenuSettings.ContainerHeight - 5; Line.Begin(); Line.Draw( new[] { new Vector2( this.Component.Position.X + this.Component.MenuWidth - buttonTextWidth - (2 * TextGap) + 2, this.Component.Position.Y + (MenuSettings.ContainerHeight / 2f)), new Vector2( this.Component.Position.X + this.Component.MenuWidth - 2, this.Component.Position.Y + (MenuSettings.ContainerHeight / 2f)), }, this.Component.Hovering ? this.buttonHoverColor : this.buttonColor); Line.End(); MenuSettings.Font.DrawText( MenuManager.Instance.Sprite, MultiLanguage.Translation(this.Component.ButtonText), (int)(this.Component.Position.X + this.Component.MenuWidth - buttonTextWidth - TextGap), (int)rectangleName.Y, new ColorBGRA(221, 233, 255, 255)); } /// <summary> /// Processes windows events /// </summary> /// <param name="args"> /// The event data /// </param> public override void OnWndProc(WindowsKeys args) { if (!this.Component.Visible) { return; } var rect = this.ButtonBoundaries(this.Component); if (args.Cursor.IsUnderRectangle(rect.X, rect.Y, rect.Width, rect.Height)) { this.Component.Hovering = true; if (args.Msg == WindowsMessages.LBUTTONDOWN) { this.Component.Action?.Invoke(); } } else { this.Component.Hovering = false; } } /// <summary> /// Gets the width of the <see cref="MenuButton" /> /// </summary> /// <returns> /// The <see cref="int" />. /// </returns> public override int Width() { return LightUtilities.CalcWidthItem(this.Component) + (2 * TextGap) + MenuSettings.Font.MeasureText(MenuManager.Instance.Sprite, this.Component.ButtonText, 0).Width; } #endregion } }
CjShuMoon/TwLS.SDK
Core/UI/IMenu/Skins/Light/LightButton.cs
C#
gpl-2.0
6,953
# -*- coding: utf-8 -*- """ Created on Thu Nov 19 17:38:50 2015 @author: deep """ from binaryTree import BTree, generateRandomTree, inorder def largestBST(root): if root.left is None and root.right is None: return True, 1, root.value, root.value if root.left: isBSTL, sizeL, minL, maxL = largestBST(root.left) else: isBSTL = True sizeL = 0 minL = -float('inf') if root.right: isBSTR, sizeR, minR, maxR = largestBST(root.right) else: isBSTR = True sizeR = 0 maxR = float('inf') if isBSTL and isBSTR: if maxL <= root.value <= minR: return True, sizeL+sizeR+1, minL, maxR, size = max(sizeL, sizeR) return False, size , None, None root1 = BTree() root1.value = 0 root2 = BTree() root2.value = 0 generateRandomTree(root2,2) generateRandomTree(root1,2) root1.left.left.left = root2 inorder(root1) print largestBST(root1)
ddeepak6992/Algorithms
Binary-Tree/largest_BST_in_a_binary_tree.py
Python
gpl-2.0
953
package edu.stanford.nlp.parser.lexparser; import edu.stanford.nlp.trees.CompositeTreeTransformer; import edu.stanford.nlp.trees.TreebankLanguagePack; import edu.stanford.nlp.trees.TreeTransformer; import edu.stanford.nlp.util.Function; import edu.stanford.nlp.util.ReflectionLoading; import edu.stanford.nlp.util.StringUtils; import java.io.*; import java.util.*; import org.apache.log4j.Logger; /** * This class contains options to the parser which MUST be the SAME at * both training and testing (parsing) time in order for the parser to * work properly. It also contains an object which stores the options * used by the parser at training time and an object which contains * default options for test use. * * @author Dan Klein * @author Christopher Manning * @author John Bauer */ public class Options implements Serializable { protected static Logger logger = Logger.getRootLogger(); public Options() { this(new EnglishTreebankParserParams()); } public Options(TreebankLangParserParams tlpParams) { this.tlpParams = tlpParams; } /** * Set options based on a String array in the style of * commandline flags. This method goes through the array until it ends, * processing options, as for {@link #setOption}. * * @param flags Array of options (or as a varargs list of arguments). * The options passed in should * be specified like command-line arguments, including with an initial * minus sign for example, * {"-outputFormat", "typedDependencies", "-maxLength", "70"} * @throws IllegalArgumentException If an unknown flag is passed in */ public void setOptions(String... flags) { setOptions(flags, 0, flags.length); } /** * Set options based on a String array in the style of * commandline flags. This method goes through the array until it ends, * processing options, as for {@link #setOption}. * * @param flags Array of options. The options passed in should * be specified like command-line arguments, including with an initial * minus sign for example, * {"-outputFormat", "typedDependencies", "-maxLength", "70"} * @param startIndex The index in the array to begin processing options at * @param endIndexPlusOne A number one greater than the last array index at * which options should be processed * @throws IllegalArgumentException If an unknown flag is passed in */ public void setOptions(final String[] flags, final int startIndex, final int endIndexPlusOne) { for (int i = startIndex; i < endIndexPlusOne;) { i = setOption(flags, i); } } /** * Set options based on a String array in the style of * commandline flags. This method goes through the array until it ends, * processing options, as for {@link #setOption}. * * @param flags Array of options (or as a varargs list of arguments). * The options passed in should * be specified like command-line arguments, including with an initial * minus sign for example, * {"-outputFormat", "typedDependencies", "-maxLength", "70"} * @throws IllegalArgumentException If an unknown flag is passed in */ public void setOptionsOrWarn(String... flags) { setOptionsOrWarn(flags, 0, flags.length); } /** * Set options based on a String array in the style of * commandline flags. This method goes through the array until it ends, * processing options, as for {@link #setOption}. * * @param flags Array of options. The options passed in should * be specified like command-line arguments, including with an initial * minus sign for example, * {"-outputFormat", "typedDependencies", "-maxLength", "70"} * @param startIndex The index in the array to begin processing options at * @param endIndexPlusOne A number one greater than the last array index at * which options should be processed * @throws IllegalArgumentException If an unknown flag is passed in */ public void setOptionsOrWarn(final String[] flags, final int startIndex, final int endIndexPlusOne) { for (int i = startIndex; i < endIndexPlusOne;) { i = setOptionOrWarn(flags, i); } } /** * Set an option based on a String array in the style of * commandline flags. The option may * be either one known by the Options object, or one recognized by the * TreebankLangParserParams which has already been set up inside the Options * object, and then the option is set in the language-particular * TreebankLangParserParams. * Note that despite this method being an instance method, many flags * are actually set as static class variables in the Train and Test * classes (this should be fixed some day). * Some options (there are many others; see the source code): * <ul> * <li> <code>-maxLength n</code> set the maximum length sentence to parse (inclusively) * <li> <code>-printTT</code> print the training trees in raw, annotated, and annotated+binarized form. Useful for debugging and other miscellany. * <li> <code>-printAnnotated filename</code> use only in conjunction with -printTT. Redirects printing of annotated training trees to <code>filename</code>. * <li> <code>-forceTags</code> when the parser is tested against a set of gold standard trees, use the tagged yield, instead of just the yield, as input. * </ul> * * @param flags An array of options arguments, command-line style. E.g. {"-maxLength", "50"}. * @param i The index in flags to start at when processing an option * @return The index in flags of the position after the last element used in * processing this option. If the current array position cannot be processed as a valid * option, then a warning message is printed to stderr and the return value is <code>i+1</code> */ public int setOptionOrWarn(String[] flags, int i) { int j = setOptionFlag(flags, i); if (j == i) { j = tlpParams.setOptionFlag(flags, i); } if (j == i) { System.err.println("WARNING! lexparser.Options: Unknown option ignored: " + flags[i]); j++; } return j; } /** * Set an option based on a String array in the style of * commandline flags. The option may * be either one known by the Options object, or one recognized by the * TreebankLangParserParams which has already been set up inside the Options * object, and then the option is set in the language-particular * TreebankLangParserParams. * Note that despite this method being an instance method, many flags * are actually set as static class variables in the Train and Test * classes (this should be fixed some day). * Some options (there are many others; see the source code): * <ul> * <li> <code>-maxLength n</code> set the maximum length sentence to parse (inclusively) * <li> <code>-printTT</code> print the training trees in raw, annotated, and annotated+binarized form. Useful for debugging and other miscellany. * <li> <code>-printAnnotated filename</code> use only in conjunction with -printTT. Redirects printing of annotated training trees to <code>filename</code>. * <li> <code>-forceTags</code> when the parser is tested against a set of gold standard trees, use the tagged yield, instead of just the yield, as input. * </ul> * * @param flags An array of options arguments, command-line style. E.g. {"-maxLength", "50"}. * @param i The index in flags to start at when processing an option * @return The index in flags of the position after the last element used in * processing this option. * @throws IllegalArgumentException If the current array position cannot be * processed as a valid option */ public int setOption(String[] flags, int i) { int j = setOptionFlag(flags, i); if (j == i) { j = tlpParams.setOptionFlag(flags, i); } if (j == i) { throw new IllegalArgumentException("Unknown option: " + flags[i]); } return j; } /** * Set an option in this object, based on a String array in the style of * commandline flags. The option is only processed with respect to * options directly known by the Options object. * Some options (there are many others; see the source code): * <ul> * <li> <code>-maxLength n</code> set the maximum length sentence to parse (inclusively) * <li> <code>-printTT</code> print the training trees in raw, annotated, and annotated+binarized form. Useful for debugging and other miscellany. * <li> <code>-printAnnotated filename</code> use only in conjunction with -printTT. Redirects printing of annotated training trees to <code>filename</code>. * <li> <code>-forceTags</code> when the parser is tested against a set of gold standard trees, use the tagged yield, instead of just the yield, as input. * </ul> * * @param args An array of options arguments, command-line style. E.g. {"-maxLength", "50"}. * @param i The index in args to start at when processing an option * @return The index in args of the position after the last element used in * processing this option, or the value i unchanged if a valid option couldn't * be processed starting at position i. */ private int setOptionFlag(String[] args, int i) { if (args[i].equalsIgnoreCase("-PCFG")) { doDep = false; doPCFG = true; i++; } else if (args[i].equalsIgnoreCase("-dep")) { doDep = true; doPCFG = false; i++; } else if (args[i].equalsIgnoreCase("-factored")) { doDep = true; doPCFG = true; testOptions.useFastFactored = false; i++; } else if (args[i].equalsIgnoreCase("-fastFactored")) { doDep = true; doPCFG = true; testOptions.useFastFactored = true; i++; } else if (args[i].equalsIgnoreCase("-noRecoveryTagging")) { testOptions.noRecoveryTagging = true; i++; } else if (args[i].equalsIgnoreCase("-useLexiconToScoreDependencyPwGt")) { testOptions.useLexiconToScoreDependencyPwGt = true; i++; } else if (args[i].equalsIgnoreCase("-useSmoothTagProjection")) { useSmoothTagProjection = true; i++; } else if (args[i].equalsIgnoreCase("-useUnigramWordSmoothing")) { useUnigramWordSmoothing = true; i++; } else if (args[i].equalsIgnoreCase("-useNonProjectiveDependencyParser")) { testOptions.useNonProjectiveDependencyParser = true; i++; } else if (args[i].equalsIgnoreCase("-maxLength") && (i + 1 < args.length)) { testOptions.maxLength = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-MAX_ITEMS") && (i + 1 < args.length)) { testOptions.MAX_ITEMS = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-trainLength") && (i + 1 < args.length)) { // train on only short sentences trainOptions.trainLengthLimit = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-lengthNormalization")) { testOptions.lengthNormalization = true; i++; } else if (args[i].equalsIgnoreCase("-iterativeCKY")) { testOptions.iterativeCKY = true; i++; } else if (args[i].equalsIgnoreCase("-vMarkov") && (i + 1 < args.length)) { int order = Integer.parseInt(args[i + 1]); if (order <= 1) { trainOptions.PA = false; trainOptions.gPA = false; } else if (order == 2) { trainOptions.PA = true; trainOptions.gPA = false; } else if (order >= 3) { trainOptions.PA = true; trainOptions.gPA = true; } i += 2; } else if (args[i].equalsIgnoreCase("-vSelSplitCutOff") && (i + 1 < args.length)) { trainOptions.selectiveSplitCutOff = Double.parseDouble(args[i + 1]); trainOptions.selectiveSplit = trainOptions.selectiveSplitCutOff > 0.0; i += 2; } else if (args[i].equalsIgnoreCase("-vSelPostSplitCutOff") && (i + 1 < args.length)) { trainOptions.selectivePostSplitCutOff = Double.parseDouble(args[i + 1]); trainOptions.selectivePostSplit = trainOptions.selectivePostSplitCutOff > 0.0; i += 2; } else if (args[i].equalsIgnoreCase("-deleteSplitters") && (i+1 < args.length)) { String[] toDel = args[i+1].split(" *, *"); trainOptions.deleteSplitters = new HashSet<String>(Arrays.asList(toDel)); i += 2; } else if (args[i].equalsIgnoreCase("-postSplitWithBaseCategory")) { trainOptions.postSplitWithBaseCategory = true; i += 1; } else if (args[i].equalsIgnoreCase("-vPostMarkov") && (i + 1 < args.length)) { int order = Integer.parseInt(args[i + 1]); if (order <= 1) { trainOptions.postPA = false; trainOptions.postGPA = false; } else if (order == 2) { trainOptions.postPA = true; trainOptions.postGPA = false; } else if (order >= 3) { trainOptions.postPA = true; trainOptions.postGPA = true; } i += 2; } else if (args[i].equalsIgnoreCase("-hMarkov") && (i + 1 < args.length)) { int order = Integer.parseInt(args[i + 1]); if (order >= 0) { trainOptions.markovOrder = order; trainOptions.markovFactor = true; } else { trainOptions.markovFactor = false; } i += 2; } else if (args[i].equalsIgnoreCase("-distanceBins") && (i + 1 < args.length)) { int numBins = Integer.parseInt(args[i + 1]); if (numBins <= 1) { distance = false; } else if (numBins == 4) { distance = true; coarseDistance = true; } else if (numBins == 5) { distance = true; coarseDistance = false; } else { throw new IllegalArgumentException("Invalid value for -distanceBin: " + args[i+1]); } i += 2; } else if (args[i].equalsIgnoreCase("-noStop")) { genStop = false; i++; } else if (args[i].equalsIgnoreCase("-nonDirectional")) { directional = false; i++; } else if (args[i].equalsIgnoreCase("-depWeight") && (i + 1 < args.length)) { testOptions.depWeight = Double.parseDouble(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-printPCFGkBest") && (i + 1 < args.length)) { testOptions.printPCFGkBest = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-evalPCFGkBest") && (i + 1 < args.length)) { testOptions.evalPCFGkBest = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-printFactoredKGood") && (i + 1 < args.length)) { testOptions.printFactoredKGood = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-smoothTagsThresh") && (i + 1 < args.length)) { lexOptions.smoothInUnknownsThreshold = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-unseenSmooth") && (i + 1 < args.length)) { testOptions.unseenSmooth = Double.parseDouble(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-fractionBeforeUnseenCounting") && (i + 1 < args.length)) { trainOptions.fractionBeforeUnseenCounting = Double.parseDouble(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-hSelSplitThresh") && (i + 1 < args.length)) { trainOptions.HSEL_CUT = Integer.parseInt(args[i + 1]); trainOptions.hSelSplit = trainOptions.HSEL_CUT > 0; i += 2; } else if (args[i].equalsIgnoreCase("-tagPA")) { trainOptions.tagPA = true; i += 1; } else if (args[i].equalsIgnoreCase("-tagSelSplitCutOff") && (i + 1 < args.length)) { trainOptions.tagSelectiveSplitCutOff = Double.parseDouble(args[i + 1]); trainOptions.tagSelectiveSplit = trainOptions.tagSelectiveSplitCutOff > 0.0; i += 2; } else if (args[i].equalsIgnoreCase("-tagSelPostSplitCutOff") && (i + 1 < args.length)) { trainOptions.tagSelectivePostSplitCutOff = Double.parseDouble(args[i + 1]); trainOptions.tagSelectivePostSplit = trainOptions.tagSelectivePostSplitCutOff > 0.0; i += 2; } else if (args[i].equalsIgnoreCase("-noTagSplit")) { trainOptions.noTagSplit = true; i += 1; } else if (args[i].equalsIgnoreCase("-uwm") && (i + 1 < args.length)) { lexOptions.useUnknownWordSignatures = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-unknownSuffixSize") && (i + 1 < args.length)) { lexOptions.unknownSuffixSize = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-unknownPrefixSize") && (i + 1 < args.length)) { lexOptions.unknownPrefixSize = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-uwModelTrainer") && (i + 1 < args.length)) { lexOptions.uwModelTrainer = args[i+1]; i += 2; } else if (args[i].equalsIgnoreCase("-openClassThreshold") && (i + 1 < args.length)) { trainOptions.openClassTypesThreshold = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-unary") && i+1 < args.length) { trainOptions.markUnary = Integer.parseInt(args[i+1]); i += 2; } else if (args[i].equalsIgnoreCase("-unaryTags")) { trainOptions.markUnaryTags = true; i += 1; } else if (args[i].equalsIgnoreCase("-mutate")) { lexOptions.smartMutation = true; i += 1; } else if (args[i].equalsIgnoreCase("-useUnicodeType")) { lexOptions.useUnicodeType = true; i += 1; } else if (args[i].equalsIgnoreCase("-rightRec")) { trainOptions.rightRec = true; i += 1; } else if (args[i].equalsIgnoreCase("-noRightRec")) { trainOptions.rightRec = false; i += 1; } else if (args[i].equalsIgnoreCase("-preTag")) { testOptions.preTag = true; i += 1; } else if (args[i].equalsIgnoreCase("-forceTags")) { testOptions.forceTags = true; i += 1; } else if (args[i].equalsIgnoreCase("-taggerSerializedFile")) { testOptions.taggerSerializedFile = args[i+1]; i += 2; } else if (args[i].equalsIgnoreCase("-forceTagBeginnings")) { testOptions.forceTagBeginnings = true; i += 1; } else if (args[i].equalsIgnoreCase("-noFunctionalForcing")) { testOptions.noFunctionalForcing = true; i += 1; } else if (args[i].equalsIgnoreCase("-scTags")) { dcTags = false; i += 1; } else if (args[i].equalsIgnoreCase("-dcTags")) { dcTags = true; i += 1; } else if (args[i].equalsIgnoreCase("-basicCategoryTagsInDependencyGrammar")) { trainOptions.basicCategoryTagsInDependencyGrammar = true; i+= 1; } else if (args[i].equalsIgnoreCase("-evalb")) { testOptions.evalb = true; i += 1; } else if (args[i].equalsIgnoreCase("-v") || args[i].equalsIgnoreCase("-verbose")) { testOptions.verbose = true; i += 1; } else if (args[i].equalsIgnoreCase("-outputFilesDirectory") && i+1 < args.length) { testOptions.outputFilesDirectory = args[i+1]; i += 2; } else if (args[i].equalsIgnoreCase("-outputFilesExtension") && i+1 < args.length) { testOptions.outputFilesExtension = args[i+1]; i += 2; } else if (args[i].equalsIgnoreCase("-outputFilesPrefix") && i+1 < args.length) { testOptions.outputFilesPrefix = args[i+1]; i += 2; } else if (args[i].equalsIgnoreCase("-outputkBestEquivocation") && i+1 < args.length) { testOptions.outputkBestEquivocation = args[i+1]; i += 2; } else if (args[i].equalsIgnoreCase("-writeOutputFiles")) { testOptions.writeOutputFiles = true; i += 1; } else if (args[i].equalsIgnoreCase("-printAllBestParses")) { testOptions.printAllBestParses = true; i += 1; } else if (args[i].equalsIgnoreCase("-outputTreeFormat") || args[i].equalsIgnoreCase("-outputFormat")) { testOptions.outputFormat = args[i + 1]; i += 2; } else if (args[i].equalsIgnoreCase("-outputTreeFormatOptions") || args[i].equalsIgnoreCase("-outputFormatOptions")) { testOptions.outputFormatOptions = args[i + 1]; i += 2; } else if (args[i].equalsIgnoreCase("-addMissingFinalPunctuation")) { testOptions.addMissingFinalPunctuation = true; i += 1; } else if (args[i].equalsIgnoreCase("-flexiTag")) { lexOptions.flexiTag = true; i += 1; } else if (args[i].equalsIgnoreCase("-lexiTag")) { lexOptions.flexiTag = false; i += 1; } else if (args[i].equalsIgnoreCase("-useSignatureForKnownSmoothing")) { lexOptions.useSignatureForKnownSmoothing = true; i += 1; } else if (args[i].equalsIgnoreCase("-compactGrammar")) { trainOptions.compactGrammar = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-markFinalStates")) { trainOptions.markFinalStates = args[i + 1].equalsIgnoreCase("true"); i += 2; } else if (args[i].equalsIgnoreCase("-leftToRight")) { trainOptions.leftToRight = args[i + 1].equals("true"); i += 2; } else if (args[i].equalsIgnoreCase("-cnf")) { forceCNF = true; i += 1; } else if(args[i].equalsIgnoreCase("-smoothRules")) { trainOptions.ruleSmoothing = true; trainOptions.ruleSmoothingAlpha = Double.valueOf(args[i+1]); i += 2; } else if (args[i].equalsIgnoreCase("-nodePrune") && i+1 < args.length) { nodePrune = args[i+1].equalsIgnoreCase("true"); i += 2; } else if (args[i].equalsIgnoreCase("-noDoRecovery")) { testOptions.doRecovery = false; i += 1; } else if (args[i].equalsIgnoreCase("-acl03chinese")) { trainOptions.markovOrder = 1; trainOptions.markovFactor = true; // no increment } else if (args[i].equalsIgnoreCase("-wordFunction")) { wordFunction = ReflectionLoading.loadByReflection(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-acl03pcfg")) { doDep = false; doPCFG = true; // lexOptions.smoothInUnknownsThreshold = 30; trainOptions.markUnary = 1; trainOptions.PA = true; trainOptions.gPA = false; trainOptions.tagPA = true; trainOptions.tagSelectiveSplit = false; trainOptions.rightRec = true; trainOptions.selectiveSplit = true; trainOptions.selectiveSplitCutOff = 400.0; trainOptions.markovFactor = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; lexOptions.useUnknownWordSignatures = 2; lexOptions.flexiTag = true; // DAN: Tag double-counting is BAD for PCFG-only parsing dcTags = false; // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-jenny")) { doDep = false; doPCFG = true; // lexOptions.smoothInUnknownsThreshold = 30; trainOptions.markUnary = 1; trainOptions.PA = false; trainOptions.gPA = false; trainOptions.tagPA = false; trainOptions.tagSelectiveSplit = false; trainOptions.rightRec = true; trainOptions.selectiveSplit = false; // trainOptions.selectiveSplitCutOff = 400.0; trainOptions.markovFactor = false; // trainOptions.markovOrder = 2; trainOptions.hSelSplit = false; lexOptions.useUnknownWordSignatures = 2; lexOptions.flexiTag = true; // DAN: Tag double-counting is BAD for PCFG-only parsing dcTags = false; // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-goodPCFG")) { doDep = false; doPCFG = true; // op.lexOptions.smoothInUnknownsThreshold = 30; trainOptions.markUnary = 1; trainOptions.PA = true; trainOptions.gPA = false; trainOptions.tagPA = true; trainOptions.tagSelectiveSplit = false; trainOptions.rightRec = true; trainOptions.selectiveSplit = true; trainOptions.selectiveSplitCutOff = 400.0; trainOptions.markovFactor = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; lexOptions.useUnknownWordSignatures = 2; lexOptions.flexiTag = true; // DAN: Tag double-counting is BAD for PCFG-only parsing dcTags = false; String[] delSplit = { "-deleteSplitters", "VP^NP,VP^VP,VP^SINV,VP^SQ" }; if (this.setOptionFlag(delSplit, 0) != 2) { System.err.println("Error processing deleteSplitters"); } // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-linguisticPCFG")) { doDep = false; doPCFG = true; // op.lexOptions.smoothInUnknownsThreshold = 30; trainOptions.markUnary = 1; trainOptions.PA = true; trainOptions.gPA = false; trainOptions.tagPA = true; // on at the moment, but iffy trainOptions.tagSelectiveSplit = false; trainOptions.rightRec = false; // not for linguistic trainOptions.selectiveSplit = true; trainOptions.selectiveSplitCutOff = 400.0; trainOptions.markovFactor = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; lexOptions.useUnknownWordSignatures = 5; // different from acl03pcfg lexOptions.flexiTag = false; // different from acl03pcfg // DAN: Tag double-counting is BAD for PCFG-only parsing dcTags = false; // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-ijcai03")) { doDep = true; doPCFG = true; trainOptions.markUnary = 0; trainOptions.PA = true; trainOptions.gPA = false; trainOptions.tagPA = false; trainOptions.tagSelectiveSplit = false; trainOptions.rightRec = false; trainOptions.selectiveSplit = true; trainOptions.selectiveSplitCutOff = 300.0; trainOptions.markovFactor = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; trainOptions.compactGrammar = 0; /// cdm: May 2005 compacting bad for factored? lexOptions.useUnknownWordSignatures = 2; lexOptions.flexiTag = false; dcTags = true; // op.nodePrune = true; // cdm: May 2005: this doesn't help // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-goodFactored")) { doDep = true; doPCFG = true; trainOptions.markUnary = 0; trainOptions.PA = true; trainOptions.gPA = false; trainOptions.tagPA = false; trainOptions.tagSelectiveSplit = false; trainOptions.rightRec = false; trainOptions.selectiveSplit = true; trainOptions.selectiveSplitCutOff = 300.0; trainOptions.markovFactor = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; trainOptions.compactGrammar = 0; /// cdm: May 2005 compacting bad for factored? lexOptions.useUnknownWordSignatures = 5; // different from ijcai03 lexOptions.flexiTag = false; dcTags = true; // op.nodePrune = true; // cdm: May 2005: this doesn't help // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-chineseFactored")) { // Single counting tag->word rewrite is also much better for Chinese // Factored. Bracketing F1 goes up about 0.7%. dcTags = false; lexOptions.useUnicodeType = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; trainOptions.markovFactor = true; trainOptions.HSEL_CUT = 50; // trainOptions.openClassTypesThreshold=1; // so can get unseen punctuation // trainOptions.fractionBeforeUnseenCounting=0.0; // so can get unseen punctuation // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-arabicFactored")) { doDep = true; doPCFG = true; dcTags = false; // "false" seems to help Arabic about 0.1% F1 trainOptions.markovFactor = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; trainOptions.HSEL_CUT = 75; // 75 bit better than 50, 100 a bit worse trainOptions.PA = true; trainOptions.gPA = false; trainOptions.selectiveSplit = true; trainOptions.selectiveSplitCutOff = 300.0; trainOptions.markUnary = 1; // Helps PCFG and marginally factLB // trainOptions.compactGrammar = 0; // Doesn't seem to help or only 0.05% F1 lexOptions.useUnknownWordSignatures = 9; lexOptions.unknownPrefixSize = 1; lexOptions.unknownSuffixSize = 1; testOptions.MAX_ITEMS = 500000; // Arabic sentences are long enough that this helps a fraction // don't increment i so it gets language specific stuff as well } else if (args[i].equalsIgnoreCase("-frenchFactored")) { doDep = true; doPCFG = true; dcTags = false; //wsg2011: Setting to false improves F1 by 0.5% trainOptions.markovFactor = true; trainOptions.markovOrder = 2; trainOptions.hSelSplit = true; trainOptions.HSEL_CUT = 75; trainOptions.PA = true; trainOptions.gPA = false; trainOptions.selectiveSplit = true; trainOptions.selectiveSplitCutOff = 300.0; trainOptions.markUnary = 0; //Unary rule marking bad for french..setting to 0 gives +0.3 F1 lexOptions.useUnknownWordSignatures = 1; lexOptions.unknownPrefixSize = 1; lexOptions.unknownSuffixSize = 2; } else if (args[i].equalsIgnoreCase("-chinesePCFG")) { trainOptions.markovOrder = 2; trainOptions.markovFactor = true; trainOptions.HSEL_CUT = 5; trainOptions.PA = true; trainOptions.gPA = true; trainOptions.selectiveSplit = false; doDep = false; doPCFG = true; // Single counting tag->word rewrite is also much better for Chinese PCFG // Bracketing F1 is up about 2% and tag accuracy about 1% (exact by 6%) dcTags = false; // no increment } else if (args[i].equalsIgnoreCase("-printTT") && (i+1 < args.length)) { trainOptions.printTreeTransformations = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-printAnnotatedRuleCounts")) { trainOptions.printAnnotatedRuleCounts = true; i++; } else if (args[i].equalsIgnoreCase("-printAnnotatedStateCounts")) { trainOptions.printAnnotatedStateCounts = true; i++; } else if (args[i].equalsIgnoreCase("-printAnnotated") && (i + 1 < args.length)) { try { trainOptions.printAnnotatedPW = tlpParams.pw(new FileOutputStream(args[i + 1])); } catch (IOException ioe) { trainOptions.printAnnotatedPW = null; } i += 2; } else if (args[i].equalsIgnoreCase("-printBinarized") && (i + 1 < args.length)) { try { trainOptions.printBinarizedPW = tlpParams.pw(new FileOutputStream(args[i + 1])); } catch (IOException ioe) { trainOptions.printBinarizedPW = null; } i += 2; } else if (args[i].equalsIgnoreCase("-printStates")) { trainOptions.printStates = true; i++; } else if (args[i].equalsIgnoreCase("-preTransformer") && (i + 1 < args.length)) { String[] classes = args[i + 1].split(","); i += 2; if (classes.length == 1) { trainOptions.preTransformer = ReflectionLoading.loadByReflection(classes[0], this); } else if (classes.length > 1) { CompositeTreeTransformer composite = new CompositeTreeTransformer(); trainOptions.preTransformer = composite; for (String clazz : classes) { TreeTransformer transformer = ReflectionLoading.loadByReflection(clazz, this); composite.addTransformer(transformer); } } } else if (args[i].equalsIgnoreCase("-taggedFiles") && (i + 1 < args.length)) { trainOptions.taggedFiles = args[i + 1]; i += 2; } else if (args[i].equalsIgnoreCase("-predictSplits")) { // This is an experimental (and still in development) // reimplementation of Berkeley's state splitting grammar. trainOptions.predictSplits = true; trainOptions.compactGrammar = 0; i++; } else if (args[i].equalsIgnoreCase("-splitCount")) { trainOptions.splitCount = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-splitRecombineRate")) { trainOptions.splitRecombineRate = Double.parseDouble(args[i + 1]); i +=2; } else if (args[i].equalsIgnoreCase("-splitTrainingThreads")) { trainOptions.splitTrainingThreads = Integer.parseInt(args[i + 1]); i +=2; } else if (args[i].equalsIgnoreCase("-evals")) { testOptions.evals = StringUtils.stringToProperties(args[i+1], testOptions.evals); i += 2; } else if (args[i].equalsIgnoreCase("-fastFactoredCandidateMultiplier")) { testOptions.fastFactoredCandidateMultiplier = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-fastFactoredCandidateAddend")) { testOptions.fastFactoredCandidateAddend = Integer.parseInt(args[i + 1]); i += 2; } else if (args[i].equalsIgnoreCase("-simpleBinarizedLabels")) { trainOptions.simpleBinarizedLabels = true; i += 1; } else if (args[i].equalsIgnoreCase("-noRebinarization")) { trainOptions.noRebinarization = true; i += 1; } return i; } public static class LexOptions implements Serializable { /** * Whether to use suffix and capitalization information for unknowns. * Within the BaseLexicon model options have the following meaning: * 0 means a single unknown token. 1 uses suffix, and capitalization. * 2 uses a variant (richer) form of signature. Good. * Use this one. Using the richer signatures in versions 3 or 4 seems * to have very marginal or no positive value. * 3 uses a richer form of signature that mimics the NER word type * patterns. 4 is a variant of 2. 5 is another with more English * specific morphology (good for English unknowns!). * 6-9 are options for Arabic. 9 codes some patterns for numbers and * derivational morphology, but also supports unknownPrefixSize and * unknownSuffixSize. * For German, 0 means a single unknown token, and non-zero means to use * capitalization of first letter and a suffix of length * unknownSuffixSize. */ public int useUnknownWordSignatures = 0; /** * Words more common than this are tagged with MLE P(t|w). Default 100. The * smoothing is sufficiently slight that changing this has little effect. * But set this to 0 to be able to use the parser as a vanilla PCFG with * no smoothing (not as a practical parser but for exposition or debugging). */ public int smoothInUnknownsThreshold = 100; /** * Smarter smoothing for rare words. */ public boolean smartMutation = false; /** * Make use of unicode code point types in smoothing. */ public boolean useUnicodeType = false; /** For certain Lexicons, a certain number of word-final letters are * used to subclassify the unknown token. This gives the number of * letters. */ public int unknownSuffixSize = 1; /** For certain Lexicons, a certain number of word-initial letters are * used to subclassify the unknown token. This gives the number of * letters. */ public int unknownPrefixSize = 1; /** * Trainer which produces model for unknown words that the lexicon * should use */ public String uwModelTrainer; // = null; /* If this option is false, then all words that were seen in the training * data (even once) are constrained to only have seen tags. That is, * mle is used for the lexicon. * If this option is true, then if a word has been seen more than * smoothInUnknownsThreshold, then it will still only get tags with which * it has been seen, but rarer words will get all tags for which the * unknown word model (or smart mutation) does not give a score of -Inf. * This will normally be all open class tags. * If floodTags is invoked by the parser, all other tags will also be * given a minimal non-zero, non-infinite probability. */ public boolean flexiTag = false; /** Whether to use signature rather than just being unknown as prior in * known word smoothing. Currently only works if turned on for English. */ public boolean useSignatureForKnownSmoothing; private static final long serialVersionUID = 2805351374506855632L; private static final String[] params = { "useUnknownWordSignatures", "smoothInUnknownsThreshold", "smartMutation", "useUnicodeType", "unknownSuffixSize", "unknownPrefixSize", "flexiTag", "useSignatureForKnownSmoothing"}; @Override public String toString() { return params[0] + " " + useUnknownWordSignatures + "\n" + params[1] + " " + smoothInUnknownsThreshold + "\n" + params[2] + " " + smartMutation + "\n" + params[3] + " " + useUnicodeType + "\n" + params[4] + " " + unknownSuffixSize + "\n" + params[5] + " " + unknownPrefixSize + "\n" + params[6] + " " + flexiTag + "\n" + params[7] + " " + useSignatureForKnownSmoothing + "\n"; } public void readData(BufferedReader in) throws IOException { for (int i = 0; i < params.length; i++) { String line = in.readLine(); int idx = line.indexOf(' '); String key = line.substring(0, idx); String value = line.substring(idx + 1); if ( ! key.equalsIgnoreCase(params[i])) { System.err.println("Yikes!!! Expected " + params[i] + " got " + key); } switch (i) { case 0: useUnknownWordSignatures = Integer.parseInt(value); break; case 1: smoothInUnknownsThreshold = Integer.parseInt(value); break; case 2: smartMutation = Boolean.parseBoolean(value); break; case 3: useUnicodeType = Boolean.parseBoolean(value); break; case 4: unknownSuffixSize = Integer.parseInt(value); break; case 5: unknownPrefixSize = Integer.parseInt(value); break; case 6: flexiTag = Boolean.parseBoolean(value); } } } } // end class LexOptions public LexOptions lexOptions = new LexOptions(); /** * The treebank-specific parser parameters to use. */ public TreebankLangParserParams tlpParams; /** * @return The treebank language pack for the treebank the parser * is trained on. */ public TreebankLanguagePack langpack() { return tlpParams.treebankLanguagePack(); } /** * Forces parsing with strictly CNF grammar -- unary chains are converted * to XP&YP symbols and back */ public boolean forceCNF = false; /** * Do a PCFG parse of the sentence. If both variables are on, * also do a combined parse of the sentence. */ public boolean doPCFG = true; /** * Do a dependency parse of the sentence. */ public boolean doDep = true; /** * if true, any child can be the head (seems rather bad!) */ public boolean freeDependencies = false; /** * Whether dependency grammar considers left/right direction. Good. */ public boolean directional = true; public boolean genStop = true; public boolean useSmoothTagProjection = false; public boolean useUnigramWordSmoothing = false; /** * Use distance bins in the dependency calculations */ public boolean distance = true; /** * Use coarser distance (4 bins) in dependency calculations */ public boolean coarseDistance = false; /** * "double count" tags rewrites as word in PCFG and Dep parser. Good for * combined parsing only (it used to not kick in for PCFG parsing). This * option is only used at Test time, but it is now in Options, so the * correct choice for a grammar is recorded by a serialized parser. * You should turn this off for a vanilla PCFG parser. */ public boolean dcTags = true; /** * If true, inside the factored parser, remove any node from the final * chosen tree which improves the PCFG score. This was added as the * dependency factor tends to encourage 'deep' trees. */ public boolean nodePrune = false; public TrainOptions trainOptions = new TrainOptions(); /** * Note that the TestOptions is transient. This means that whatever * options get set at creation time are forgotten when the parser is * serialized. If you want an option to be remembered when the * parser is reloaded, put it in either TrainOptions or in this * class itself. */ public transient TestOptions testOptions = new TestOptions(); /** * A function that maps words used in training and testing to new * words. For example, it could be a function to lowercase text, * such as edu.stanford.nlp.util.LowercaseFunction (which makes the * parser case insensitive). This function is applied in * LexicalizedParserQuery.parse and in the training methods which * build a new parser. */ public Function<String, String> wordFunction = null; /** * Making the TestOptions transient means it won't even be * constructed when you deserialize an Options, so we need to * construct it on our own when deserializing */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); testOptions = new TestOptions(); } public void display() { // try { logger.trace("Options parameters:"); writeData(); /* } catch (IOException e) { e.printStackTrace(); }*/ } public void writeData() {//throws IOException { StringBuilder sb = new StringBuilder(); sb.append(lexOptions.toString()); sb.append("parserParams ").append(tlpParams.getClass().getName()).append("\n"); sb.append("forceCNF ").append(forceCNF).append("\n"); sb.append("doPCFG ").append(doPCFG).append("\n"); sb.append("doDep ").append(doDep).append("\n"); sb.append("freeDependencies ").append(freeDependencies).append("\n"); sb.append("directional ").append(directional).append("\n"); sb.append("genStop ").append(genStop).append("\n"); sb.append("distance ").append(distance).append("\n"); sb.append("coarseDistance ").append(coarseDistance).append("\n"); sb.append("dcTags ").append(dcTags).append("\n"); sb.append("nPrune ").append(nodePrune).append("\n"); logger.trace(sb.toString()); } /** * Populates data in this Options from the character stream. * @param in The Reader * @throws IOException If there is a problem reading data */ public void readData(BufferedReader in) throws IOException { String line, value; // skip old variables if still present lexOptions.readData(in); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); try { tlpParams = (TreebankLangParserParams) Class.forName(value).newInstance(); } catch (Exception e) { IOException ioe = new IOException("Problem instantiating parserParams: " + line); ioe.initCause(e); throw ioe; } line = in.readLine(); // ensure backwards compatibility if (line.matches("^forceCNF.*")) { value = line.substring(line.indexOf(' ') + 1); forceCNF = Boolean.parseBoolean(value); line = in.readLine(); } value = line.substring(line.indexOf(' ') + 1); doPCFG = Boolean.parseBoolean(value); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); doDep = Boolean.parseBoolean(value); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); freeDependencies = Boolean.parseBoolean(value); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); directional = Boolean.parseBoolean(value); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); genStop = Boolean.parseBoolean(value); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); distance = Boolean.parseBoolean(value); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); coarseDistance = Boolean.parseBoolean(value); line = in.readLine(); value = line.substring(line.indexOf(' ') + 1); dcTags = Boolean.parseBoolean(value); line = in.readLine(); if ( ! line.matches("^nPrune.*")) { throw new RuntimeException("Expected nPrune, found: " + line); } value = line.substring(line.indexOf(' ') + 1); nodePrune = Boolean.parseBoolean(value); line = in.readLine(); // get rid of last line if (line.length() != 0) { throw new RuntimeException("Expected blank line, found: " + line); } } private static final long serialVersionUID = 4L; } // end class Options
chbrown/stanford-parser
edu/stanford/nlp/parser/lexparser/Options.java
Java
gpl-2.0
45,340
<?php $ajax= get_input('ajax',0); $idGrupo = get_input('id'); $grupo = new ElggGrupoInvestigacion($idGrupo); $title = $grupo->name . ": Administración de Roles"; $miembrosGrupo = elgg_get_miembros_grupo_investigacion($grupo); $params['title'] = $title; $params['grupo'] = array( 'nombre' => $grupo->name, 'guid' => $grupo->guid, 'rol_user' => $rol, ); $params['ajax']=$ajax; $params['buttons'] = array(); $params['miembros'] = $miembrosGrupo; $content= elgg_view('grupo_investigacion/profile/header', $params); $content.=elgg_view('grupo_investigacion/roles/admin_roles', $params); $vars = array('content' => $content); $body = elgg_view_layout('one_sidebar', $vars); echo elgg_view_page($title, $body); /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */
jonreycas/enjambre
mod/grupo_investigacion/pages/grupo_investigacion/administrar_roles.php
PHP
gpl-2.0
931
#ifndef TRUE #define TRUE 1 #endif //TRUE #ifndef FALSE #define FALSE 0 #endif //FALSE #include <plib/ssg.h> #include <plib/sg.h> #include <raceman.h> #include <track.h> #include "grscene.h" typedef struct LightInfo { int index; ssgVtxTable *light; //ssgSimpleState* onState; //ssgSimpleState* offState; ssgStateSelector *states; struct LightInfo *next; } tLightInfo; typedef struct TrackLights { tLightInfo *st_red; tLightInfo *st_green; tLightInfo *st_yellow; tLightInfo *st_green_st; } tTrackLights; typedef struct StateList { ssgSimpleState *state; struct StateList *next; } tStateList; static tStateList *statelist; static ssgBranch *lightBranch; static tTrackLights trackLights; //static void setOnOff( tLightInfo *light, char onoff ); static void calcNorm( sgVec3 topleft, sgVec3 bottomright, sgVec3 *result ) { (*result)[ 0 ] = bottomright[ 1 ] - topleft[ 1 ]; (*result)[ 1 ] = topleft[ 0 ] - bottomright[ 0 ]; (*result)[ 2 ] = 0.0f; } static ssgSimpleState* createState( char const *filename ) { tStateList *current = statelist; while( current && current->state ) { if( strcmp( filename, current->state->getTextureFilename() ) == 0 ) { return current->state; } current = current->next; } current = (tStateList*)malloc( sizeof( tStateList ) ); current->state = new ssgSimpleState(); if( !current->state ) { free( current ); return NULL; } current->state->disable( GL_LIGHTING ); current->state->enable( GL_BLEND ); current->state->enable( GL_CULL_FACE ); current->state->enable( GL_TEXTURE_2D ); current->state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE ); current->state->setTexture( filename, TRUE, TRUE, TRUE ); current->state->ref(); current->next = statelist; statelist = current; return current->state; } static void deleteStates() { tStateList *current = statelist; tStateList *next; while( current ) { next = current->next; if( current->state ) { current->state->deRef(); delete current->state; } free( current ); current = next; } } static void addLight( tGraphicLightInfo *info, tTrackLights *lights, ssgBranch *parent ) { tLightInfo *trackLight; int states = 2; ssgVertexArray *vertexArray = new ssgVertexArray( 4 ); ssgNormalArray *normalArray = new ssgNormalArray( 4 ); ssgColourArray *colourArray = new ssgColourArray( 4 ); ssgTexCoordArray *texArray = new ssgTexCoordArray( 4 ); sgVec3 vertex; sgVec3 normal; sgVec4 colour; sgVec2 texcoord; colour[ 0 ] = info->red; colour[ 1 ] = info->green; colour[ 2 ] = info->blue; colour[ 3 ] = 1.0f; colourArray->add( colour ); colourArray->add( colour ); colourArray->add( colour ); colourArray->add( colour ); vertex[ 0 ] = info->topleft.x; vertex[ 1 ] = info->topleft.y; vertex[ 2 ] = info->topleft.z; vertexArray->add( vertex ); vertex[ 2 ] = info->bottomright.z; vertexArray->add( vertex ); vertex[ 0 ] = info->bottomright.x; vertex[ 1 ] = info->bottomright.y; vertex[ 2 ] = info->topleft.z; //? vertexArray->add( vertex ); vertex[ 2 ] = info->topleft.z; vertex[ 2 ] = info->bottomright.z; //? vertexArray->add( vertex ); calcNorm( vertexArray->get( 0 ), vertexArray->get( 2 ), &normal ); normalArray->add( normal ); normalArray->add( normal ); normalArray->add( normal ); normalArray->add( normal ); texcoord[ 0 ] = 0.0f; texcoord[ 1 ] = 0.0f; texArray->add( texcoord ); texcoord[ 0 ] = 0.0f; texcoord[ 1 ] = 1.0f; texArray->add( texcoord ); texcoord[ 0 ] = 1.0f; texcoord[ 1 ] = 0.0f; texArray->add( texcoord ); texcoord[ 0 ] = 1.0f; texcoord[ 1 ] = 1.0f; texArray->add( texcoord ); if( info->role == GR_TRACKLIGHT_START_YELLOW || info->role == GR_TRACKLIGHT_POST_YELLOW || info->role == GR_TRACKLIGHT_POST_GREEN || info->role == GR_TRACKLIGHT_POST_RED || info->role == GR_TRACKLIGHT_POST_BLUE || info->role == GR_TRACKLIGHT_POST_WHITE || info->role == GR_TRACKLIGHT_PIT_BLUE ) { states = 3; } trackLight = (tLightInfo*)malloc( sizeof( tLightInfo ) ); trackLight->index = info->index; trackLight->light = new ssgVtxTable( GL_TRIANGLE_STRIP, vertexArray, normalArray, texArray, colourArray ); trackLight->states = new ssgStateSelector( states ); trackLight->states->setStep( 0, createState( info->offTexture ) ); trackLight->states->setStep( 1 + MAX( states - 2, info->index % 2 ), createState( info->onTexture ) ); if( states == 3 ) trackLight->states->setStep( 1 + ( info->index + 1 ) % 2, createState( info->offTexture ) ); trackLight->states->selectStep( 0 ); trackLight->light->setState( trackLight->states ); //trackLight->onState = createState( info->onTexture ); //trackLight->offState = createState( info->offTexture ); switch( info->role ) { case GR_TRACKLIGHT_START_RED: trackLight->next = lights->st_red; lights->st_red = trackLight; break; case GR_TRACKLIGHT_START_GREEN: trackLight->next = lights->st_green; lights->st_green = trackLight; break; case GR_TRACKLIGHT_START_GREENSTART: trackLight->next = lights->st_green_st; lights->st_green_st = trackLight; break; case GR_TRACKLIGHT_START_YELLOW: trackLight->next = lights->st_yellow; lights->st_yellow = trackLight; break; case GR_TRACKLIGHT_POST_YELLOW: case GR_TRACKLIGHT_POST_GREEN: case GR_TRACKLIGHT_POST_RED: case GR_TRACKLIGHT_POST_BLUE: case GR_TRACKLIGHT_POST_WHITE: case GR_TRACKLIGHT_PIT_RED: case GR_TRACKLIGHT_PIT_GREEN: case GR_TRACKLIGHT_PIT_BLUE: default: delete trackLight->light; free( trackLight ); return; } parent->addKid( trackLight->light ); } static void addLights( tTrackLights *lights, ssgBranch *parent ) { int xx; for( xx = 0; xx < grTrack->graphic.nb_lights; ++xx ) addLight( &(grTrack->graphic.lights[ xx ]), lights, parent ); } static void manageStartLights( tTrackLights *startlights, tSituation *s, char phase ) { static int onoff_red_index = -1; static char onoff_red = FALSE; static char onoff_green = FALSE; static char onoff_green_st = FALSE; static char onoff_yellow = FALSE; static char onoff_phase = 1; char onoff; int current_index; char active = s->currentTime >= 0.0f && ( s->_totTime < 0.0f || s->currentTime < s->_totTime ); tLightInfo *current; if( s->currentTime < 0.0f ) current_index = (int)floor( s->currentTime * -10.0f ); else current_index = -1; current = startlights->st_red; onoff = !active && s->_raceType != RM_TYPE_RACE; if( current_index != onoff_red_index || onoff != onoff_red ) { onoff_red_index = current_index; onoff_red = onoff; while( current ) { //setOnOff( current, onoff || ( current_index >= 0 && current_index < current->index ) ); current->states->selectStep( ( onoff || ( current_index >= 0 && current_index < current->index ) ) ? 1 : 0 ); current = current->next; } } current = startlights->st_green; onoff = active && s->_raceType != RM_TYPE_RACE; if( onoff_green != onoff ) { onoff_green = onoff; while( current ) { //setOnOff( current, onoff ); current->states->selectStep( onoff ? 1 : 0 ); current = current->next; } } current = startlights->st_green_st; onoff = active && ( s->_raceType != RM_TYPE_RACE || s->currentTime < 30.0f ); if( onoff_green_st != onoff ) { onoff_green_st = onoff; while( current ) { //setOnOff( current, onoff ); current->states->selectStep( onoff ? 1 : 0 ); current = current->next; } } current = startlights->st_yellow; onoff = FALSE; if( onoff_yellow != onoff || ( onoff && phase != onoff_phase ) ) { onoff_yellow = onoff; while( current ) { //setOnOff( current, onoff ? ( phase + current->index ) % 2 : 0 ); current->states->selectStep( onoff ? phase : 0 ); current = current->next; } } onoff_phase = phase; } /*static void setOnOff( tLightInfo *light, char onoff ) { ssgSimpleState *sstate; if( !light ) return; sstate = onoff ? light->onState : light->offState; if( light->light != NULL && light->light->getState() != sstate ) light->light->setState( sstate ); }*/ void grTrackLightInit() { statelist = NULL; lightBranch = new ssgBranch(); TrackLightAnchor->addKid( lightBranch ); memset( &trackLights, 0, sizeof( tTrackLights ) ); addLights( &trackLights, lightBranch ); } void grTrackLightUpdate( tSituation *s ) { char phase = ( (int)floor( fmod( s->currentTime + 120.0f, (double)0.3f ) / 0.3f ) % 2 ) + 1; manageStartLights( &trackLights, s, phase ); } void grTrackLightShutdown() { TrackLightAnchor->removeAllKids(); //lightBranch->removeAllKids(); /*delete lightBranch;*/ lightBranch = NULL; deleteStates(); }
xy008areshsu/speed-dreams-2
src/modules/graphic/ssggraph/grtracklight.cpp
C++
gpl-2.0
8,533
define(['jquery','config','base','ajax','checkInput','serializeJson'],function($,config,base,AjaxFunUtils){ var defaultAddr = ''; var init = function(){ getAddress(defaultAddr); }; //加载模板 var loadhtml = function(){ var telhtml = '<div id="addressbox" class="addressbox">'+ '<form id="addressform" method="post">'+ '<div id="add_headerbox" class="headerbox">'+ '<div class="rowbox searchbox">'+ '<div class="top_l"> <a href="javascript:void(0);" id="back-address" class="back-address rel" data-level="0"> <span class="b_ico ico-back-h"></span> </a> </div>'+ '<div class="row-flex1 text-center h2_title">收货地址管理</div>'+ '</div>'+ '<div id="address_cont" class="address_cont">'+ '<ul id="addressedit" class="jsbox f16 color-333 jsbox_mt0" style="display:none">'+ '<li id="address_row" class="rowbox">'+ '<div class="row-flex1">'+ '<p id="add_str_text">广东省广州市天河区</p>'+ '<p class="f12 color-999 edit_text">所在地区</p>'+ '<input id="add_str" name="add_str" type="hidden" />'+ '<input id="add_ids" name="add_ids" type="hidden" />'+ '</div>'+ '<div class="ico ico-jt mt-10"></div>'+ '</li>'+ '<li id="townSelRow" class="rowbox">'+ '<div class="row-flex1">'+ '<input id="add_str_2" class="noborder edit_input" name="add_str_2" type="text" placeholder="请选择街道" style="padding-left:0" readonly />'+ '<p class="f12 color-999 edit_text">街道</p>'+ '</div>'+ '<div class="ico ico-jt mt-10"></div>'+ '</li>'+ '<li class="rowbox li_edit">'+ '<div class="row-flex1">'+ '<input id="add_more" name="add_more" type="text" value="" placeholder="请输入详细地址" class="noborder edit_input" style="padding-left:0" data-validate="isempty" />'+ '<p class="f12 color-999 edit_text">详细地址</p>'+ '</div>'+ '<div class="ico ico-jt mt-10"></div>'+ '</li>'+ '<li class="rowbox li_edit">'+ '<div class="row-flex1">'+ '<input id="addressee" name="addressee" type="text" value="" placeholder="请输入收货人姓名" class="noborder edit_input" style="padding-left:0" data-validate="isempty" />'+ '<p class="f12 color-999 edit_text">收货人姓名</p>'+ '</div>'+ '<div class="ico ico-jt mt-10"></div>'+ '</li>'+ '<li class="rowbox li_edit">'+ '<div class="row-flex1">'+ '<input type="text" id="cellphone" name="cellphone" value="" placeholder="请输入收货人手机号码" class="noborder edit_input" style="padding-left:0" data-validate="Mobile" />'+ '<p class="f12 color-999 edit_text">收货人手机号码</p>'+ '</div>'+ '<div class="ico ico-jt mt-10"></div>'+ '</li>'+ '<li class="rowbox li_edit">'+ '<div class="row-flex1">'+ '<input type="text" id="zip" name="zip" value="" placeholder="请输入邮编" class="noborder edit_input" style="padding-left:0" />'+ '<p class="f12 color-999 edit_text">邮编</p>'+ '</div>'+ '<div class="ico ico-jt mt-10"></div>'+ '</li>'+ '<li class="rowbox" for="sedefault">'+ '<div class="row-flex1">'+ '<label><input type="checkbox" name="sedefault" id="sedefault" style="width:20px;padding:0; margin-bottom:-10px"/>设置为默认收货地址</label>'+ '<p class="f12 color-999 edit_text">默认收货地址</p>'+ '</div>'+ '<div class="ico ico-jt mt-10"></div>'+ '</li>'+ '</ul>'+ '<ul id="townSelRow_list" class="jsbox jsbox_mt0" style="display:none"></ul>'+ '<div id="divsionSelect" style="display:none">'+ '<ul id="selected" class="jsbox jsbox_mt0" style="display:none"></ul>'+ '<ul id="forselect" class="jsbox jsbox_mt0"></ul>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="footerbox rowbox" style="padding:10px 0;z-index:99999">'+ '<input id="addrid_edt" name="addrid" type="hidden" />'+ '<div class="row-flex1 text-left">'+ '<button id="delBtn" type="button" class="btn w150">删除</button>'+ '</div>'+ '<div class="row-flex1 text-right">'+ '<button type="button" class="btn btn-danger w150 address_sub_btn">保存</button>'+ '</div>'+ '</div>'+ '</form>'+ '</div>'; $("body").append(telhtml); var bodyh=config.base.getHeightBody(); $("#add_headerbox").css({"height":bodyh,"z-index":99998}); $("#address_cont").css({"height":bodyh-60}); }; //添加,编辑,删除收货地址 var addedtAddress = function(opt){ //加载模板 loadhtml(); //加载,编辑地址 if(opt.act == 'add'){ $("#add_headerbox").addClass("address_add"); //省级地址获取 siondatalist(); //提交绑定 subaddress({act:opt.act}); }else{ $("#add_headerbox").addClass("address_edt"); //编辑提取数据 edtaddress({ act:opt.act, addrid:opt.addrid, callback:function(res3){ //提交绑定 subaddress({act:'edt'}); } }); } //被选中li selectedclik(); //所在地区行click address_row(); //街道选择 townSelRow(); //详细地址,收货人姓名等 $("#addressedit").on("click",".li_edit",function(){ $(this).addClass("li_edit_current"); $(this).siblings(".li_edit").removeClass("li_edit_current"); $(this).find(".edit_input").focus(); }); //关闭地址弹框 $("#back-address").on("click",function(){ var level = $(this).attr("data-level"); var stateid = $(this).attr("data-state"); var cityid = $(this).attr("data-city"); if(level == 0 || level == 3){ $("#addressbox").remove(); }else if(level == 1){ if(opt.act == 'add'){ //省级地址获取 siondatalist(); $(this).attr("data-level",0); $("#selected").html('').hide(); }else{ $(this).attr("data-level",0); $("#addressedit").show(); $("#divsionSelect").hide(); } }else if(level == 2){ $(this).attr("data-level",1); $("#selected").find(".li_click").each(function(index, element) { var li_level = $(this).attr("data-level"); if(li_level == 2){ $(this).remove(); } }); //市级地址获取 getcityaddress({thisId:stateid}); } }); }; var selectedclik = function(){ //被选中li $("#selected").on("click",'.li_click',function(){ var parentid = $(this).attr("data-parentid"); var level = $(this).attr("data-level"); $("#back-address").attr("data-level",level-1); if(parentid > 0){ getcityaddress({thisId:parentid}); $(this).remove(); }else{ siondatalist(); $("#selected").html('').hide(); } $("#add_str_2").attr("data-id",''); $("#add_str_2").val(''); $("#townSelRow_list").hide(); $("#divsionSelect").show(); $("#addressedit").hide(); }) }; //所在地区行click var address_row = function(){ //所在地区行click $("#address_row").off("click").on("click",function(){ var state = $(this).attr("data-state"); var city = $(this).attr("data-city"); var county = $(this).attr("data-county"); $("#back-address").attr("data-level",2); if(state > 0){ $("#selected").html(''); getdataaddress({ callback:function(res3){ $.each(res3.data,function(index,ooo){ if(ooo.id == state){ var lihtml3 = '<li class="li_click" data-level="'+ooo.level+'" data-name="'+ooo.name+'" data-id="'+ooo.id+'" data-parentid="0">'+ooo.name+'</li>' $("#selected").append(lihtml3); return; } }); getdataaddress({ upid:state, callback:function(res3){ $.each(res3.data,function(index,ooo){ if(ooo.id == city){ var lihtml3 = '<li class="li_click" data-level="'+ooo.level+'" data-name="'+ooo.name+'" data-id="'+ooo.id+'" data-parentid="'+state+'">'+ooo.name+'</li>' $("#selected").append(lihtml3); return; } }); getdataaddress({ upid:city, callback:function(res3){ if(res3.data.length<=0){ $("#forselect").hide(); }else{ $("#forselect").show(); } var lihtml3 = ''; $.each(res3.data,function(index,ooo){ lihtml3 += '<li class="li_click" data-level="'+ooo.level+'" data-name="'+ooo.name+'" data-id="'+ooo.id+'" data-parentid="'+city+'">'+ooo.name+'</li>' }); $("#forselect").html(lihtml3); } }); } }); } }) $("#divsionSelect,#selected").show(); $("#addressedit").hide(); forselectclick(); }else{ //省级地址获取 siondatalist(); //提交绑定 subaddress({act:'edt'}); } }) }; //街道选择 var townSelRow = function(){ //街道click $("#townSelRow").off("click").on("click",function(e){ var upid = $(this).attr("data-townid"); if(upid<=0){ return false; } getdataaddress({ upid:upid, callback:function(res){ var lihtml = ''; $.each(res.data,function(index,o){ lihtml += '<li class="li_click" data-level="'+o.level+'" data-name="'+o.name+'" data-id="'+o.id+'" data-isleaf="0">'+o.name+'</li>'; }); $("#townSelRow_list").html(lihtml).show(); $("#divsionSelect").hide(); $("#addressedit").hide(); $("#townSelRow_list").off("click").on("click",'.li_click',function(){ var thisname = $(this).attr("data-name"); var thisid = $(this).attr("data-id"); $("#add_str_2").attr("data-id",thisid); $("#add_str_2").val(thisname); var newadd_ids = $("#address_row").attr("data-state")+"_"+$("#address_row").attr("data-city")+"_"+$("#address_row").attr("data-county")+"_"+thisid; $("#add_ids").val(newadd_ids); $("#townSelRow_list").hide(); $("#divsionSelect").hide(); $("#addressedit").show(); }); } }); }); }; //准备选择li var forselectclick = function(){ $("#forselect").off("click").on('click','.li_click',function(){ var thisId = $(this).attr("data-id"); var thislevel = $(this).attr("data-level"); var thisname = $(this).attr("data-name"); var $this = $(this); $("#back-address").attr("data-level",thislevel); if(thislevel == 1){ $("#address_row,#back-address").attr("data-state",thisId); }else if(thislevel == 2){ $("#address_row,#back-address").attr("data-city",thisId); }else if(thislevel == 3){ $("#address_row,#back-address").attr("data-county",thisId); $("#add_str_2").val(''); $("#add_str_2").attr("data-id",''); } getcityaddress({ thisId:thisId, thislevel:thislevel, callback:function(resin){ if(resin.data.length <=0 || thislevel>2){ $("#divsionSelect").hide(); $("#addressedit").show(); var add_str_text = ''; var add_str_id = ''; $("#selected").find("li").each(function(index, element) { var thisinname = $(this).attr("data-name"); var thisinid = $(this).attr("data-id"); add_str_text += thisinname; add_str_id += thisinid+'_'; }); add_str_text += thisname; add_str_id += thisId+'_' $("#townSelRow").attr("data-townid",thisId); $("#add_ids").val(add_str_id); $("#add_str_text,#add_str").text(add_str_text); $("#add_str").val(add_str_text); if(resin.data.length <=0){ $("#forselect").hide(); $("#townSelRow").hide(); }else{ $("#forselect").show(); $("#townSelRow").show(); } }else{ $("#selected").append($this).show(); } } }); }); } //获取省级数据 var siondatalist = function(opt){ getdataaddress({ callback:function(res){ if(res.status == 1){ var lihtml = ''; $.each(res.data,function(index,o){ lihtml += '<li class="li_click" data-level="'+o.level+'" data-name="'+o.name+'" data-id="'+o.id+'" data-parentid="0" data-isleaf="0">'+o.name+'</li>'; }); $("#forselect").html(lihtml).show(); $("#divsionSelect").show(); $("#addressedit").hide(); forselectclick(); }else{ config.tip.tips({ htmlmsg:'<div style="padding:30px">'+res.msg+'</div>', w:"96%", type:0 }); } } }); }; //获取省级以下数据列表 var getcityaddress = function(opt){ getdataaddress({ upid:opt.thisId, callback:function(res){ var lihtml = ''; $.each(res.data,function(index,o){ lihtml += '<li class="li_click" data-level="'+o.level+'" data-name="'+o.name+'" data-id="'+o.id+'" data-parentid="'+opt.thisId+'" data-isleaf="0">'+o.name+'</li>'; }); $("#forselect").html(lihtml).show(); if(opt.callback){ opt.callback(res); } } }); }; //统一获取地址 var getdataaddress = function(opt){ AjaxFunUtils.ajaxInit({ "url":"/common/district_son.html", "params":{upid:opt.upid}, "callback":function (res) { if(opt.callback){ opt.callback(res); } } }); }; //编辑地址,获取当前编辑地址数据 var edtaddress = function(optin){ AjaxFunUtils.ajaxInit({ url:"/myorder/address.html", params:{act:"get",addrid:optin.addrid}, callback:function(resin){ if(resin.status == 1){ $("#addressedit").show(); $("#addrid_edt").val(optin.addrid); $("#addressee").val(resin.data.addressee); $("#add_str_text").text(resin.data.address1); $("#add_str").val(resin.data.address1); $("#add_ids").val(resin.data.state+'_'+resin.data.city+'_'+resin.data.county+'_'+resin.data.town); $("#add_more").val(resin.data.more); $("#zip").val(resin.data.zip); $("#cellphone").val(resin.data.cellphone); if(resin.data.town){ $("#add_str_2").val(resin.data.address2); }else{ $("#townSelRow").hide(); } if(resin.data.addrid == defaultAddr){ $("#sedefault").attr("checked","checked"); } $("#address_row").attr("data-state",resin.data.state); $("#address_row").attr("data-city",resin.data.city); $("#address_row").attr("data-county",resin.data.county); $("#townSelRow").attr("data-townid",resin.data.county); //删除地址 $("#delBtn").show().unbind("click").bind("click",function(){ AjaxFunUtils.ajaxInit({ url:"/myorder/address.html", params:{act:"del",addrid:optin.addrid}, callback:function (result) { if(result.status == 1){ getAddress();//删除完成刷新地址列表 config.tip.tips({ htmlmsg:'<div style="padding:30px">'+result.msg+'</div>', w:"96%", type:0 }); $("#addressbox").remove(); }else{ config.tip.tips({ htmlmsg:'<div style="padding:30px">'+result.msg+'</div>', w:"96%", type:0 }); } } }); }); if(optin.callback){ optin.callback(resin); } } } }); }; //获取送货地址 var getAddress = function(odz){ AjaxFunUtils.ajaxInit({ url:"/myorder/address.html", params:{act:'list' }, callback:function(res){ var addresslist = res.data; if(addresslist.length<=0){ $("#addrid").html('<p id="newaddress" class="addAddressBtn" data-address="0" data-act="add" style="padding:0 5px; margin:5px 0">请填写收货人信息</p>'); addAddressBtn(); return false; } var html = ''; $.each(addresslist,function(index,o){ var newaddress = o.address1+' '+o.address2 + ' ' + o.more + ' ' + o.addressee + ' ' + o.cellphone; var checked = ''; if(o.default == 1){ checked = 'checked="checked"'; defaultAddr = o.addrid; } var addVal = '<li class="rowbox mt-5"><div class="row-flex1 rowbox"><input name="addrid" id="'+o.addrid+'" type="radio" value="'+o.addrid+'" '+checked+'><label style="line-height:20px" for="'+o.addrid+'">'+newaddress+'</label></div><div class="w100 text-right"><a href="javascript:void(0);" class="addAddressBtn" data-address="1" data-addrid="'+o.addrid+'" data-act="edt">编辑<div class="ico ico-jt ml-5"></div></a></div></li>'; html +=addVal; }); $("#addrid").html(html); addAddressBtn(); } }); }; //提交添加,编辑地址 var subaddress = function(opt){ $("#addressform").checkInput({ button:'.address_sub_btn', submitBtnFn: function (from) { var dataFrom = from.serializeJson(); dataFrom.act = opt.act; AjaxFunUtils.ajaxInit({ "url":"/myorder/address.html", "params":dataFrom, "callback":function (res) { if(res.status == 1){ config.tip.tips({ htmlmsg:'<div style="padding:30px">'+res.msg+'</div>', w:"96%", type:0, callback:function(){ getAddress();//添加,编辑完成刷新地址列表 $("#addressbox").remove(); } }); }else{ config.tip.tips({ htmlmsg:'<div style="padding:30px">'+res.msg+'</div>', w:"96%", type:0 }); } } }); } }); }; //增加地址,编辑地址绑定 var addAddressBtn = function(){ $(".addAddressBtn").unbind("click").bind("click",function(){ var typeId = $(this).attr("data-address"); var thisaddrid = $(this).attr("data-addrid"); var act = $(this).attr("data-act"); addedtAddress({act:act,addrid:thisaddrid}); }); //获取微信地址 $(".wxAddressBtn").unbind("click").bind("click",function(){ var thisaddrid = $(this).attr("data-addrid"); AjaxFunUtils.ajaxInit({ "url":"/myorder/address.html?act=weixin_sign", "params":{}, "callback":function (res) { if(res.status == 1){ var sign_info = res.data.sign_info; get_addres(); //获取微信地址 function get_addresinfo(){ WeixinJSBridge.invoke( 'editAddress', sign_info, function(res){ var resData = {}; resData.act = "add"; resData.nickname = res.username; resData.cellphone = res.telNumber; resData.zip = res.addressPostalCode; resData.address1 = res.addressCitySecondStageName +" "+res.addressCountiesThirdStageName+" "+res.addressDetailInfo; AjaxFunUtils.ajaxInit({ "url":"/myorder/address.html", "params":resData, "callback":function (res3) { if(res3.status == 1){ if($("#sedefault").attr("checked")){ //defaultAddr = thisaddrid; } //address.getAddress();//添加,编辑完成刷新地址s列表 }else{ config.tip.tips({ htmlmsg:'<div style="padding:30px">'+res3.msg+'</div>', w:"96%", type:0 }); } } }); } ); }; function get_addres(){ if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', get_addresinfo, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', get_addresinfo); document.attachEvent('onWeixinJSBridgeReady', get_addresinfo); } }else{ get_addresinfo(); } }; } } }); }); }; return {init:init,getAddress:getAddress}; });
38695248/require-gulp
moblie/require/js/address.js
JavaScript
gpl-2.0
19,264
package org.masterylearning.domain.data; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.masterylearning.domain.Entry; import org.masterylearning.dto.out.EntryDataOutDto; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.OneToOne; /** * For use of JsonTypeInfo and JsonSubType see this stackoverflow answer: * http://stackoverflow.com/questions/6542833/how-can-i-polymorphic-deserialization-json-string-using-java-and-jackson-library */ @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, property = "type") @JsonSubTypes({ @Type(value = Section.class, name = "section"), @Type(value = Unit.class, name = "unit"), @Type(value = Paragraph.class, name = "paragraph"), @Type(value = ContinueButton.class, name = "continue-button"), @Type(value = InteractiveContent.class, name = "interactive-content"), @Type(value = YesNoExercise.class, name = "yesnoexercise"), @Type(value = MultiAnswerExercise.class, name = "multianswerexercise") }) @Entity (name = "EntryData") @Inheritance (strategy = InheritanceType.TABLE_PER_CLASS) public abstract class EntryData { @Id @GeneratedValue(strategy = GenerationType.TABLE) public Long id; public String type; @JsonBackReference("entry-data") @OneToOne public Entry container; public abstract EntryDataOutDto toDto (); }
lanoxx/masterylearning
backend/src/main/java/org/masterylearning/domain/data/EntryData.java
Java
gpl-2.0
1,748
package org.dolphinemu.dolphinemu.features.settings.ui.viewholder; import android.view.View; import android.widget.TextView; import org.dolphinemu.dolphinemu.R; import org.dolphinemu.dolphinemu.features.settings.model.view.SettingsItem; import org.dolphinemu.dolphinemu.features.settings.model.view.SliderSetting; import org.dolphinemu.dolphinemu.features.settings.ui.SettingsAdapter; public final class SliderViewHolder extends SettingViewHolder { private SliderSetting mItem; private TextView mTextSettingName; private TextView mTextSettingDescription; public SliderViewHolder(View itemView, SettingsAdapter adapter) { super(itemView, adapter); } @Override protected void findViews(View root) { mTextSettingName = (TextView) root.findViewById(R.id.text_setting_name); mTextSettingDescription = (TextView) root.findViewById(R.id.text_setting_description); } @Override public void bind(SettingsItem item) { mItem = (SliderSetting) item; mTextSettingName.setText(item.getNameId()); if (item.getDescriptionId() > 0) { mTextSettingDescription.setText(item.getDescriptionId()); } } @Override public void onClick(View clicked) { getAdapter().onSliderClick(mItem); } }
riking/dolphin
Source/Android/app/src/main/java/org/dolphinemu/dolphinemu/features/settings/ui/viewholder/SliderViewHolder.java
Java
gpl-2.0
1,213
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace AL.Utils.NPOI.SS.Formula.PTG { using System; using System.Text; using AL.Utils.NPOI.HSSF.Record; using AL.Utils.NPOI.Util; /** * RefError - handles deleted cell reference * @author Jason Height (jheight at chariot dot net dot au) */ public class RefErrorPtg : OperandPtg { private static int SIZE = 5; public const byte sid = 0x2a; private int field_1_reserved; public RefErrorPtg() { field_1_reserved = 0; } public RefErrorPtg(ILittleEndianInput in1) { field_1_reserved = in1.ReadInt(); } public override String ToString() { StringBuilder buffer = new StringBuilder("[RefError]\n"); buffer.Append("reserved = ").Append(Reserved).Append("\n"); return buffer.ToString(); } public override void Write(ILittleEndianOutput out1) { out1.WriteByte(sid + PtgClass); out1.WriteInt(field_1_reserved); } public int Reserved { get{return field_1_reserved;} set { field_1_reserved = value; } } public override int Size { get { return SIZE; } } public override String ToFormulaString() { //TODO -- should we store a cellreference instance in this ptg?? but .. memory is an Issue, i believe! return "#REF!"; } public override byte DefaultOperandClass { get { return Ptg.CLASS_REF; } } } }
alexchentao/AL.Web
AL.Utils/Document/Excel/NPOI/SS/Formula/PTG/RefErrorPtg.cs
C#
gpl-2.0
2,556
// ** I18N Calendar._DN = new Array ("Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"); Calendar._MN = new Array ("Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"); // tooltips Calendar._TT = {}; Calendar._TT["TOGGLE"] = "Skifta första veckodag"; Calendar._TT["PREV_YEAR"] = "Förra året (tryck för meny)"; Calendar._TT["PREV_MONTH"] = "Förra månaden (tryck för meny)"; Calendar._TT["GO_TODAY"] = "Gå till dagens datum"; Calendar._TT["NEXT_MONTH"] = "Nästa månad (tryck för meny)"; Calendar._TT["NEXT_YEAR"] = "Nästa år (tryck för meny)"; Calendar._TT["SEL_DATE"] = "Välj dag"; Calendar._TT["DRAG_TO_MOVE"] = "Flytta fönstret"; Calendar._TT["PART_TODAY"] = " (idag)"; Calendar._TT["MON_FIRST"] = "Visa Måndag först"; Calendar._TT["SUN_FIRST"] = "Visa Söndag först"; Calendar._TT["CLOSE"] = "Stäng fönstret"; Calendar._TT["TODAY"] = "Idag"; // date formats Calendar._TT["DEF_DATE_FORMAT"] = "y-mm-dd"; Calendar._TT["TT_DATE_FORMAT"] = "DD, d MM y"; Calendar._TT["WK"] = "wk";
Fightmander/Hydra
lib/calendar/lang/calendar-sw.js
JavaScript
gpl-2.0
1,143
/* * Copyright (c) 2021 Charles University in Prague, Faculty of Arts, * Institute of the Czech National Corpus * Copyright (c) 2021 Martin Zimandl <martin.zimandl@gmail.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * dated June, 1991. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import styled from 'styled-components'; import * as theme from '../../theme/default'; // ---------------- <GeneralOptions /> -------------------------------------- export const GeneralOptions = styled.div` max-width: 30em; white-space: normal; .warn { white-space: normal; width: 25em; .icon { display: inline-block; padding-right: 0.3em; vertical-align: middle; img { width: 1.2em; } } } .data-loader { text-align: center; } fieldset { padding: 10pt 10pt; legend { font-weight: bold; } legend:first-letter { text-transform: capitalize; } input { margin-left: 5pt; } // hide number input arrows /* Chrome, Safari, Edge, Opera */ input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } /* Firefox */ input[type=number] { -moz-appearance: textfield; } } fieldset:not(:first-of-type) { margin-top: 0.7em; } `; // ------------------- <ResultRangeAndPagingTable /> ------------------------ export const ResultRangeAndPagingTable = styled.table` border-collapse: collapse; th { font-weight: normal; text-align: left; } td { padding: 3pt 0; } `;
czcorpus/kontext
public/files/js/views/options/general/style.tsx
TypeScript
gpl-2.0
2,389
///////////////////////////////////////////////////////////////////////////// // Name: exec.cpp // Purpose: exec sample demonstrates wxExecute and related functions // Author: Vadim Zeitlin // Modified by: // Created: 15.01.00 // RCS-ID: $Id: exec.cpp 54352 2008-06-25 07:51:09Z JS $ // Copyright: (c) Vadim Zeitlin // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWidgets headers #ifndef WX_PRECOMP #include "wx/app.h" #include "wx/log.h" #include "wx/frame.h" #include "wx/panel.h" #include "wx/timer.h" #include "wx/utils.h" #include "wx/menu.h" #include "wx/msgdlg.h" #include "wx/textdlg.h" #include "wx/filedlg.h" #include "wx/choicdlg.h" #include "wx/button.h" #include "wx/textctrl.h" #include "wx/listbox.h" #include "wx/sizer.h" #endif #include "wx/txtstrm.h" #include "wx/numdlg.h" #include "wx/textdlg.h" #include "wx/ffile.h" #include "wx/process.h" #include "wx/mimetype.h" #ifdef __WINDOWS__ #include "wx/dde.h" #endif // __WINDOWS__ // ---------------------------------------------------------------------------- // the usual application and main frame classes // ---------------------------------------------------------------------------- // Define a new application type, each program should derive a class from wxApp class MyApp : public wxApp { public: // override base class virtuals // ---------------------------- // this one is called on application startup and is a good place for the app // initialization (doing it here and not in the ctor allows to have an error // return: if OnInit() returns false, the application terminates) virtual bool OnInit(); }; // Define an array of process pointers used by MyFrame class MyPipedProcess; WX_DEFINE_ARRAY_PTR(MyPipedProcess *, MyProcessesArray); // Define a new frame type: this is going to be our main frame class MyFrame : public wxFrame { public: // ctor(s) MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size); // event handlers (these functions should _not_ be virtual) void OnQuit(wxCommandEvent& event); void OnKill(wxCommandEvent& event); void OnClear(wxCommandEvent& event); void OnSyncExec(wxCommandEvent& event); void OnAsyncExec(wxCommandEvent& event); void OnShell(wxCommandEvent& event); void OnExecWithRedirect(wxCommandEvent& event); void OnExecWithPipe(wxCommandEvent& event); void OnPOpen(wxCommandEvent& event); void OnFileExec(wxCommandEvent& event); void OnOpenURL(wxCommandEvent& event); void OnAbout(wxCommandEvent& event); // polling output of async processes void OnTimer(wxTimerEvent& event); void OnIdle(wxIdleEvent& event); // for MyPipedProcess void OnProcessTerminated(MyPipedProcess *process); wxListBox *GetLogListBox() const { return m_lbox; } private: void ShowOutput(const wxString& cmd, const wxArrayString& output, const wxString& title); void DoAsyncExec(const wxString& cmd); void AddAsyncProcess(MyPipedProcess *process) { if ( m_running.IsEmpty() ) { // we want to start getting the timer events to ensure that a // steady stream of idle events comes in -- otherwise we // wouldn't be able to poll the child process input m_timerIdleWakeUp.Start(100); } //else: the timer is already running m_running.Add(process); } void RemoveAsyncProcess(MyPipedProcess *process) { m_running.Remove(process); if ( m_running.IsEmpty() ) { // we don't need to get idle events all the time any more m_timerIdleWakeUp.Stop(); } } // the PID of the last process we launched asynchronously long m_pidLast; // last command we executed wxString m_cmdLast; #ifdef __WINDOWS__ void OnDDEExec(wxCommandEvent& event); void OnDDERequest(wxCommandEvent& event); bool GetDDEServer(); // last params of a DDE transaction wxString m_server, m_topic, m_cmdDde; #endif // __WINDOWS__ wxListBox *m_lbox; MyProcessesArray m_running; // the idle event wake up timer wxTimer m_timerIdleWakeUp; // any class wishing to process wxWidgets events must use this macro DECLARE_EVENT_TABLE() }; // ---------------------------------------------------------------------------- // MyPipeFrame: allows the user to communicate with the child process // ---------------------------------------------------------------------------- class MyPipeFrame : public wxFrame { public: MyPipeFrame(wxFrame *parent, const wxString& cmd, wxProcess *process); protected: void OnTextEnter(wxCommandEvent& WXUNUSED(event)) { DoSend(); } void OnBtnSend(wxCommandEvent& WXUNUSED(event)) { DoSend(); } void OnBtnSendFile(wxCommandEvent& WXUNUSED(event)); void OnBtnGet(wxCommandEvent& WXUNUSED(event)) { DoGet(); } void OnBtnClose(wxCommandEvent& WXUNUSED(event)) { DoClose(); } void OnClose(wxCloseEvent& event); void OnProcessTerm(wxProcessEvent& event); void DoSend() { wxString s(m_textOut->GetValue()); s += _T('\n'); m_out.Write(s.c_str(), s.length()); m_textOut->Clear(); DoGet(); } void DoGet(); void DoClose(); private: void DoGetFromStream(wxTextCtrl *text, wxInputStream& in); void DisableInput(); void DisableOutput(); wxProcess *m_process; wxOutputStream &m_out; wxInputStream &m_in, &m_err; wxTextCtrl *m_textOut, *m_textIn, *m_textErr; DECLARE_EVENT_TABLE() }; // ---------------------------------------------------------------------------- // wxProcess-derived classes // ---------------------------------------------------------------------------- // This is the handler for process termination events class MyProcess : public wxProcess { public: MyProcess(MyFrame *parent, const wxString& cmd) : wxProcess(parent), m_cmd(cmd) { m_parent = parent; } // instead of overriding this virtual function we might as well process the // event from it in the frame class - this might be more convenient in some // cases virtual void OnTerminate(int pid, int status); protected: MyFrame *m_parent; wxString m_cmd; }; // A specialization of MyProcess for redirecting the output class MyPipedProcess : public MyProcess { public: MyPipedProcess(MyFrame *parent, const wxString& cmd) : MyProcess(parent, cmd) { Redirect(); } virtual void OnTerminate(int pid, int status); virtual bool HasInput(); }; // A version of MyPipedProcess which also sends input to the stdin of the // child process class MyPipedProcess2 : public MyPipedProcess { public: MyPipedProcess2(MyFrame *parent, const wxString& cmd, const wxString& input) : MyPipedProcess(parent, cmd), m_input(input) { } virtual bool HasInput(); private: wxString m_input; }; // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // IDs for the controls and the menu commands enum { // menu items Exec_Quit = 100, Exec_Kill, Exec_ClearLog, Exec_SyncExec = 200, Exec_AsyncExec, Exec_Shell, Exec_POpen, Exec_OpenFile, Exec_OpenURL, Exec_DDEExec, Exec_DDERequest, Exec_Redirect, Exec_Pipe, Exec_About = 300, // control ids Exec_Btn_Send = 1000, Exec_Btn_SendFile, Exec_Btn_Get, Exec_Btn_Close }; static const wxChar *DIALOG_TITLE = _T("Exec sample"); // ---------------------------------------------------------------------------- // event tables and other macros for wxWidgets // ---------------------------------------------------------------------------- // the event tables connect the wxWidgets events with the functions (event // handlers) which process them. It can be also done at run-time, but for the // simple menu events like this the static method is much simpler. BEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(Exec_Quit, MyFrame::OnQuit) EVT_MENU(Exec_Kill, MyFrame::OnKill) EVT_MENU(Exec_ClearLog, MyFrame::OnClear) EVT_MENU(Exec_SyncExec, MyFrame::OnSyncExec) EVT_MENU(Exec_AsyncExec, MyFrame::OnAsyncExec) EVT_MENU(Exec_Shell, MyFrame::OnShell) EVT_MENU(Exec_Redirect, MyFrame::OnExecWithRedirect) EVT_MENU(Exec_Pipe, MyFrame::OnExecWithPipe) EVT_MENU(Exec_POpen, MyFrame::OnPOpen) EVT_MENU(Exec_OpenFile, MyFrame::OnFileExec) EVT_MENU(Exec_OpenURL, MyFrame::OnOpenURL) #ifdef __WINDOWS__ EVT_MENU(Exec_DDEExec, MyFrame::OnDDEExec) EVT_MENU(Exec_DDERequest, MyFrame::OnDDERequest) #endif // __WINDOWS__ EVT_MENU(Exec_About, MyFrame::OnAbout) EVT_IDLE(MyFrame::OnIdle) EVT_TIMER(wxID_ANY, MyFrame::OnTimer) END_EVENT_TABLE() BEGIN_EVENT_TABLE(MyPipeFrame, wxFrame) EVT_BUTTON(Exec_Btn_Send, MyPipeFrame::OnBtnSend) EVT_BUTTON(Exec_Btn_SendFile, MyPipeFrame::OnBtnSendFile) EVT_BUTTON(Exec_Btn_Get, MyPipeFrame::OnBtnGet) EVT_BUTTON(Exec_Btn_Close, MyPipeFrame::OnBtnClose) EVT_TEXT_ENTER(wxID_ANY, MyPipeFrame::OnTextEnter) EVT_CLOSE(MyPipeFrame::OnClose) EVT_END_PROCESS(wxID_ANY, MyPipeFrame::OnProcessTerm) END_EVENT_TABLE() // Create a new application object: this macro will allow wxWidgets to create // the application object during program execution (it's better than using a // static object for many reasons) and also declares the accessor function // wxGetApp() which will return the reference of the right type (i.e. MyApp and // not wxApp) IMPLEMENT_APP(MyApp) // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // the application class // ---------------------------------------------------------------------------- // `Main program' equivalent: the program execution "starts" here bool MyApp::OnInit() { // Create the main application window MyFrame *frame = new MyFrame(_T("Exec wxWidgets sample"), wxDefaultPosition, wxSize(500, 140)); // Show it and tell the application that it's our main window frame->Show(true); SetTopWindow(frame); // success: wxApp::OnRun() will be called which will enter the main message // loop and the application will run. If we returned false here, the // application would exit immediately. return true; } // ---------------------------------------------------------------------------- // main frame // ---------------------------------------------------------------------------- #ifdef __VISUALC__ #pragma warning(disable: 4355) // this used in base member initializer list #endif // frame constructor MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size) : wxFrame((wxFrame *)NULL, wxID_ANY, title, pos, size), m_timerIdleWakeUp(this) { m_pidLast = 0; #ifdef __WXMAC__ // we need this in order to allow the about menu relocation, since ABOUT is // not the default id of the about menu wxApp::s_macAboutMenuItemId = Exec_About; #endif // create a menu bar wxMenu *menuFile = new wxMenu(wxEmptyString, wxMENU_TEAROFF); menuFile->Append(Exec_Kill, _T("&Kill process...\tCtrl-K"), _T("Kill a process by PID")); menuFile->AppendSeparator(); menuFile->Append(Exec_ClearLog, _T("&Clear log\tCtrl-C"), _T("Clear the log window")); menuFile->AppendSeparator(); menuFile->Append(Exec_Quit, _T("E&xit\tAlt-X"), _T("Quit this program")); wxMenu *execMenu = new wxMenu; execMenu->Append(Exec_SyncExec, _T("Sync &execution...\tCtrl-E"), _T("Launch a program and return when it terminates")); execMenu->Append(Exec_AsyncExec, _T("&Async execution...\tCtrl-A"), _T("Launch a program and return immediately")); execMenu->Append(Exec_Shell, _T("Execute &shell command...\tCtrl-S"), _T("Launch a shell and execute a command in it")); execMenu->AppendSeparator(); execMenu->Append(Exec_Redirect, _T("Capture command &output...\tCtrl-O"), _T("Launch a program and capture its output")); execMenu->Append(Exec_Pipe, _T("&Pipe through command..."), _T("Pipe a string through a filter")); execMenu->Append(Exec_POpen, _T("&Open a pipe to a command...\tCtrl-P"), _T("Open a pipe to and from another program")); execMenu->AppendSeparator(); execMenu->Append(Exec_OpenFile, _T("Open &file...\tCtrl-F"), _T("Launch the command to open this kind of files")); execMenu->Append(Exec_OpenURL, _T("Open &URL...\tCtrl-U"), _T("Launch the default browser with the given URL")); #ifdef __WINDOWS__ execMenu->AppendSeparator(); execMenu->Append(Exec_DDEExec, _T("Execute command via &DDE...\tCtrl-D")); execMenu->Append(Exec_DDERequest, _T("Send DDE &request...\tCtrl-R")); #endif wxMenu *helpMenu = new wxMenu(wxEmptyString, wxMENU_TEAROFF); helpMenu->Append(Exec_About, _T("&About...\tF1"), _T("Show about dialog")); // now append the freshly created menu to the menu bar... wxMenuBar *menuBar = new wxMenuBar(); menuBar->Append(menuFile, _T("&File")); menuBar->Append(execMenu, _T("&Exec")); menuBar->Append(helpMenu, _T("&Help")); // ... and attach this menu bar to the frame SetMenuBar(menuBar); // create the listbox in which we will show misc messages as they come m_lbox = new wxListBox(this, wxID_ANY); wxFont font(12, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); if ( font.Ok() ) m_lbox->SetFont(font); #if wxUSE_STATUSBAR // create a status bar just for fun (by default with 1 pane only) CreateStatusBar(); SetStatusText(_T("Welcome to wxWidgets exec sample!")); #endif // wxUSE_STATUSBAR } // ---------------------------------------------------------------------------- // event handlers: file and help menu // ---------------------------------------------------------------------------- void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) { // true is to force the frame to close Close(true); } void MyFrame::OnClear(wxCommandEvent& WXUNUSED(event)) { m_lbox->Clear(); } void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) { wxMessageBox(_T("Exec wxWidgets Sample\n(c) 2000-2002 Vadim Zeitlin"), _T("About Exec"), wxOK | wxICON_INFORMATION, this); } void MyFrame::OnKill(wxCommandEvent& WXUNUSED(event)) { long pid = wxGetNumberFromUser(_T("Please specify the process to kill"), _T("Enter PID:"), _T("Exec question"), m_pidLast, // we need the full unsigned int range -INT_MAX, INT_MAX, this); if ( pid == -1 ) { // cancelled return; } static const wxString signalNames[] = { _T("Just test (SIGNONE)"), _T("Hangup (SIGHUP)"), _T("Interrupt (SIGINT)"), _T("Quit (SIGQUIT)"), _T("Illegal instruction (SIGILL)"), _T("Trap (SIGTRAP)"), _T("Abort (SIGABRT)"), _T("Emulated trap (SIGEMT)"), _T("FP exception (SIGFPE)"), _T("Kill (SIGKILL)"), _T("Bus (SIGBUS)"), _T("Segment violation (SIGSEGV)"), _T("System (SIGSYS)"), _T("Broken pipe (SIGPIPE)"), _T("Alarm (SIGALRM)"), _T("Terminate (SIGTERM)"), }; int sig = wxGetSingleChoiceIndex(_T("How to kill the process?"), _T("Exec question"), WXSIZEOF(signalNames), signalNames, this); switch ( sig ) { default: wxFAIL_MSG( _T("unexpected return value") ); // fall through case -1: // cancelled return; case wxSIGNONE: case wxSIGHUP: case wxSIGINT: case wxSIGQUIT: case wxSIGILL: case wxSIGTRAP: case wxSIGABRT: case wxSIGEMT: case wxSIGFPE: case wxSIGKILL: case wxSIGBUS: case wxSIGSEGV: case wxSIGSYS: case wxSIGPIPE: case wxSIGALRM: case wxSIGTERM: break; } if ( sig == 0 ) { if ( wxProcess::Exists(pid) ) wxLogStatus(_T("Process %ld is running."), pid); else wxLogStatus(_T("No process with pid = %ld."), pid); } else // not SIGNONE { wxKillError rc = wxProcess::Kill(pid, (wxSignal)sig); if ( rc == wxKILL_OK ) { wxLogStatus(_T("Process %ld killed with signal %d."), pid, sig); } else { static const wxChar *errorText[] = { _T(""), // no error _T("signal not supported"), _T("permission denied"), _T("no such process"), _T("unspecified error"), }; wxLogStatus(_T("Failed to kill process %ld with signal %d: %s"), pid, sig, errorText[rc]); } } } // ---------------------------------------------------------------------------- // event handlers: exec menu // ---------------------------------------------------------------------------- void MyFrame::DoAsyncExec(const wxString& cmd) { wxProcess *process = new MyProcess(this, cmd); m_pidLast = wxExecute(cmd, wxEXEC_ASYNC, process); if ( !m_pidLast ) { wxLogError( _T("Execution of '%s' failed."), cmd.c_str() ); delete process; } else { wxLogStatus( _T("Process %ld (%s) launched."), m_pidLast, cmd.c_str() ); m_cmdLast = cmd; } } void MyFrame::OnSyncExec(wxCommandEvent& WXUNUSED(event)) { wxString cmd = wxGetTextFromUser(_T("Enter the command: "), DIALOG_TITLE, m_cmdLast); if ( !cmd ) return; wxLogStatus( _T("'%s' is running please wait..."), cmd.c_str() ); int code = wxExecute(cmd, wxEXEC_SYNC); wxLogStatus(_T("Process '%s' terminated with exit code %d."), cmd.c_str(), code); m_cmdLast = cmd; } void MyFrame::OnAsyncExec(wxCommandEvent& WXUNUSED(event)) { wxString cmd = wxGetTextFromUser(_T("Enter the command: "), DIALOG_TITLE, m_cmdLast); if ( !cmd ) return; DoAsyncExec(cmd); } void MyFrame::OnShell(wxCommandEvent& WXUNUSED(event)) { wxString cmd = wxGetTextFromUser(_T("Enter the command: "), DIALOG_TITLE, m_cmdLast); if ( !cmd ) return; int code = wxShell(cmd); wxLogStatus(_T("Shell command '%s' terminated with exit code %d."), cmd.c_str(), code); m_cmdLast = cmd; } void MyFrame::OnExecWithRedirect(wxCommandEvent& WXUNUSED(event)) { wxString cmd = wxGetTextFromUser(_T("Enter the command: "), DIALOG_TITLE, m_cmdLast); if ( !cmd ) return; bool sync; switch ( wxMessageBox(_T("Execute it synchronously?"), _T("Exec question"), wxYES_NO | wxCANCEL | wxICON_QUESTION, this) ) { case wxYES: sync = true; break; case wxNO: sync = false; break; default: return; } if ( sync ) { wxArrayString output, errors; int code = wxExecute(cmd, output, errors); wxLogStatus(_T("command '%s' terminated with exit code %d."), cmd.c_str(), code); if ( code != -1 ) { ShowOutput(cmd, output, _T("Output")); ShowOutput(cmd, errors, _T("Errors")); } } else // async exec { MyPipedProcess *process = new MyPipedProcess(this, cmd); if ( !wxExecute(cmd, wxEXEC_ASYNC, process) ) { wxLogError(_T("Execution of '%s' failed."), cmd.c_str()); delete process; } else { AddAsyncProcess(process); } } m_cmdLast = cmd; } void MyFrame::OnExecWithPipe(wxCommandEvent& WXUNUSED(event)) { if ( !m_cmdLast ) m_cmdLast = _T("tr [a-z] [A-Z]"); wxString cmd = wxGetTextFromUser(_T("Enter the command: "), DIALOG_TITLE, m_cmdLast); if ( !cmd ) return; wxString input = wxGetTextFromUser(_T("Enter the string to send to it: "), DIALOG_TITLE); if ( !input ) return; // always execute the filter asynchronously MyPipedProcess2 *process = new MyPipedProcess2(this, cmd, input); long pid = wxExecute(cmd, wxEXEC_ASYNC, process); if ( pid ) { wxLogStatus( _T("Process %ld (%s) launched."), pid, cmd.c_str() ); AddAsyncProcess(process); } else { wxLogError(_T("Execution of '%s' failed."), cmd.c_str()); delete process; } m_cmdLast = cmd; } void MyFrame::OnPOpen(wxCommandEvent& WXUNUSED(event)) { wxString cmd = wxGetTextFromUser(_T("Enter the command to launch: "), DIALOG_TITLE, m_cmdLast); if ( cmd.empty() ) return; wxProcess *process = wxProcess::Open(cmd); if ( !process ) { wxLogError(_T("Failed to launch the command.")); return; } wxLogVerbose(_T("PID of the new process: %ld"), process->GetPid()); wxOutputStream *out = process->GetOutputStream(); if ( !out ) { wxLogError(_T("Failed to connect to child stdin")); return; } wxInputStream *in = process->GetInputStream(); if ( !in ) { wxLogError(_T("Failed to connect to child stdout")); return; } new MyPipeFrame(this, cmd, process); } void MyFrame::OnFileExec(wxCommandEvent& WXUNUSED(event)) { static wxString s_filename; wxString filename; #if wxUSE_FILEDLG filename = wxLoadFileSelector(_T("any file"), NULL, s_filename, this); #else // !wxUSE_FILEDLG filename = wxGetTextFromUser(_T("Enter the file name"), _T("exec sample"), s_filename, this); #endif // wxUSE_FILEDLG/!wxUSE_FILEDLG if ( filename.empty() ) return; s_filename = filename; wxString ext = filename.AfterLast(_T('.')); wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext); if ( !ft ) { wxLogError(_T("Impossible to determine the file type for extension '%s'"), ext.c_str()); return; } wxString cmd; bool ok = ft->GetOpenCommand(&cmd, wxFileType::MessageParameters(filename)); delete ft; if ( !ok ) { wxLogError(_T("Impossible to find out how to open files of extension '%s'"), ext.c_str()); return; } DoAsyncExec(cmd); } void MyFrame::OnOpenURL(wxCommandEvent& WXUNUSED(event)) { static wxString s_filename; wxString filename = wxGetTextFromUser ( _T("Enter the URL"), _T("exec sample"), s_filename, this ); if ( filename.empty() ) return; s_filename = filename; if ( !wxLaunchDefaultBrowser(s_filename) ) wxLogError(_T("Failed to open URL \"%s\""), s_filename.c_str()); } // ---------------------------------------------------------------------------- // DDE stuff // ---------------------------------------------------------------------------- #ifdef __WINDOWS__ bool MyFrame::GetDDEServer() { wxString server = wxGetTextFromUser(_T("Server to connect to:"), DIALOG_TITLE, m_server); if ( !server ) return false; m_server = server; wxString topic = wxGetTextFromUser(_T("DDE topic:"), DIALOG_TITLE, m_topic); if ( !topic ) return false; m_topic = topic; wxString cmd = wxGetTextFromUser(_T("DDE command:"), DIALOG_TITLE, m_cmdDde); if ( !cmd ) return false; m_cmdDde = cmd; return true; } void MyFrame::OnDDEExec(wxCommandEvent& WXUNUSED(event)) { if ( !GetDDEServer() ) return; wxDDEClient client; wxConnectionBase *conn = client.MakeConnection(wxEmptyString, m_server, m_topic); if ( !conn ) { wxLogError(_T("Failed to connect to the DDE server '%s'."), m_server.c_str()); } else { if ( !conn->Execute(m_cmdDde) ) { wxLogError(_T("Failed to execute command '%s' via DDE."), m_cmdDde.c_str()); } else { wxLogStatus(_T("Successfully executed DDE command")); } } } void MyFrame::OnDDERequest(wxCommandEvent& WXUNUSED(event)) { if ( !GetDDEServer() ) return; wxDDEClient client; wxConnectionBase *conn = client.MakeConnection(wxEmptyString, m_server, m_topic); if ( !conn ) { wxLogError(_T("Failed to connect to the DDE server '%s'."), m_server.c_str()); } else { if ( !conn->Request(m_cmdDde) ) { wxLogError(_T("Failed to send request '%s' via DDE."), m_cmdDde.c_str()); } else { wxLogStatus(_T("Successfully sent DDE request.")); } } } #endif // __WINDOWS__ // ---------------------------------------------------------------------------- // various helpers // ---------------------------------------------------------------------------- // input polling void MyFrame::OnIdle(wxIdleEvent& event) { size_t count = m_running.GetCount(); for ( size_t n = 0; n < count; n++ ) { if ( m_running[n]->HasInput() ) { event.RequestMore(); } } } void MyFrame::OnTimer(wxTimerEvent& WXUNUSED(event)) { wxWakeUpIdle(); } void MyFrame::OnProcessTerminated(MyPipedProcess *process) { RemoveAsyncProcess(process); } void MyFrame::ShowOutput(const wxString& cmd, const wxArrayString& output, const wxString& title) { size_t count = output.GetCount(); if ( !count ) return; m_lbox->Append(wxString::Format(_T("--- %s of '%s' ---"), title.c_str(), cmd.c_str())); for ( size_t n = 0; n < count; n++ ) { m_lbox->Append(output[n]); } m_lbox->Append(wxString::Format(_T("--- End of %s ---"), title.Lower().c_str())); } // ---------------------------------------------------------------------------- // MyProcess // ---------------------------------------------------------------------------- void MyProcess::OnTerminate(int pid, int status) { wxLogStatus(m_parent, _T("Process %u ('%s') terminated with exit code %d."), pid, m_cmd.c_str(), status); // we're not needed any more delete this; } // ---------------------------------------------------------------------------- // MyPipedProcess // ---------------------------------------------------------------------------- bool MyPipedProcess::HasInput() { bool hasInput = false; if ( IsInputAvailable() ) { wxTextInputStream tis(*GetInputStream()); // this assumes that the output is always line buffered wxString msg; msg << m_cmd << _T(" (stdout): ") << tis.ReadLine(); m_parent->GetLogListBox()->Append(msg); hasInput = true; } if ( IsErrorAvailable() ) { wxTextInputStream tis(*GetErrorStream()); // this assumes that the output is always line buffered wxString msg; msg << m_cmd << _T(" (stderr): ") << tis.ReadLine(); m_parent->GetLogListBox()->Append(msg); hasInput = true; } return hasInput; } void MyPipedProcess::OnTerminate(int pid, int status) { // show the rest of the output while ( HasInput() ) ; m_parent->OnProcessTerminated(this); MyProcess::OnTerminate(pid, status); } // ---------------------------------------------------------------------------- // MyPipedProcess2 // ---------------------------------------------------------------------------- bool MyPipedProcess2::HasInput() { if ( !m_input.empty() ) { wxTextOutputStream os(*GetOutputStream()); os.WriteString(m_input); CloseOutput(); m_input.clear(); // call us once again - may be we'll have output return true; } return MyPipedProcess::HasInput(); } // ============================================================================ // MyPipeFrame implementation // ============================================================================ MyPipeFrame::MyPipeFrame(wxFrame *parent, const wxString& cmd, wxProcess *process) : wxFrame(parent, wxID_ANY, cmd), m_process(process), // in a real program we'd check that the streams are !NULL here m_out(*process->GetOutputStream()), m_in(*process->GetInputStream()), m_err(*process->GetErrorStream()) { m_process->SetNextHandler(this); wxPanel *panel = new wxPanel(this, wxID_ANY); m_textOut = new wxTextCtrl(panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER); m_textIn = new wxTextCtrl(panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_RICH); m_textIn->SetEditable(false); m_textErr = new wxTextCtrl(panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_RICH); m_textErr->SetEditable(false); wxSizer *sizerTop = new wxBoxSizer(wxVERTICAL); sizerTop->Add(m_textOut, 0, wxGROW | wxALL, 5); wxSizer *sizerBtns = new wxBoxSizer(wxHORIZONTAL); sizerBtns-> Add(new wxButton(panel, Exec_Btn_Send, _T("&Send")), 0, wxALL, 5); sizerBtns-> Add(new wxButton(panel, Exec_Btn_SendFile, _T("&File...")), 0, wxALL, 5); sizerBtns-> Add(new wxButton(panel, Exec_Btn_Get, _T("&Get")), 0, wxALL, 5); sizerBtns-> Add(new wxButton(panel, Exec_Btn_Close, _T("&Close")), 0, wxALL, 5); sizerTop->Add(sizerBtns, 0, wxCENTRE | wxALL, 5); sizerTop->Add(m_textIn, 1, wxGROW | wxALL, 5); sizerTop->Add(m_textErr, 1, wxGROW | wxALL, 5); panel->SetSizer(sizerTop); sizerTop->Fit(this); Show(); } void MyPipeFrame::OnBtnSendFile(wxCommandEvent& WXUNUSED(event)) { #if wxUSE_FILEDLG wxFileDialog filedlg(this, _T("Select file to send")); if ( filedlg.ShowModal() != wxID_OK ) return; wxFFile file(filedlg.GetFilename(), _T("r")); wxString data; if ( !file.IsOpened() || !file.ReadAll(&data) ) return; // can't write the entire string at once, this risk overflowing the pipe // and we would dead lock size_t len = data.length(); const wxChar *pc = data.c_str(); while ( len ) { const size_t CHUNK_SIZE = 4096; m_out.Write(pc, len > CHUNK_SIZE ? CHUNK_SIZE : len); // note that not all data could have been written as we don't block on // the write end of the pipe const size_t lenChunk = m_out.LastWrite(); pc += lenChunk; len -= lenChunk; DoGet(); } #endif // wxUSE_FILEDLG } void MyPipeFrame::DoGet() { // we don't have any way to be notified when any input appears on the // stream so we have to poll it :-( DoGetFromStream(m_textIn, m_in); DoGetFromStream(m_textErr, m_err); } void MyPipeFrame::DoGetFromStream(wxTextCtrl *text, wxInputStream& in) { while ( in.CanRead() ) { wxChar buffer[4096]; buffer[in.Read(buffer, WXSIZEOF(buffer) - 1).LastRead()] = _T('\0'); text->AppendText(buffer); } } void MyPipeFrame::DoClose() { m_process->CloseOutput(); DisableInput(); } void MyPipeFrame::DisableInput() { m_textOut->SetEditable(false); FindWindow(Exec_Btn_Send)->Disable(); FindWindow(Exec_Btn_SendFile)->Disable(); FindWindow(Exec_Btn_Close)->Disable(); } void MyPipeFrame::DisableOutput() { FindWindow(Exec_Btn_Get)->Disable(); } void MyPipeFrame::OnClose(wxCloseEvent& event) { if ( m_process ) { // we're not interested in getting the process termination notification // if we are closing it ourselves wxProcess *process = m_process; m_process = NULL; process->SetNextHandler(NULL); process->CloseOutput(); } event.Skip(); } void MyPipeFrame::OnProcessTerm(wxProcessEvent& WXUNUSED(event)) { DoGet(); delete m_process; m_process = NULL; wxLogWarning(_T("The other process has terminated, closing")); DisableInput(); DisableOutput(); }
hajuuk/R7000
ap/gpl/amule/wxWidgets-2.8.12/samples/exec/exec.cpp
C++
gpl-2.0
34,871
<? use \Studip\Button; ?> <br /> <a name="users"></a> <form action="<?= $controller->url_for('course/members/edit_accepted/') ?>" method="post" data-dialog="size=50%> <?= CSRFProtection::tokenTag() ?> <table class="default collapsable"> <caption> <span class="actions"> <a href="<?= URLHelper::getLink('dispatch.php/messages/write', array('filter' => 'prelim', 'emailrequest' => 1, 'course_id' => $course_id, 'default_subject' => $subject)) ?>" data-dialog> <?= Icon::create('inbox', 'clickable', ['title' => sprintf(_('Nachricht mit Mailweiterleitung an alle %s versenden'),'vorläufig akzeptierten Nutzer/-innen')])->asImg(16)?> </a> </span> <?= _('Vorläufig akzeptierte Teilnehmende') ?> </caption> <colgroup> <? if (!$is_locked) : ?> <col width="20"> <? endif ?> <col width="20"> <col> <col width="15%"> <col width="40%"> <col width="80"> </colgroup> <thead> <tr class="sortable"> <? if (!$is_locked) : ?> <th> <input aria-label="<?= sprintf(_('Alle %s auswählen'), 'vorläufig akzeptierten NutzerInnen') ?>" type="checkbox" name="all" value="1" data-proxyfor=":checkbox[name^=accepted]"> </th> <? endif ?> <th></th> <th <?= ($sort_by == 'nachname' && $sort_status == 'accepted') ? sprintf('class="sort%s"', $order) : '' ?>> <? ($sort_status != 'accepted') ? $order = 'desc' : $order = $order ?> <a href="<?= URLHelper::getLink(sprintf('?sortby=nachname&sort_status=accepted&order=%s&toggle=%s', $order, ($sort_by == 'nachname'))) ?>#users"> <?=_('Nachname, Vorname')?> </a> </th> <th <?= ($sort_by == 'mkdate' && $sort_status == 'accepted') ? sprintf('class="sort%s"', $order) : '' ?>> <a href="<?= URLHelper::getLink(sprintf('?sortby=mkdate&sort_status=accepted&order=%s&toggle=%s', $order, ($sort_by == 'mkdate'))) ?>#accepted"> <?= _('Anmeldedatum') ?> </a> </th> <th><?=_('Studiengang')?></th> <th style="text-align: right"><?= _('Aktion') ?></th> </tr> </thead> <tbody> <? $nr= 0; foreach($accepted as $accept) : ?> <? $fullname = $accept['fullname'];?> <tr> <? if (!$is_locked) : ?> <td> <input aria-label="<?= sprintf(_('%s auswählen'), 'Vorläufig akzeptierte/n NutzerIn') ?>" type="checkbox" name="accepted[<?= $accept['user_id'] ?>]" value="1" /> </td> <? endif ?> <td style="text-align: right"><?= (++$nr < 10) ? sprintf('%02d', $nr) : $nr ?></td> <td> <a style="position: relative" href="<?= $controller->url_for(sprintf('profile?username=%s',$accept['username'])) ?>"> <?= Avatar::getAvatar($accept['user_id'], $accept['username'])->getImageTag(Avatar::SMALL, array('style' => 'margin-right: 5px','title' => htmlReady($fullname))); ?> <?= $accept['mkdate'] >= $last_visitdate ? Assets::img('red_star', array('style' => 'position: absolute; margin: 0px 0px 0px -15px')) : '' ?> <?= htmlReady($fullname) ?> </a> <? if ($accept['comment'] != '') : ?> <?= tooltipIcon(sprintf('<strong>%s</strong><br>%s', _('Bemerkung'), htmlReady($accept['comment'])), false, true) ?> <? endif ?> </td> <td> <? if(!empty($accept['mkdate'])) : ?> <?= strftime('%x %X', $accept['mkdate'])?> <? endif ?> </td> <td> <?= $this->render_partial("course/members/_studycourse.php", array('study_courses' => UserModel::getUserStudycourse($accept['user_id']))) ?> </td> <td style="text-align: right"> <a data-dialog title='<?= _('Bemerkung hinzufügen') ?>' href="<?=$controller->url_for('course/members/add_comment', $accept['user_id']) ?>"> <?= Icon::create('comment', 'clickable')->asImg() ?> </a> <? if($user_id != $accept['user_id']) : ?> <a href="<?= URLHelper::getLink('dispatch.php/messages/write', array('filter' => 'send_sms_to_all', 'emailrequest' => 1, 'rec_uname' => $accept['username'], 'default_subject' => $subject)) ?> " data-dialog> <?= Icon::create('mail', 'clickable', ['title' => sprintf(_('Nachricht mit Mailweiterleitung an %s senden'),htmlReady($fullname))])->asImg(16) ?> </a> <? endif?> <? if (!$is_locked) : ?> <a href="<?= $controller->url_for(sprintf('course/members/cancel_subscription/singleuser/accepted/%s', $accept['user_id'])) ?>"> <?= Icon::create('door-leave', 'clickable', ['title' => sprintf(_('%s austragen'),htmlReady($fullname))])->asImg(16) ?> </a> <? endif ?> </td> </tr> <? endforeach ?> </tbody> <? if (!$is_locked) : ?> <tfoot> <tr> <td class="printhead" colspan="6"> <select name="action_accepted" id="action_accepted" aria-label="<?= _('Aktion ausführen') ?>"> <option value="">- <?= _('Aktion wählen') ?></option> <option value="upgrade"><?= _('Akzeptieren') ?></option> <option value="remove"><?= _('Austragen') ?></option> <option value="message"><?=_('Nachricht senden')?></option> <!--<option value="copy_to_course"><?= _('In Seminar verschieben/kopieren') ?></option>--> </select> <?= Button::create(_('Ausführen'), 'submit_accepted') ?> </td> </tr> </tfoot> <? endif ?> </table> </form>
ratbird/hope
app/views/course/members/accepted_list.php
PHP
gpl-2.0
6,994
from collections import OrderedDict from rest_framework import pagination from rest_framework.response import Response __author__ = 'alexandreferreira' class DetailPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): return Response(OrderedDict([ ('count', self.page.paginator.count), ('next', self.get_next_page_number()), ('has_next', self.page.has_next()), ('previous', self.get_previous_page_number()), ('has_previous', self.page.has_previous()), ('current', self.page.number), ('results', data) ])) def get_next_page_number(self): if not self.page.has_next(): return self.page.number return self.page.next_page_number() def get_previous_page_number(self): if not self.page.has_previous(): return 1 return self.page.previous_page_number()
alexandreferreira/namesearch-example
namesearch/pagination.py
Python
gpl-2.0
948
## # Copyright 2013-2020 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/easybuilders/easybuild # # EasyBuild 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 v2. # # EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ EasyBuild support for a GCC+CUDA compiler toolchain. :author: Kenneth Hoste (Ghent University) """ from easybuild.toolchains.compiler.cuda import Cuda from easybuild.toolchains.gcc import GccToolchain class GccCUDA(GccToolchain, Cuda): """Compiler toolchain with GCC and CUDA.""" NAME = 'gcccuda' COMPILER_MODULE_NAME = ['GCC', 'CUDA'] SUBTOOLCHAIN = GccToolchain.NAME
pescobar/easybuild-framework
easybuild/toolchains/gcccuda.py
Python
gpl-2.0
1,443
/* * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Scripts for spells with SPELLFAMILY_HUNTER, SPELLFAMILY_PET and SPELLFAMILY_GENERIC spells used by hunter players. * Ordered alphabetically using scriptname. * Scriptnames of files in this file should be prefixed with "spell_hun_". */ #include "Pet.h" #include "ScriptMgr.h" #include "Cell.h" #include "CellImpl.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "SpellScript.h" #include "SpellAuraEffects.h" enum HunterSpells { SPELL_HUNTER_ASPECT_OF_THE_BEAST_PET = 61669, SPELL_HUNTER_BESTIAL_WRATH = 19574, SPELL_HUNTER_CHIMERA_SHOT_SERPENT = 53353, SPELL_HUNTER_CHIMERA_SHOT_VIPER = 53358, SPELL_HUNTER_CHIMERA_SHOT_SCORPID = 53359, SPELL_HUNTER_INVIGORATION_TRIGGERED = 53398, SPELL_HUNTER_MASTERS_CALL_TRIGGERED = 62305, SPELL_HUNTER_PET_LAST_STAND_TRIGGERED = 53479, SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX = 55709, SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_TRIGGERED = 54114, SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_DEBUFF = 55711, SPELL_HUNTER_PET_CARRION_FEEDER_TRIGGERED = 54045, SPELL_HUNTER_READINESS = 23989, SPELL_HUNTER_SNIPER_TRAINING_R1 = 53302, SPELL_HUNTER_SNIPER_TRAINING_BUFF_R1 = 64418, SPELL_DRAENEI_GIFT_OF_THE_NAARU = 59543, }; // 13161 - Aspect of the Beast class spell_hun_aspect_of_the_beast : public SpellScriptLoader { public: spell_hun_aspect_of_the_beast() : SpellScriptLoader("spell_hun_aspect_of_the_beast") { } class spell_hun_aspect_of_the_beast_AuraScript : public AuraScript { PrepareAuraScript(spell_hun_aspect_of_the_beast_AuraScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_ASPECT_OF_THE_BEAST_PET)) return false; return true; } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (Player* caster = GetCaster()->ToPlayer()) if (Pet* pet = caster->GetPet()) pet->RemoveAurasDueToSpell(SPELL_HUNTER_ASPECT_OF_THE_BEAST_PET); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (Player* caster = GetCaster()->ToPlayer()) if (caster->GetPet()) caster->CastSpell(caster, SPELL_HUNTER_ASPECT_OF_THE_BEAST_PET, true); } void Register() { AfterEffectApply += AuraEffectApplyFn(spell_hun_aspect_of_the_beast_AuraScript::OnApply, EFFECT_0, SPELL_AURA_UNTRACKABLE, AURA_EFFECT_HANDLE_REAL); AfterEffectRemove += AuraEffectRemoveFn(spell_hun_aspect_of_the_beast_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_UNTRACKABLE, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_hun_aspect_of_the_beast_AuraScript(); } }; // 53209 - Chimera Shot class spell_hun_chimera_shot : public SpellScriptLoader { public: spell_hun_chimera_shot() : SpellScriptLoader("spell_hun_chimera_shot") { } class spell_hun_chimera_shot_SpellScript : public SpellScript { PrepareSpellScript(spell_hun_chimera_shot_SpellScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_CHIMERA_SHOT_SERPENT) || !sSpellMgr->GetSpellInfo(SPELL_HUNTER_CHIMERA_SHOT_VIPER) || !sSpellMgr->GetSpellInfo(SPELL_HUNTER_CHIMERA_SHOT_SCORPID)) return false; return true; } void HandleScriptEffect(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); if (Unit* unitTarget = GetHitUnit()) { uint32 spellId = 0; int32 basePoint = 0; Unit::AuraApplicationMap& Auras = unitTarget->GetAppliedAuras(); for (Unit::AuraApplicationMap::iterator i = Auras.begin(); i != Auras.end(); ++i) { Aura* aura = i->second->GetBase(); if (aura->GetCasterGUID() != caster->GetGUID()) continue; // Search only Serpent Sting, Viper Sting, Scorpid Sting auras flag96 familyFlag = aura->GetSpellInfo()->SpellFamilyFlags; if (!(familyFlag[1] & 0x00000080 || familyFlag[0] & 0x0000C000)) continue; if (AuraEffect const* aurEff = aura->GetEffect(0)) { // Serpent Sting - Instantly deals 40% of the damage done by your Serpent Sting. if (familyFlag[0] & 0x4000) { int32 TickCount = aurEff->GetTotalTicks(); spellId = SPELL_HUNTER_CHIMERA_SHOT_SERPENT; basePoint = caster->SpellDamageBonusDone(unitTarget, aura->GetSpellInfo(), aurEff->GetAmount(), DOT, aura->GetStackAmount()); ApplyPct(basePoint, TickCount * 40); basePoint = unitTarget->SpellDamageBonusTaken(caster, aura->GetSpellInfo(), basePoint, DOT, aura->GetStackAmount()); } // Viper Sting - Instantly restores mana to you equal to 60% of the total amount drained by your Viper Sting. else if (familyFlag[1] & 0x00000080) { int32 TickCount = aura->GetEffect(0)->GetTotalTicks(); spellId = SPELL_HUNTER_CHIMERA_SHOT_VIPER; // Amount of one aura tick basePoint = int32(CalculatePct(unitTarget->GetMaxPower(POWER_MANA), aurEff->GetAmount())); int32 casterBasePoint = aurEff->GetAmount() * unitTarget->GetMaxPower(POWER_MANA) / 50; // TODO: WTF? caster uses unitTarget? if (basePoint > casterBasePoint) basePoint = casterBasePoint; ApplyPct(basePoint, TickCount * 60); } // Scorpid Sting - Attempts to Disarm the target for 10 sec. This effect cannot occur more than once per 1 minute. else if (familyFlag[0] & 0x00008000) spellId = SPELL_HUNTER_CHIMERA_SHOT_SCORPID; // ?? nothing say in spell desc (possibly need addition check) //if (familyFlag & 0x0000010000000000LL || // dot // familyFlag & 0x0000100000000000LL) // stun //{ // spellId = 53366; // 53366 Chimera Shot - Wyvern //} // Refresh aura duration aura->RefreshDuration(); } break; } if (spellId) caster->CastCustomSpell(unitTarget, spellId, &basePoint, 0, 0, true); if (spellId == SPELL_HUNTER_CHIMERA_SHOT_SCORPID && caster->ToPlayer()) // Scorpid Sting - Add 1 minute cooldown caster->ToPlayer()->AddSpellCooldown(spellId, 0, uint32(time(NULL) + 60)); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_hun_chimera_shot_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_hun_chimera_shot_SpellScript(); } }; // 781 - Disengage class spell_hun_disengage : public SpellScriptLoader { public: spell_hun_disengage() : SpellScriptLoader("spell_hun_disengage") { } class spell_hun_disengage_SpellScript : public SpellScript { PrepareSpellScript(spell_hun_disengage_SpellScript); SpellCastResult CheckCast() { Unit* caster = GetCaster(); if (caster->GetTypeId() == TYPEID_PLAYER && !caster->isInCombat()) return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW; return SPELL_CAST_OK; } void Register() { OnCheckCast += SpellCheckCastFn(spell_hun_disengage_SpellScript::CheckCast); } }; SpellScript* GetSpellScript() const { return new spell_hun_disengage_SpellScript(); } }; // 53412 - Invigoration class spell_hun_invigoration : public SpellScriptLoader { public: spell_hun_invigoration() : SpellScriptLoader("spell_hun_invigoration") { } class spell_hun_invigoration_SpellScript : public SpellScript { PrepareSpellScript(spell_hun_invigoration_SpellScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_INVIGORATION_TRIGGERED)) return false; return true; } void HandleScriptEffect(SpellEffIndex /*effIndex*/) { if (Unit* unitTarget = GetHitUnit()) if (AuraEffect* aurEff = unitTarget->GetDummyAuraEffect(SPELLFAMILY_HUNTER, 3487, 0)) if (roll_chance_i(aurEff->GetAmount())) unitTarget->CastSpell(unitTarget, SPELL_HUNTER_INVIGORATION_TRIGGERED, true); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_hun_invigoration_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_hun_invigoration_SpellScript(); } }; // 53478 - Last Stand Pet class spell_hun_last_stand_pet : public SpellScriptLoader { public: spell_hun_last_stand_pet() : SpellScriptLoader("spell_hun_last_stand_pet") { } class spell_hun_last_stand_pet_SpellScript : public SpellScript { PrepareSpellScript(spell_hun_last_stand_pet_SpellScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_PET_LAST_STAND_TRIGGERED)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); int32 healthModSpellBasePoints0 = int32(caster->CountPctFromMaxHealth(30)); caster->CastCustomSpell(caster, SPELL_HUNTER_PET_LAST_STAND_TRIGGERED, &healthModSpellBasePoints0, NULL, NULL, true, NULL); } void Register() { // add dummy effect spell handler to pet's Last Stand OnEffectHitTarget += SpellEffectFn(spell_hun_last_stand_pet_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_hun_last_stand_pet_SpellScript(); } }; // 53271 - Masters Call class spell_hun_masters_call : public SpellScriptLoader { public: spell_hun_masters_call() : SpellScriptLoader("spell_hun_masters_call") { } class spell_hun_masters_call_SpellScript : public SpellScript { PrepareSpellScript(spell_hun_masters_call_SpellScript); bool Validate(SpellInfo const* spellInfo) { if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_MASTERS_CALL_TRIGGERED) || !sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].CalcValue()) || !sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_1].CalcValue())) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { if (Unit* ally = GetHitUnit()) if (Player* caster = GetCaster()->ToPlayer()) if (Pet* target = caster->GetPet()) { TriggerCastFlags castMask = TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_IGNORE_CASTER_AURASTATE); target->CastSpell(ally, GetEffectValue(), castMask); target->CastSpell(ally, GetSpellInfo()->Effects[EFFECT_0].CalcValue(), castMask); } } void HandleScriptEffect(SpellEffIndex /*effIndex*/) { if (Unit* target = GetHitUnit()) { // Cannot be processed while pet is dead TriggerCastFlags castMask = TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_IGNORE_CASTER_AURASTATE); target->CastSpell(target, SPELL_HUNTER_MASTERS_CALL_TRIGGERED, castMask); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_hun_masters_call_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); OnEffectHitTarget += SpellEffectFn(spell_hun_masters_call_SpellScript::HandleScriptEffect, EFFECT_1, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_hun_masters_call_SpellScript(); } }; // 34477 - Misdirection class spell_hun_misdirection : public SpellScriptLoader { public: spell_hun_misdirection() : SpellScriptLoader("spell_hun_misdirection") { } class spell_hun_misdirection_AuraScript : public AuraScript { PrepareAuraScript(spell_hun_misdirection_AuraScript); void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (Unit* caster = GetCaster()) if (GetTargetApplication()->GetRemoveMode() != AURA_REMOVE_BY_DEFAULT) caster->SetReducedThreatPercent(0, 0); } void Register() { AfterEffectRemove += AuraEffectRemoveFn(spell_hun_misdirection_AuraScript::OnRemove, EFFECT_1, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_hun_misdirection_AuraScript(); } }; // 35079 - Misdirection proc class spell_hun_misdirection_proc : public SpellScriptLoader { public: spell_hun_misdirection_proc() : SpellScriptLoader("spell_hun_misdirection_proc") { } class spell_hun_misdirection_proc_AuraScript : public AuraScript { PrepareAuraScript(spell_hun_misdirection_proc_AuraScript); void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (GetCaster()) GetCaster()->SetReducedThreatPercent(0, 0); } void Register() { AfterEffectRemove += AuraEffectRemoveFn(spell_hun_misdirection_proc_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_hun_misdirection_proc_AuraScript(); } }; // 54044 - Pet Carrion Feeder class spell_hun_pet_carrion_feeder : public SpellScriptLoader { public: spell_hun_pet_carrion_feeder() : SpellScriptLoader("spell_hun_pet_carrion_feeder") { } class spell_hun_pet_carrion_feeder_SpellScript : public SpellScript { PrepareSpellScript(spell_hun_pet_carrion_feeder_SpellScript); bool Load() { if (!GetCaster()->isPet()) return false; return true; } bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_PET_CARRION_FEEDER_TRIGGERED)) return false; return true; } SpellCastResult CheckIfCorpseNear() { Unit* caster = GetCaster(); float max_range = GetSpellInfo()->GetMaxRange(false); WorldObject* result = NULL; // search for nearby enemy corpse in range Trinity::AnyDeadUnitSpellTargetInRangeCheck check(caster, max_range, GetSpellInfo(), TARGET_CHECK_ENEMY); Trinity::WorldObjectSearcher<Trinity::AnyDeadUnitSpellTargetInRangeCheck> searcher(caster, result, check); caster->GetMap()->VisitFirstFound(caster->m_positionX, caster->m_positionY, max_range, searcher); if (!result) return SPELL_FAILED_NO_EDIBLE_CORPSES; return SPELL_CAST_OK; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); caster->CastSpell(caster, SPELL_HUNTER_PET_CARRION_FEEDER_TRIGGERED, false); } void Register() { // add dummy effect spell handler to pet's Last Stand OnEffectHit += SpellEffectFn(spell_hun_pet_carrion_feeder_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); OnCheckCast += SpellCheckCastFn(spell_hun_pet_carrion_feeder_SpellScript::CheckIfCorpseNear); } }; SpellScript* GetSpellScript() const { return new spell_hun_pet_carrion_feeder_SpellScript(); } }; // 55709 - Pet Heart of the Phoenix class spell_hun_pet_heart_of_the_phoenix : public SpellScriptLoader { public: spell_hun_pet_heart_of_the_phoenix() : SpellScriptLoader("spell_hun_pet_heart_of_the_phoenix") { } class spell_hun_pet_heart_of_the_phoenix_SpellScript : public SpellScript { PrepareSpellScript(spell_hun_pet_heart_of_the_phoenix_SpellScript); bool Load() { if (!GetCaster()->isPet()) return false; return true; } bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_TRIGGERED) || !sSpellMgr->GetSpellInfo(SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_DEBUFF)) return false; return true; } void HandleScript(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); if (Unit* owner = caster->GetOwner()) if (!caster->HasAura(SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_DEBUFF)) { owner->CastCustomSpell(SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_TRIGGERED, SPELLVALUE_BASE_POINT0, 100, caster, true); caster->CastSpell(caster, SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_DEBUFF, true); } } void Register() { // add dummy effect spell handler to pet's Last Stand OnEffectHitTarget += SpellEffectFn(spell_hun_pet_heart_of_the_phoenix_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_hun_pet_heart_of_the_phoenix_SpellScript(); } }; // 23989 - Readiness class spell_hun_readiness : public SpellScriptLoader { public: spell_hun_readiness() : SpellScriptLoader("spell_hun_readiness") { } class spell_hun_readiness_SpellScript : public SpellScript { PrepareSpellScript(spell_hun_readiness_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } void HandleDummy(SpellEffIndex /*effIndex*/) { Player* caster = GetCaster()->ToPlayer(); // immediately finishes the cooldown on your other Hunter abilities except Bestial Wrath const SpellCooldowns& cm = caster->ToPlayer()->GetSpellCooldownMap(); for (SpellCooldowns::const_iterator itr = cm.begin(); itr != cm.end();) { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itr->first); ///! If spellId in cooldown map isn't valid, the above will return a null pointer. if (spellInfo && spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && spellInfo->Id != SPELL_HUNTER_READINESS && spellInfo->Id != SPELL_HUNTER_BESTIAL_WRATH && spellInfo->Id != SPELL_DRAENEI_GIFT_OF_THE_NAARU && spellInfo->GetRecoveryTime() > 0) caster->RemoveSpellCooldown((itr++)->first, true); else ++itr; } } void Register() { // add dummy effect spell handler to Readiness OnEffectHitTarget += SpellEffectFn(spell_hun_readiness_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_hun_readiness_SpellScript(); } }; // 37506 - Scatter Shot class spell_hun_scatter_shot : public SpellScriptLoader { public: spell_hun_scatter_shot() : SpellScriptLoader("spell_hun_scatter_shot") { } class spell_hun_scatter_shot_SpellScript : public SpellScript { PrepareSpellScript(spell_hun_scatter_shot_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } void HandleDummy(SpellEffIndex /*effIndex*/) { Player* caster = GetCaster()->ToPlayer(); // break Auto Shot and autohit caster->InterruptSpell(CURRENT_AUTOREPEAT_SPELL); caster->AttackStop(); caster->SendAttackSwingCancelAttack(); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_hun_scatter_shot_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_hun_scatter_shot_SpellScript(); } }; // -53302 - Sniper Training class spell_hun_sniper_training : public SpellScriptLoader { public: spell_hun_sniper_training() : SpellScriptLoader("spell_hun_sniper_training") { } class spell_hun_sniper_training_AuraScript : public AuraScript { PrepareAuraScript(spell_hun_sniper_training_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_SNIPER_TRAINING_R1) || !sSpellMgr->GetSpellInfo(SPELL_HUNTER_SNIPER_TRAINING_BUFF_R1)) return false; return true; } void HandlePeriodic(AuraEffect const* aurEff) { PreventDefaultAction(); if (aurEff->GetAmount() <= 0) { Unit* caster = GetCaster(); uint32 spellId = SPELL_HUNTER_SNIPER_TRAINING_BUFF_R1 + GetId() - SPELL_HUNTER_SNIPER_TRAINING_R1; if (Unit* target = GetTarget()) if (!target->HasAura(spellId)) { SpellInfo const* triggeredSpellInfo = sSpellMgr->GetSpellInfo(spellId); Unit* triggerCaster = triggeredSpellInfo->NeedsToBeTriggeredByCaster() ? caster : target; triggerCaster->CastSpell(target, triggeredSpellInfo, true, 0, aurEff); } } } void HandleUpdatePeriodic(AuraEffect* aurEff) { if (Player* playerTarget = GetUnitOwner()->ToPlayer()) { int32 baseAmount = aurEff->GetBaseAmount(); int32 amount = playerTarget->isMoving() ? playerTarget->CalculateSpellDamage(playerTarget, GetSpellInfo(), aurEff->GetEffIndex(), &baseAmount) : aurEff->GetAmount() - 1; aurEff->SetAmount(amount); } } void Register() { OnEffectPeriodic += AuraEffectPeriodicFn(spell_hun_sniper_training_AuraScript::HandlePeriodic, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); OnEffectUpdatePeriodic += AuraEffectUpdatePeriodicFn(spell_hun_sniper_training_AuraScript::HandleUpdatePeriodic, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); } }; AuraScript* GetAuraScript() const { return new spell_hun_sniper_training_AuraScript(); } }; // 1515 - Tame Beast class spell_hun_tame_beast : public SpellScriptLoader { public: spell_hun_tame_beast() : SpellScriptLoader("spell_hun_tame_beast") { } class spell_hun_tame_beast_SpellScript : public SpellScript { PrepareSpellScript(spell_hun_tame_beast_SpellScript); SpellCastResult CheckCast() { Unit* caster = GetCaster(); if (caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_DONT_REPORT; if (!GetExplTargetUnit()) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; if (Creature* target = GetExplTargetUnit()->ToCreature()) { if (target->getLevel() > caster->getLevel()) return SPELL_FAILED_HIGHLEVEL; // use SMSG_PET_TAME_FAILURE? if (!target->GetCreatureTemplate()->isTameable(caster->ToPlayer()->CanTameExoticPets())) return SPELL_FAILED_BAD_TARGETS; if (caster->GetPetGUID()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; if (caster->GetCharmGUID()) return SPELL_FAILED_ALREADY_HAVE_CHARM; } else return SPELL_FAILED_BAD_IMPLICIT_TARGETS; return SPELL_CAST_OK; } void Register() { OnCheckCast += SpellCheckCastFn(spell_hun_tame_beast_SpellScript::CheckCast); } }; SpellScript* GetSpellScript() const { return new spell_hun_tame_beast_SpellScript(); } }; // -24604 - Furious Howl // 53434 - Call of the Wild class spell_hun_target_only_pet_and_owner : public SpellScriptLoader { public: spell_hun_target_only_pet_and_owner() : SpellScriptLoader("spell_hun_target_only_pet_and_owner") { } class spell_hun_target_only_pet_and_owner_SpellScript : public SpellScript { PrepareSpellScript(spell_hun_target_only_pet_and_owner_SpellScript); void FilterTargets(std::list<WorldObject*>& targets) { targets.clear(); targets.push_back(GetCaster()); if (Unit* owner = GetCaster()->GetOwner()) targets.push_back(owner); } void Register() { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_hun_target_only_pet_and_owner_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_CASTER_AREA_PARTY); OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_hun_target_only_pet_and_owner_SpellScript::FilterTargets, EFFECT_1, TARGET_UNIT_CASTER_AREA_PARTY); } }; SpellScript* GetSpellScript() const { return new spell_hun_target_only_pet_and_owner_SpellScript(); } }; void AddSC_hunter_spell_scripts() { new spell_hun_aspect_of_the_beast(); new spell_hun_chimera_shot(); new spell_hun_disengage(); new spell_hun_invigoration(); new spell_hun_last_stand_pet(); new spell_hun_masters_call(); new spell_hun_misdirection(); new spell_hun_misdirection_proc(); new spell_hun_pet_carrion_feeder(); new spell_hun_pet_heart_of_the_phoenix(); new spell_hun_readiness(); new spell_hun_scatter_shot(); new spell_hun_sniper_training(); new spell_hun_tame_beast(); new spell_hun_target_only_pet_and_owner(); }
Multigaming/WoW434
src/server/scripts/Spells/spell_hunter.cpp
C++
gpl-2.0
30,225
/* * LSpec.java * * Created on April 24, 2007, 11:06 PM */ package org.das2.qds.util; import java.util.LinkedHashMap; import java.util.Map; import org.das2.datum.Datum; import org.das2.datum.Units; import org.das2.qds.ArrayDataSet; import org.das2.qds.DDataSet; import org.das2.qds.DataSetUtil; import org.das2.qds.QDataSet; import org.das2.qds.SemanticOps; import org.das2.qds.ops.Ops; /** * Form a rank 2 dataset with L and Time for tags by identifying monotonic sweeps * in two rank 1 datasets. * @author jbf */ public class LSpec { /** * identifies the sweep of each record */ public static final String USER_PROP_SWEEPS = "sweeps"; /** Creates a new instance of LSpec */ private LSpec() { } /** * just the inward sweeps */ public static int DIR_INWARD= -1; /** * just the outward sweeps */ public static int DIR_OUTWARD= 1; /** * include both sweeps */ public static int DIR_BOTH= 0; /** * identify monotonically increasing or decreasing segments of the dataset. * @param lds the dataset which sweeps back and forth, such as LShell or MagLat (or a sine wave for testing). * @param dir 0=both 1=outward 2= inward * @return rank 2 data set of sweep indeces, dim0 is sweep number, dim1 is two-element [ start, end(inclusive) ]. */ public static QDataSet identifySweeps( QDataSet lds, int dir ) { DataSetBuilder builder= new DataSetBuilder( 2, 100, 2 ); DataSetBuilder dep0builder= new DataSetBuilder( 2, 100, 2 ); double slope0= lds.value(1) - lds.value(0); int start=0; int end=0; // index of the right point of slope0. QDataSet wds= SemanticOps.weightsDataSet(lds); ArrayDataSet tds= ArrayDataSet.copy( SemanticOps.xtagsDataSet(lds) ); wds= Ops.multiply( wds, SemanticOps.weightsDataSet(tds) ); Datum cadence= SemanticOps.guessXTagWidth( tds, lds ); cadence= cadence.multiply(10.0); // kludge for data on 2012-10-25 tds.putProperty( QDataSet.CADENCE, DataSetUtil.asDataSet(cadence) ); QDataSet nonGap= SemanticOps.cadenceCheck(tds,lds); for ( int i=1; i<lds.length(); i++ ) { double slope1= lds.value(i) - lds.value(i-1); if ( slope0 * slope1 <= 0. || ( nonGap.value(i-1)==1 && nonGap.value(i)==0 ) ) { if ( slope0!=0. && ( dir==0 || ( slope0*dir>0 && end-start>1 ) ) ) { //TODO: detect jumps in the LShell, e.g. only downward: \\\\\ if ( start<end ) { builder.putValue( -1, 0, start ); builder.putValue( -1, 1, end-1 ); builder.nextRecord(); dep0builder.putValue( -1, 0, tds.value(start) ); dep0builder.putValue( -1, 1, tds.value(end-1) ); dep0builder.nextRecord(); } else { // all fill. } } if ( slope1!=0. || nonGap.value(i)>0 ) { start= i; } } else if ( wds.value(i)>0 ) { if ( nonGap.value(i-1)==0 && nonGap.value(i)==1 ) { start= i; end= i+1; } else { end= i+1; // end is not inclusive } } slope0= slope1; } dep0builder.putProperty( QDataSet.BINS_1, "min,maxInclusive" ); dep0builder.putProperty( QDataSet.UNITS, SemanticOps.getUnits(tds) ); DDataSet result= builder.getDataSet(); result.putProperty( QDataSet.DEPEND_0, dep0builder.getDataSet() ); result.putProperty( QDataSet.RENDER_TYPE, "eventsBar" ); return result; } /** * * @param datax data series that is aggregation of monotonic series (up and down) * @param start start index limiting search * @param end end index inclusive limiting search * @param x the value to locate. * @param guess guess index, because we are calling this repeatedly * @param dir 1 if datax is increasing, -1 if decreasing * @return index */ private static int findIndex( QDataSet datax, int start, int end, double x, int guess, int dir ) { int index= Math.max( Math.min( guess, end-1 ), start ); if ( dir > 0 ) { while ( index<end && datax.value(index+1) < x ) index++; while ( index>start && datax.value(index) > x ) index--; } else { while ( index<end && datax.value(index+1) > x ) index++; while ( index>start && datax.value(index) < x ) index--; } return index; } /** * this is probably old and shouldn't be used. * @param lds * @param zds * @param start * @param end * @param col * @param lgrid * @param ds */ private static void interpolate( QDataSet lds, QDataSet zds, int start, int end, int col, QDataSet lgrid, DDataSet ds ) { Units u= SemanticOps.getUnits( ds ); double fill= u.getFillDouble(); ds.putProperty( QDataSet.FILL_VALUE, fill ); if ( ! u.equals( SemanticOps.getUnits( zds ) ) ) { throw new IllegalArgumentException("zds units must be the same as ds units!"); } QDataSet wds= Ops.valid(zds); int index; int dir= (int) Math.signum( lds.value(end) - lds.value( start ) ); if ( dir > 0 ) index= start; else index= end; for ( int i=0; i<lgrid.length(); i++ ) { double ll= lgrid.value(i); index= findIndex( lds, start, end, ll, index, dir ); double alpha= ( ll - lds.value(index) ) / ( lds.value(index+1) - lds.value(index) ); if ( alpha < 0 ) { ds.putValue( col, i, fill ); } else if ( alpha > 1 ) { ds.putValue( col, i, fill ); } else if ( alpha == 0 ) { ds.putValue( col, i, zds.value(index) ); } else { if ( ( wds.value(index)==0 ) || wds.value( index+1 )==0 ) { ds.putValue( col, i, fill ); } else { ds.putValue( col, i, zds.value(index) * ( 1.0 - alpha ) + zds.value(index+1) * alpha ); } } } } private static double guessCadence( QDataSet xds, final int skip ) { double cadence = 0; // calculate average cadence for consistent points. Preload to avoid extra branch. double cadenceS= 0; int cadenceN= 1; for ( int i=skip; i < xds.length(); i++) { double cadenceAvg; cadenceAvg= cadenceS/cadenceN; cadence = xds.value(i) - xds.value(i-skip); if ( cadence > 1.5 * cadenceAvg) { cadenceS= cadence; cadenceN= 1; } else if ( cadence < 1.5 * cadenceAvg ) { cadenceS+= cadence; cadenceN+= 1; } } return cadenceS/cadenceN; } /** * rebin the datasets to rank 2 dataset ( time, LShell ), by interpolating along sweeps. This * dataset has the property "sweeps", which is a dataset that indexes the input datasets. * @param lds rank 1 dataset of length N * @param zds rank 1 dataset of length N, indexed along with <tt>lds</tt> * @param lgrid rank 1 dataset indicating the dim 1 tags for the result dataset. * @return a rank 2 dataset, with one column per sweep, interpolated to <tt>lgrid</tt> */ public static QDataSet rebin( QDataSet lds, QDataSet zds, QDataSet lgrid ) { return rebin( lds, zds, lgrid, 0 ); } /** * alternate, convenient interface which where tlz is a bundle of buckshot data (T,L,Z) * * @param tlz x,y,z (T,L,Z) bundle of Z values collected along inward and outward sweeps of L in time. * @param lgrid desired uniform grid of L values. * @param dir =1 increasing (outward) only, =-1 decreasing (inward) only, 0 both. * @return a rank 2 dataset, with one column per sweep, interpolated to <tt>lgrid</tt> */ public static QDataSet rebin( QDataSet tlz, QDataSet lgrid, int dir ) { QDataSet lds= Ops.link( Ops.slice1(tlz,0), Ops.slice1(tlz,1) ); QDataSet zds= Ops.slice1(tlz,2); return rebin( lds, zds, lgrid, dir ); } /** * alternate algorithm following Brian Larson's algorithm that rebin the datasets to rank 2 dataset ( time, LShell ), by interpolating along sweeps. This * dataset has the property "sweeps", which is a dataset that indexes the input datasets. * @param lds The L values corresponding to y axis position, which should be a function of time. * @param tt The Time values corresponding to x axis position. If null, then use lds.property(QDataSet.DEPEND_0). * @param zds the Z values corresponding to the parameter we wish to organize * @param tspace rank 0 cadence, such as dataset('9 hr') * @param lgrid rank 1 data is the grid points, such as linspace( 2.,8.,30 ) * @param dir =1 increasing (outward) only, =-1 decreasing (inward) only, 0 both * @return a rank 2 dataset, with one column per sweep, interpolated to <tt>lgrid</tt> */ public static QDataSet rebin( QDataSet tt, QDataSet lds, QDataSet zds, QDataSet tspace, QDataSet lgrid, int dir ) { final QDataSet sweeps= identifySweeps( lds, dir ); if ( tt==null ) { tt= (QDataSet) lds.property(QDataSet.DEPEND_0); } Units tu= SemanticOps.getUnits(tt); Number fill= (Number) zds.property( QDataSet.FILL_VALUE ); double dfill= fill==null ? -1e31 : fill.doubleValue(); QDataSet wds= DataSetUtil.weightsDataSet(zds); int ny= lgrid.length(); double[] ss= new double[ny]; double[] nn= new double[ny]; DataSetBuilder builder= new DataSetBuilder( 2, 100, ny ); DataSetBuilder tbuilder= new DataSetBuilder( 1, 100 ); tbuilder.putProperty( QDataSet.UNITS, tu ); builder.putProperty( QDataSet.FILL_VALUE,dfill ); int ix=-1; double nextx= Double.MAX_VALUE; double dt= DataSetUtil.asDatum( tspace ).doubleValue( tu.getOffsetUnits() ); double t0= -1; double dg= lgrid.value(1)-lgrid.value(0); double g0= lgrid.value(0); int n= ny-1; for ( int i=2; i<n; i++ ) { //if ( (lgrid.value(i)-lgrid.value(i-1)/dg ) throw new IllegalArgumentException( "lgrid must be uniform linear" ); } for ( int i=0; i<sweeps.length(); i++ ) { int ist= (int)sweeps.value(i,0); int ien= (int)sweeps.value(i,1); for ( int j= ist; j<ien; j++ ) { if ( ix==-1 || tt.value(j)-nextx >= 0 ) { //reset the accumulators nextx= dt * Math.ceil( tt.value(j) / dt ); // next threshold if ( ix>-1 ) { for ( int k=0; k<ny; k++ ) { if ( nn[k]==0 ) { builder.putValue( -1, k, dfill ); } else { builder.putValue( -1, k, ss[k]/nn[k] ); } } builder.nextRecord(); tbuilder.putValue( -1, t0-dt/2 ); tbuilder.nextRecord(); } t0= nextx; for ( int k=0; k<ny; k++ ) { ss[k]=0; nn[k]=0; } ix++; } int iy= (int)Math.floor( ( lds.value(j) - g0 ) / dg ); if ( iy>=0 && iy<ny ) { double w= wds.value(j); ss[iy]+= w*zds.value(j); nn[iy]+= w; } } } DDataSet result= builder.getDataSet(); result.putProperty(QDataSet.DEPEND_0,tbuilder.getDataSet()); result.putProperty(QDataSet.DEPEND_1,lgrid); DataSetUtil.copyDimensionProperties( zds, result ); String title= (String) result.property( QDataSet.TITLE ); if ( title==null ) title=""; if ( dir==-1 ) { title+= "!cinward"; } else if ( dir==1 ) { title+= "!coutward"; } result.putProperty( QDataSet.TITLE, title ); result.putProperty( QDataSet.FILL_VALUE, dfill ); return result; } /** * rebin the datasets to rank 2 dataset ( time, LShell ), by interpolating along sweeps. This * dataset has the property "sweeps", which is a dataset that indexes the input datasets. * @param lds rank 1 dataset of length N * @param zds rank 1 dataset of length N, indexed along with <tt>lds</tt> * @param lgrid rank 1 dataset indicating the dim 1 tags for the result dataset. * @param dir =1 increasing (outward) only, =-1 decreasing (inward) only, 0 both * @return a rank 2 dataset, with one column per sweep, interpolated to <tt>lgrid</tt> */ public static QDataSet rebin( QDataSet lds, QDataSet zds, QDataSet lgrid, int dir ) { final QDataSet sweeps= identifySweeps( lds, dir ); DDataSet result= DDataSet.createRank2( sweeps.length(), lgrid.length() ); result.putProperty( QDataSet.UNITS, zds.property( QDataSet.UNITS ) ); for ( int i=0; i<sweeps.length(); i++ ) { interpolate( lds, zds, (int) sweeps.value( i,0 ), (int) sweeps.value( i,1 ), i, lgrid, result ); } DDataSet xtags= DDataSet.createRank2( sweeps.length(), 2 ); QDataSet dep0= (QDataSet) lds.property(QDataSet.DEPEND_0); if ( dep0!=null ) { for ( int i=0; i<sweeps.length(); i++ ) { xtags.putValue( i,0,dep0.value( (int)sweeps.value( i,0 ) ) ); xtags.putValue( i,1,dep0.value( (int)sweeps.value( i,1 ) ) ); } DataSetUtil.putProperties( DataSetUtil.getDimensionProperties(dep0,null), xtags ); Units xunits= SemanticOps.getUnits(dep0); xtags.putProperty( QDataSet.UNITS, xunits ); xtags.putProperty( QDataSet.BINS_1, QDataSet.VALUE_BINS_MIN_MAX ); xtags.putProperty(QDataSet.MONOTONIC, org.das2.qds.DataSetUtil.isMonotonic(dep0) ); } else { for ( int i=0; i<sweeps.length(); i++ ) { xtags.putValue( i,0, sweeps.value( i,0 ) ); xtags.putValue( i,1, sweeps.value( i,1 ) ); } } Map<String,Object> userProps= new LinkedHashMap(); userProps.put(USER_PROP_SWEEPS, sweeps); result.putProperty( QDataSet.USER_PROPERTIES, userProps ); if ( lgrid.property(QDataSet.UNITS)==null ) { ArrayDataSet lgridCopy= ArrayDataSet.copy(lgrid); // often linspace( 4, 10, 30 ) is used to specify locations. Go ahead and copy over units. Units u= (Units) lds.property( QDataSet.UNITS ); if ( u!=null ) lgridCopy.putProperty( QDataSet.UNITS, u ); lgrid= lgridCopy; } result.putProperty( QDataSet.DEPEND_1, lgrid ); result.putProperty( QDataSet.DEPEND_0, xtags ); DataSetUtil.putProperties( DataSetUtil.getDimensionProperties( zds, null ), result ); return result; } }
autoplot/app
QDataSet/src/org/das2/qds/util/LSpec.java
Java
gpl-2.0
16,160
//{{COMPONENT_IMPORT_STMTS package MetaRepos; import java.util.Enumeration; import java.util.Vector; import versata.common.*; import versata.common.vstrace.*; import versata.vls.*; import java.util.*; import java.math.*; import versata.vls.cache.*; //END_COMPONENT_IMPORT_STMTS}} /* ** Activity */ //{{COMPONENT_RULES_CLASS_DECL public class ActivityImpl extends ActivityBaseImpl //END_COMPONENT_RULES_CLASS_DECL}} { //{{COMP_CLASS_CTOR public ActivityImpl (){ super(); } public ActivityImpl(Session session, boolean makeDefaults) { super(session, makeDefaults); //END_COMP_CLASS_CTOR}} } //{{EVENT_CODE //END_EVENT_CODE}} public void addListeners() { //{{EVENT_ADD_LISTENERS //END_EVENT_ADD_LISTENERS}} } //{{COMPONENT_RULES public static ActivityImpl getNewObject(Session session, boolean makeDefaults) { return new ActivityImpl(session, makeDefaults); } //END_COMPONENT_RULES}} }
tylerm007/MetaRepos
Source/VLS/DataObjects/WorkFlow/ActivityImpl.java
Java
gpl-2.0
947